0% found this document useful (0 votes)
29 views38 pages

Bitlabactivity 2

Here is the code to initialize and calculate the sum of the array value using for loops: 1. To initialize the array: int value[6]; for(int i=0; i<6; i++) { scanf("%d", &value[i]); } 2. To calculate the sum: int sum = 0; for(int i=0; i<6; i++) { sum += value[i]; } printf("Sum is %d", sum); So the full code is: #include <stdio.h> int main() { int value[6], sum=0; for(int

Uploaded by

AMAR ZAMANI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views38 pages

Bitlabactivity 2

Here is the code to initialize and calculate the sum of the array value using for loops: 1. To initialize the array: int value[6]; for(int i=0; i<6; i++) { scanf("%d", &value[i]); } 2. To calculate the sum: int sum = 0; for(int i=0; i<6; i++) { sum += value[i]; } printf("Sum is %d", sum); So the full code is: #include <stdio.h> int main() { int value[6], sum=0; for(int

Uploaded by

AMAR ZAMANI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

CHAP 6: ARRAY

Chapter : ARRAY

 One Dimensional Array  Learning objectives:


 Declaring Array  At the end of the session, student
 Array Initialization should be able to:
 Array Referencing  To understand the concept of array
as a data structure
 Sorting an Array
 To be able to declare, initialize,
 Searching an Array
and use 1- and 2-dimensional
 Two Dimensional Array array
 Two Dimensional Array Declaration  To introduce repetition structures to
 Two Dimensional Array Initialization navigate the contents of arrays.
 Two Dimensional Array Referencing
 String
 String Initialization
 String Referencing
Introduction Array is a group of memory
locations, all have the same
name & the same type.
3
What is an Array?
It is a collection of two or more adjacent memory cells,
called array elements that associated with particular
symbolic name.

Example: This array w contains 10 elements


double w[10];

Name of array (all elements of this


Position number of the element array have the same name, w)
within array w
Memory
Allocation

w[0] w[1] w[2] w[3] w[4] w[5] w[6] w[7] w[8] w[9]

70.3 48.4 52.67 56.1 54.12 50.78 63.26 68.65 74.37 73.61
Introduction(Cont..)
4
Example 1 :

To compute the average of exam score for 5 students, we need to


come up with 5 identifiers.

Declaration:

int exam_score1, exam_score2, exam_score3, exam_score4,


exam_score5;

Memory allocation :

exam_score1 exam_score2

exam_score3 exam_score4

exam_score5
before
 Using control structure
 While, do..while and for loop

int exam_score[5];
for (i=0;i<5;i++)
scanf(“%d”,&exam_score[i]);
Introduction(Cont..)
6 By using an array..
Declaration :
int exam_score[5];
array index /
Memory allocation : subscript
array name
exam_score[0]
exam_score[1]
exam_score[2]
exam_score[3]
exam_score[4]

• The array index/subscript always start with 0 not 1.


• If the array has N elements, the last element is in position N-1.
One Dimensional Array
7 • A single dimensional array

Terms :
1. Array
a collection of data items of the same name & data type.
2. Array name
name of array is an identifier.
3. Array element
maximum number that can be stored in array / size of array
4. Array subscript/Index
a value/expression enclosed in [ ] brackets after the array
name, specifying which array element to access. Must
start with 0.
Declaring Array
8 Whendeclaring arrays, we have to specify :
1. Array data type
2. Array Name
3. Number of elements

Format :

data_type array_name[ number_Of_Elements ];

Example :
int exam_score[28];

Array data type Array size / number of


Array name elements
Declaring Array (Cont..)
Another Examples :
9
i) int c[10];

ii) float myArray[ 3284 ];

iii) int a[5]; /* use a[0], a[1], .., a[4] */

iv) char b[3]; /* use b[0], b[1], b[2] */

v) float c[2] = { .1, .2};


/*initialization at declaration; c[0] = 0.1 , c[1]=0.2 */

vi) double c[3][5]; /* two dimensional array */

Declaring multiple arrays of same type :

Example:
int b[100], x[27];
char car[23], lorry[45];
float duck[3], ant[9];
Array can be initialized at :

Array Initialization 1. compile time (while declaring)


2. run time

10
1. Compile-Time Initialization of Arrays (while declaring)

 An initializer must be a constant value.


Example :
initializer array elements

int exam_score[4] = { 88, 85, 76, 91 };


4 initializers, therefore 4 array elements

 We also can declare the number of element implicitly.


Example :

first element is refer as exam_score[0]

