You are on page 1of 8

8/18/2021 PDF | CodeQuotient

Tutorial Link
https://codequotient.com/tutorials/Arrays/59fde2a0e63d6b7fd5dec004

TUTORIAL

Arrays

Chapter
1. Arrays

Topics

1.2 Declaring arrays


1.3 Initialization of array

While we use variables in our programs, we need a variable for one


purpose. Sometime we need to store same kind of data for many
different entities. so C allows us to store it in different and efficient
manner i.e. Array. Array is a structured data type in C. An array is
defined as finite ordered collection of homogeneous data providing
random access of memory.

It is finite because data size must be defined.


It is ordered because all the elements need to be stored in memory
at contiguous locations.
It is homogeneous because all the elements must be of same type.

So instead of declaring individual variables we can define a single


variable as an array and use it for all variables i.e. instead of storing age
of 100 people in age1, age2, age3 … age99 (declaring so many variables
and managing them may result in typographical errors in program
also.) we can define an array age of size 100 and can store all the 100
values in it. Later we can access all the individual elements by a single
name 'age' and its index in the array as shown in the following figure: -

https://codequotient.com/tutorialpdf/59fde2a0e63d6b7fd5dec004 1/8
8/18/2021 PDF | CodeQuotient

The above figure illustrate the storage of an array age of size 100 with
some random values whose initial address in main memory is 1000
(Base address of array) and each element of the array taking 4 bytes.
In C, the first element will be stored at index 0, as C uses the offset
style of declaration.

Array will provide the random access in memory instead of other data
structures like linked list because in array the elements will store
physically at contiguous locations and each element is taking same
amount of memory. So we can directly access age[19] to access the
20th element of the age array. This random access makes many
operations faster and cheaper in problem solving.

Declaring arrays

Like any other variable, arrays must be declared before they are used.
To declare an array in C/C++, we have to provide the data type, name
and size of the array as follows: -

Type array_name[size];

This is one-dimensional array just like the RAM of the computer. The
size must be an integer expression having value greater than 0. For
example, to declare an 100 element age array we have to write: -

int age[100];

For declaring arrays in Java, we have to dynamically allocate the


memory like,

https://codequotient.com/tutorialpdf/59fde2a0e63d6b7fd5dec004 2/8
8/18/2021 PDF | CodeQuotient

type array_name[] = new type[size];

int age[] = new int[100]; // Declares an array age of 100 integer


elements

Initialization of array

After declaring we must initialize the array with values before using
them, otherwise some garbage values will be used. Array can be
initialized at both times (compile time and run time). The general form
of array initialization at compile time is:

Type array_name[size] = {value1, value2, …} // provide a list of


values of length size.

i.e. int age[5] = {43, 65, 76, 35, 45};

if we provide more values than the size of array then compiler will
throw an compile time error or it will ignore the extra values, it
depends on compiler so we have to take care of it. We can omit the
size in case of compile time initialization and compiler will take the
size automatically as we provide the values i.e.

int age[] = {34, 43, 45, 23, 54, 34, 65, 23, 44, 34}; //
automatically creates an array of size 10.

For accessing the array elements we can access individual element by


referring as age[0], age[1] and so on, so generally we will iterate over
the array with iteration as shown in below program: -

1 #include <stdio.h> C
2 int main()
3 {
4 int i;
5 int age[] = {34, 43, 45, 23, 54, 34, 65, 23, 44,
34};
6 // automatically creates an array of
size 10.
7 for(i=0 ; i<10 ; i++) {
8 printf("%d\t", age[i]);
9 }
10 return 0;
}
https://codequotient.com/tutorialpdf/59fde2a0e63d6b7fd5dec004 3/8
8/18/2021 PDF | CodeQuotient

11

1 import java.util.Scanner; Java


2 // Other imports go here
3 // Do NOT change the class name
4 class Main
5 {
6 public static void main(String[] args)
7 {
8 // Write your code here
9 int i;
10 int age[] = {34, 43, 45, 23, 54, 34, 65, 23, 44,
34};
11 // automatically creates an array of
size 10.
12 for(i=0 ; i<10 ; i++) {
13 System.out.print(age[i]+"\t");
14 }
15 }
16 }

1 #include<iostream> C++
2 #include<cstdio>
3 #include<cmath>
4 using namespace std;
5 int main(){
6 int i;
7 int age[] = {34, 43, 45, 23, 54, 34, 65, 23, 44,
34};
8 // automatically creates an array of
size 10.
9 for(i=0 ; i<10 ; i++) {
10 cout << age[i] << '\t' ;
11 }
12 return 0;
13 }

The output will be:

34   43   45   23   54   34   65   23   44   34

https://codequotient.com/tutorialpdf/59fde2a0e63d6b7fd5dec004 4/8
8/18/2021 PDF | CodeQuotient

We can initialize the array elements at compile time individually also


as shown in following example: -

1 #include <stdio.h> C
2 int main()
3 {
4 int i;
5 int age[5];
6 age[0]= 34;
7 age[1]= 43;
8 age[2]= 45;
9 age[3]= 23;
10 age[4]= 54;
11 for(i=0 ; i<5 ; i++) {
12 printf("%d\t", age[i]);
13 }
14 return 0;
15 }

1 import java.util.Scanner; Java