int exam_score[ ] = {88,85,76,91}

third element is refer as exam_score[2]


Array Initialization (cont..)
11
2. Run-Time Initialization of Arrays
 An array can be initialized at run time explicitly.

Example :

a) for (int i = 0; i <= 27; i++)


exam_score[i] = 0.0;

b) for( int b = 0; b < 27; b++)


scanf(“%d”, &exam_score[b]);

• In addition, if we leave some values of initialization,


rightmost elements will become 0.

Example :

int exam_score[4] = {88,85}; --> the 2nd & 3rd element are 0

int exam_score[5] = {0};→ All elements are 0


Array Referencing
•12Each individual element is referred by specifying array name & index

Format:
arrayname[ position number ]
//output for the fragment code :
Example : //output element for index 0 = 4.05
89 element for index 1 = 3.45
element for index 2 = 3.21
(i) exam_score[0] = 89; element for index 3 = 6.55
element for index 4 = 10.23
printf( "%d", exam_score[ 0 ] );

(ii) float x[ ] = { 4.05,3.45,3.21,6.55,10.23}

for( int a = 0; a <= 4; a++)


printf( “ element for index %d = %f\n”, a, x[a]);
Array Referencing (cont..)
13

index → 0 1 2 3 4

x 4.05 3.45 3.21 6.55 10.23

x[0] x[1] x[2] x[3] x[4]

Position number of the element within array x


“array subscript”

Name of array ( all elements of this array,


have the same name, x)
Array Referencing (cont..)
14
• Manipulation Statement using array :
→ Perform operations in subscript (index)
Example :

double Mark [8];

Mark [0] Mark[1] Mark[2] Mark[3] Mark [4] Mark [5] Mark [6] Mark [7]
16.0 12.0 6.0 8.0 2.5 12.0 14.0 10.5

printf (“ %.f ”, Mark[0]);


Mark[3] =25.0;
Output ?
sum= Mark[0] + Mark[1];
sum += Mark[2];
Mark[3] += 1.0;
Mark[2] = Mark [0] + Mark [1];
printf (“ %.f %.f %.f %.f %.f”, Mark[0], Mark[1], Mark[2], Mark[3],
Sum);
 int value[6] ={ 4, 6, 8, 7, 3, 10 };

 Fill in the array with appropriate values.


15

value

[0] [1] [2] [3] [4] [5]

 Let x = 1 and y = 2, write the new value, if any for array value after execute
the following statements. (Assume that each of the operations is connected).
▪ value[x + 3] = value[5] ;
▪ value[5] = value[2 *x] + y;
▪ value[y] = value[4] + value[2 /y] ;
▪ value[0] = x * value[3];

value

[0] [1] [2] [3] [4] [5]


 int value[6] ={ 4, 6, 8, 7, 3, 10 };

 Fill in the array with appropriate values.


16

value 4 6 8 7 3 10

[0] [1] [2] [3] [4] [5]

 Let x = 1 and y = 2, write the new value, if any for array value after execute
the following statements. (Assume that each of the operations is connected).
▪ value[x + 3] = value[5] ;
▪ value[5] = value[2 *x] + y;
▪ value[y] = value[4] + value[2 /y] ;
▪ value[0] = x * value[3];

value 7 6 16 7 10 10

[0] [1] [2] [3] [4] [5]


1. Assign the value of array value by using for loop.
2. Calculate and display the sum of all value in the array. Use for loop in
17 your answer.
#include <stdio.h>
int main ()
{
int n[ 10 ]; /* n is an array of 10 integers */
int i,j,sum;

/* initialize elements of array n to 0 */


for ( i = 0; i < 5; i++){
scanf("%d", &n[i]);
}
for (i = 0; i < 5; i++) {
sum += n[i];
}
printf("%d", sum);
getch();
}
Two Dimensional Array
18
• Array of array.
• 2-D array have 2 subscripts showing the number of rows & the number
of column.

Two Dimensional Array Declaration


 Similar with 1-D declaration except it have 2 subscripts.
 Format :

data_type array_name [no_of_element1][no_of_element2]

❑ data_type : either int, float, double, char.


❑ array_name : name of array that is an identifier.
❑ no_of_element1 : size of row.
❑ no_of_element2 : size of column.
Two Dimensional Array Declaration (cont..)
19 Example :

(i) int x[10][5]; /*allocate 50 spaces (row:0-9,column:0-4)*/

(ii) float a[3][20]; /*allocate 60 spaces (row:0-2,column:0-19)*/