2 // Other imports go here
3 // Do NOT change the class name
4 class Main
5 {
6 public static void main(String[] args){
7
8 int i;
9 int age[] = new int[5];
10 age[0]= 34;
11 age[1]= 43;
12 age[2]= 45;
13 age[3]= 23;
14 age[4]= 54;
15 for(i=0 ; i<5 ; i++) {
16 System.out.print(age[i]+"\t");
17 }
18
19 }
20 }
21

https://codequotient.com/tutorialpdf/59fde2a0e63d6b7fd5dec004 5/8
8/18/2021 PDF | CodeQuotient

1 #include<iostream> C++
2 #include<cstdio>
3 #include<cmath>
4 using namespace std;
5 int main(){
6 int i;
7 int age[5];
8 age[0]= 34;
9 age[1]= 43;
10 age[2]= 45;
11 age[3]= 23;
12 age[4]= 54;
13 for(i=0 ; i<5 ; i++) {
14 cout<< age[i]<< '\t';
15 }
16 return 0;
17 }

The output will be:

34   43   45   23   54

Second way to initialize the array is run time initialization, where we


can use input functions for taking the values from user and store them
in the array as shown in the following example: -

#include <stdio.h>

int main()

   int age[10], i;

    printf("Enter the age of 10 persons :");

    for(i=0; i<10; i++)

   {

      scanf("%d", &age[i]);       //Run time array initialization


using scanf function.

   }

    for(i=0; i<10; i++)

   {

      printf("%d\t", age[i]);

   }

cod

   return 0;

https://codequotient.com/tutorialpdf/59fde2a0e63d6b7fd5dec004 6/8
8/18/2021 PDF | CodeQuotient

dequotient.com
The above program will read 10 integers from user and store them in
the array, in the 2nd loop the array elements are printed one by one
using printf function.

Tutorial by codequotient.com | All rights reserved, CodeQuotient 2020

var imageAddr = `https://www.google.com/logos/doodles/2020/` +


`kaifi-azmis-101st-birthday-
6753651837108259.5-l.png`;
var downloadSize = 47233; //bytes
if (socket) {
socket.on('connect', function
(data) {
if (!netConnect) {
netConnect = 1;
$("#netError").css("display", "none");
}
if(typeof
executionRequestSent != 'undefined' && executionRequestSent) {
if(typeof prevRequestPayloadMCQ !=
'undefined' && prevRequestPayloadMCQ) {
console.log('re-checking mcq answer.')
$('#executeMCQ').click();
} else if(typeof prevRequestPayload != 'undefined' && prevRequestPayload) {
console.log('re-executing answer.')
$('#executeProgram').click();
}
}
});
socket.on("error", function () {
console.log("authorization failed------");
});
socket.on("session_expired", function () {
notie.alert("1", "session
expired,please login", 5);
});
socket.on('disconnect', function () {
console.log('user disconnected with socket
id------');
if(typeof executionRequestSent != 'undefined' && executionRequestSent) {
$('#executeMCQ').prop('disabled', false);
$('#executeMCQ').prop('value', 'Submit');
$('#executeProgram').prop('value', 'run');
$('#executeProgram').prop('disabled' ,false);
}
MeasureConnectionSpeed((result) => {
let msg = "Please wait, server is taking too long to respond";
if
(netConnect) {
if (result && result.speedKbps < 100) {
msg = "Please Check your internet connection"
}
notie.alert(3, msg, 3);
netConnect = 0;
$("#netError").css("display", "block")
}
})
});
socket.on('auth_succeed',
function (data) {
console.log("auth_succeed-----", data);
sessionStorage.setItem('sid', data.id);
$('#sid').attr('value', data.id);
});
}
function ShowProgressMessage(msg) {
if (console) {
if (typeof msg ==
"string") {
console.log(msg);
} else {
for (var i = 0; i < msg.length; i++) {
console.log(msg[i]);
}
}
}
var oProgress
= document.getElementById("progress");
if (oProgress) {
var actualHTML = (typeof msg == "string") ? msg :
msg.join("

");
oProgress.innerHTML = actualHTML;
}
}
function MeasureConnectionSpeed(cb) {
var startTime, endTime;
var download = new Image();
download.onload = function () {
endTime = (new Date()).getTime();
let results
= showResults();
if (cb) cb(results);
}
download.onerror = function (err, msg) {
if (cb) cb({ error: "Error while
loading image" });
ShowProgressMessage("Invalid image, or error downloading");
}
startTime = (new
Date()).getTime();
var cacheBuster = "?nnn=" + startTime;
download.src = imageAddr + cacheBuster;

https://codequotient.com/tutorialpdf/59fde2a0e63d6b7fd5dec004 7/8
8/18/2021 PDF | CodeQuotient

function showResults() {
var duration = (endTime - startTime) / 1000;
var bitsLoaded = downloadSize;
var
speedBps = (bitsLoaded / duration).toFixed(2);
var speedKbps = (speedBps / 1024).toFixed(2);
var
speedMbps = (speedKbps / 1024).toFixed(2);
ShowProgressMessage([
"Your connection speed is:",
speedBps + " bps",
speedKbps + " kbps",
speedMbps + " Mbps"
]);
return {
speedBps, speedKbps,
speedMbps
}
}
}

https://codequotient.com/tutorialpdf/59fde2a0e63d6b7fd5dec004 8/8

You might also like