(iii) int exam_score[3][4]; /*allocate 12 spaces


(row:0-2,column:0-3)*/
Two Dimensional Array Declaration (cont..)
20
Example :
int exam_score[3][4];

row [0] to row[2] column [0] to column[3]

column1 column2 column3 column4

row1 exam_score[0][0] exam_score[0][1] exam_score[0][2] exam_score[0][3]


row2 exam_score[1][0] exam_score[1][1] exam_score[1][2] exam_score[1][3]
row3 exam_score[2][0] exam_score[2][1] exam_score[2][2] exam_score[2][3]

array name row subscript column subscript


Two Dimensional Array Declaration (cont..)

21
The right index of an array is increased first before the left index.
 Example :
int exam_score[3][4]={70,80,90,72,82,92,71,81,91,67,78,98 };

exam_score[0][0] 70
exam_score[0][1] 80
exam_score[0][2] 90
exam_score[0][3]
72
exam_score[1][0]
82
exam_score[1][1]
exam_score[1][2] 92

exam_score[1][3] 71
exam_score[2][0] 81
exam_score[2][1] 91
exam_score[2][2] 67
exam_score[2][3] 78
98
Two Dimensional Array Initialization
22
2-D array can be initialized at :
1. compile time (while declaring)
2. run time

1. Compile-Time Initialization of Arrays (while declaring)

Example :

(i) int exam_score[3][4]={70,80,90,72,82,92,71,81,91,67,78,98};

 The best way : nest the data in braces to show the exact nature of the array.

Example :

(ii) int exam_score[3][4]={{70,80,90,72},{82,92,71,81},{91,67,78,98}};


Two Dimensional Array Initialization (cont..)

23 We also can declare the far left dimension size implicitly.
Example :
(iii) int exam_score[ ][4] =
{{70,80,90,72},{82,92,71,81},{91,67,78,98}};

 If we leave some values out of each row, compiler initialize them to 0.


Example :
(iv) int exam_score[3][4]={{70,80},{82,92,71},{91,67,78,98}};

[0][0] 70 [0][1] 80 [0][2] 0 [0][3] 0


[1][0] 82 [1][1] 92 [1][2] 71 [1][3] 0
[2][0] 91 [2][1] 67 [2][2] 78 [2][3] 98
Two Dimensional Array Initialization (cont..)
24 2. Run-Time Initialization of Arrays
Example :
row column value
int exam_score[3][4]; //array 3x4
0 0

 can be initialized by nested for loops. 1


 The 1st loop varies the row from 0 - 2. 2
 The 2nd loop varies the column from 0 - 3. 3
1 0
for (row=0;row<3;row++) 1
:
for(column=0; column<4; column++)
scanf(“%d”,&exam_score[row][column]);
//end of inner for
//end of outer for
 TRY: Trace the source code flow using trace table..
Two Dimensional Array Referencing
25
 by specifying array name, its row and column index

 Can access elements in array, using nested for .

 Example:
exam_score[0][2] = 99;
exam_score[1][4] = exam_score[0][3] + 10;
Two Dimensional Array Referencing
26
(cont..)
Example Program //Program Output
[0][0] = 71
#include<stdio.h> [0][1] = 81
void main( ) { [0][2] = 91
int [0][3] = 73
exam_score[3][4]={{70,80,90,72}, [1][0] = 83
{82,92,71,81},{91,67,78,98}}; [1][1] = 93
for(int row=0; row<3; row++) [1][2] = 72
{ [1][3] = 82
for(int column=0; column<4; [2][0] = 92
column++){ [2][1] = 68
exam_score[row][column]= [2][2] = 79
exam_score[row][column]+1; [2][3] = 99
printf("[%d][%d] = %d\n",

row,column,exam_score[row][
column]);
}
}
}
Exercise
27

int marks[3][5]={80, 90, 96, 73, 65, 67, 90, 68, 92, 84, 70, 55, 95, 78,
100};

Give the value for the following statements


marks[2][3];
marks[2][4];
marks[0][1];
String
28

 String is a grouping of characters.

 C implements the string data structure using arrays of char type.

 include letters, digits and special characters (*, /, $).

 A string constant is a sequence of characters which is enclosed by double


quotation marks (“ ”).
String (cont..)
29  We can declare a string variable as a 1-D character array.

 Example :
char college[15];
character array college can store a string from 0 to 14.

 A string always ended by a null character (‘\0’)

 Example :
char college[11]=“FSKTM UTHM”;

F S K T M U T H M \0
String Initialization
30  can initialize string variables at compile-time.

 many type of expressions:

(a) a string
char college[11]={‘K’,‘U’,‘i’,‘T’,‘T’,‘H’,‘O’, ‘ ’,‘B’,‘P’,‘\0’};

(b) a string with a size of array


char college[11]=“KUiTTHO BP”;

(c) a string without a size of array


char college[ ]=“KUiTTHO BP”;
or
char college[ ]={‘K’,‘U’,‘i’,‘T’,‘T’,‘H’,‘O’, ‘ ’,‘B’,‘P’,‘\0’};
String Referencing
31  can use scanf and %s, for input of a string variables.
Example :
scanf(“%s”,string_var);

 use fscanf and %s for file-oriented input of string variables.

 If the string to be input has embedded whitespace characters, we can resort to


the standard gets function.
Example :
gets(string_var);

 use printf and %s and function fprintf for file-oriented output of string
variables.

 puts and putchar function also can be used to display string.


String Referencing (cont..)
32 Example :
char string1[ ] = "first";

 string1 actually has 6 elements.

 equivalent to

char string1[ ] = {'f','i','r','s','t','\0' };

 Can access individual characters


string1[3] is character ‘s’.

 Array name is address of array, so ‘&’ sign is not needed for scanf.
scanf( "%s", string2 );

 reads characters until whitespace encountered


String Referencing (cont..)
33

Example Program
/* Treating character arrays as strings using
//Program Output
scanf*/
#include <stdio.h>
Enter a string: Good
int main() { Luck
char string1[20], string2[] = "string literal";
int i;
string1 is: Good
printf("Enter a string: "); string2 is: string literal
scanf( "%s", string1 );
printf("string1 is: %s\nstring2 is: string1 with spaces
%s\n",string1,string2);
printf("string1 with spaces between
between characters is:
characters is:\n"); Good
for ( i = 0; string1[ i ] != '\0'; i++ )
printf( "%c ", string1[ i ] );
printf( "\n" );
return 0;
}
String Referencing (cont..)
34

Example Program //Program Output


/* Treating character arrays as strings using Enter a string: Good Luck
gets*/ string1 is: Good Luck
#include <stdio.h> string2 is: string literal
int main() { string1 with spaces between characters is:
char string1[20], string2[] = "string literal"; Good Luck
int i;
printf("Enter a string: ");
gets(string1);
printf("string1 is: %s\nstring2 is:
%s\n",string1,string2);
printf("string1 with spaces between characters
is:\n");

for ( i = 0; string1[ i ] != '\0'; i++ )


printf( "%c ", string1[ i ] );
printf( "\n" );
return 0;
}
Exercise
35

1. What will be the values of k[1] and k[3] after execution of


the code segment below using the data shown?
int k[6] = {0, 0, 0, 0, 0, 0};
int i, n;
for (i = 3; i < 6; ++i)
{
scanf("%d", &n);
k[n] = i;
}
Data: 2 0 1
Exercise
1. Declare a character based array called letters of ten 7. Assign the text string "Welcome" to the character
elements based array stuff (not at declaration time)

2. Assign the character value 'Z' to the fourth element of 8. Use a printf statement to print out the third element
the letters array of an integer array called totals

3. Use a for loop to total the contents of an integer array 9. Use a printf statement to print out the contents of the
called numbers which has five elements. Store the character array called words
result in an integer called total.

10. Use a scanf statement to read a string of


4. Declare a multidimensioned array of floats called characters into the array words.
balances having three rows and five columns.

11. Write a for loop which will read five characters


5. Write a for loop to total the contents of the (use scanf) and deposit them into the character
multidimensioned float array balances. based array words, beginning at element 0.

6. Assign the text string "Hello" to the character based


array words at declaration time.
Home Exercise
37

2. Answer the following questions regarding an array called fractions


a) Define a symbolic constant SIZE to be replaced with the replacement text 10.
b) Define an array with SIZE elements of type float and initialize the elements to
0.
c) Name the fourth element from the beginning of the array.
d) Refer to array element 4.
e) Assign the value 1.6 to array element nine.
f) Assign the value 3.3 to the seventh element of the array.
g) Print array elements 6 and 9 with two digits of precision to the right of the decimal
point, and show the output that is displayed on the screen.
h) Print all the elements of the array, using a for repetition statement. Assume the
integer variable x has been defined as a control variable for the loop. Show the
output.
Next Chapter : 7
STRUCTURE AND POINTER (4 HOURS)
7.1 Pointer and string
7.2 Structure and pointer
7.3 Nested structure
7.4 Array and structure

You might also like