1
CSC099:
FOUNDATION COMPUTING II
CHAPTER 7 -
ARRAY
PART
Declaring Arrays
Concept of Arrays
I
Input, Output of an array
Exchanging elements of an array
Application in Array
String
Prepared by: Zaid Mujaiyid Putra Ahmad Baidowi
Learning Outcomes
2
At the end of this lesson, students should
be able:
To describe the concept of ARRAY.
To declare, initialize and access an ARRAY.
To get inputs, display results and assign
values by using ARRAY.
To use string in conjunction with ARRAY.
Why should we use array?
3
#include<stdio.h>
int main() {
int mark1, mark2, mark3, sum, The inputs are
average; all marks.
printf("Enter mark 1: ");
scanf("%d", &mark1); Can be associated
printf("Enter mark 2: "); in one group of
scanf("%d", &mark2); name marks
printf("Enter mark 3: ");
scanf("%d", &mark3);
sum = mark1+ mark2+ mark3;
average = sum/3;
printf("\nSum = %d", sum);
printf("\nAverage = %f ",
average);
Using Array…..
4
Normal Way Using Array
#include<stdio.h> #include<stdio.h>
int main() int main()
{ {
int mark1, mark2, mark3, sum, int mark[3], sum=0, average, i;
average;
for (i=0; i<3; i++)
printf("Enter mark 1: "); {
scanf("%d", &mark1);
printf("Enter mark 2: ");
scanf("%d", &mark2);
printf("Enter mark 3: ");
scanf("%d", &mark3);
sum = mark1+ mark2+ mark3; }
average = sum/3;
printf("\nSum = %d", sum);
printf("\nAverage = %d ", average);
printf("\nSum = %d", sum);
return 0; printf("\nAverage = %d ", average);
}
return 0;
}
Array Structures
5
An array:
is a sequenced collection of
elements/related data items of the same
name and the same type.
serves as an example of structured data types
- they are effectively just lists of variables all of
the same data type ("int", "char" or whatever).
Arrays are “static” entities in that
they remain the same size throughout
program execution.
Array Structures
6
Specify the name of the array and the position
number (subscript) of the particular element in
the array.
E.g : marks[1]
Loops can be used to:
read and write the elements in arrays
add, subtract, multiply and divide the elements in arrays
The subscript / index starts with 0, and thus, in
general the i-th element of an array is (i-th)
E.g :
1st element of number array referred to number[0]
2nd element of number array referred to number[1]
3rd element of number array referred to number[2]
Using arrays in C
7
Difference between:
a. 7th element
b. Array element 7
8
Read or Print
using index
Example of an array flowchart
concepts :
getting
9
input,
displaying
content and
Syntax: Array Declaration
10
Syntax
component_type identifier_name[size];
Declaration and definition tells the compiler the name of
the array, type of each element and size or number of
element in the array to be reserved in the memory.
Example
float studentsCGPA[40];
Let say we are going to keep CGPA of 40 students in our
class.
Thus, we need an array of the mentioned size (i.e: 40) to
store the value of CGPA.
Example: Array Declaration
11
double price[5]; float marks[20];
Syntax: Array Initialization
12
Syntax
component_type identifier
name[sizeOfTheArray] = {list_of_values;
equals_to_the_size_of_the_array,
separated_by_comma}
Example
Array Initialization: Different
13
Ways
Basic Initialization
int number[5] = {3, 6, 9, without Size
12, 15}; int number[ ] = {3, 6, 9};
Partial Initialization Initialization All to
int number[5] = {3, 6}; Zeros
int numbers[100] = {0};
How to input an array?
14
int score[3];
for (i=0; i<3; i++)
score[i]=0;
int mark[3];
for (i=0; i<3; i++)
{
printf("Enter mark [%d] : ",i);
scanf("%d", &mark[i]);
** NOTE :
The & is used to provide scanf with a variable’s
location in memory so that a value can be stored
there.
How to display the content of an array?
15
for (i=0; i<3; i++)
printf("\nElement [%d], the value is %d ",i, score[i]);
for (i=0; i<3; i++)
printf("\nElement [%d], the value is %d ",i, mark[i]);
** NOTE :
Usually done by using a for loop.
How to assign values into
16
array?
Wrong
int mark[3] = {10,20,30}, new_mark[3]; Way !!!
new_mark = mark; // copy all elements from mark to mark_new
** NOTE :
values can be assigned by using assignment
operator
Correct Way
int mark[3] = {10,20,30}, new_mark[3];
int i;
for(i=0; i<3; i++)
Test Your Understanding 1
17
Write a statement as stated below:
1. Declare an array name age with
element type integer and the size is 5
2. Initialize the array age to 17, 18, 19, 20
and 21
3. Display the content of the array age
4. Assign the array into a new array name
student_age
18
String
String (Characters in Array)
19
String/Character Array : An array whose components
are of type char.
Texts are examples of string : ”Hello there!”, ”UiTM”, etc.
From the definition of string there is a difference between
’A’ and ”A”.
The first one is character A; the second one is string A.
A string such as “Hello" is really a static array of
individual characters in C.
String (Characters in Array)
20
To store ’A’ , we need only one memory cell of type
char.
To store ”A”, we need two memory cells of type char;
one for ’A’ and one for ’\0’. (string – has extra memory
location for delimiter)
All String in C ends with null terminated. In C, the null
character is represented by ’\0, called delimiter, which is
nonprintable. Therefore ”A” represents two character : ’A’
and ’\0’.
Difference between ‘A’ and
21
“A”
Character of ‘A’ String of “A”
String (Characters in Array)
22
Consider the following statement:
char name [16];
It declares an array name of 16 components of type
char.
Maximum string in name is 15 elements.
If you store a string of length 10 in name,
first 11 components of name are used
last 5 are left unused.
** NOTE : A character array representing a string should
always be defined large enough to hold the number of
characters in the string and the terminating null character.
String: Initialization &
23
Declaration
Declaration Basic Initialization
Syntax Syntax
char char identifier_name[sizeOfTheArray] =
identifier_name[sizeOfTheArray]; {listOfValues; equals to the size of the array
inclusive of ‘\0’, separated by comma} ;
Example
Example
Initialization with Initialization without
Size Size
Syntax
Syntax
char identifier_name[ ] = “string”;
char identifier_name[sizeOfTheArray] =
“string”; **Note: Size of the array will be as the
length of the string plus the null
Example character (‘\0’)
Example
Getting Input String
24
Example,
char ayat[ 20 ];
Input Statement
printf(“Enter a string : ”);
scanf( "%s", ayat);
By using the conversion specifier %s , it reads a
string from the keyboard.
The name of the array is passed to scanf without
(&) unlike integer.
Getting Input String
25
Function scanf will read characters until
a space, tab, newline or end-of-file
indicator is encountered.
If the user types 20 or more characters,
your program may crash!
Advisable to use the conversion
specifier %19s so that scanf does not
write characters into memory beyond
the end of the array.
Input &Output : String Library
Functions (stdio.h)
26
Input Output Descriptions
scanf() printf() •For all input/output types
(int, float, double, char,
string)
getchar putcha •For char input/output
() r() •To input/output a single
character
gets() puts() •For string input/output
•To input/output the whole
value in a string
String Input/Output:
27
Different ways
#include <stdio.h>
#define SIZE 20
int main()
{
char message[SIZE];
printf("Enter a string : ");
return 0;
}
#include <stdio.h>
#define SIZE 20
int main()
{
char message[SIZE];
printf("Enter a string : ");
return 0;
}
String Data Manipulation
28
Manipulate Data
Moving a character – use assignment
Example: name[0]=’J’; name[1]=’o’;
name[2]=’h’; name[3]=’n’;
Moving a string – use function call to read
string.
Remember! Below is error if you are using
string to copy to a variable.
Mystring = “Hello”;
String Function
29
Manipulating string data to:
Copy string
Determine length of a string
Combine strings
Compare & search strings.
<string.h> header file MUST be
used to execute all the above
processes.
String Function - strcpy
30
To copy string : strcpy(str1, str2)
Copies str2 to str1, including the ‘\0’.
Returns str1
Can be used to replace an existing string or to initialize
a string.
Example :
char CarName1[20];
char CarName2[20]=“Honda City”;
1) strcpy(CarName1, "Toyota Camry");
printf("Car Name: %19s“, CarName1 );
Output :
2) strcpy(CarName1, CarName2);
printf("Car Name: %19s“, CarName1) ;
Output :
String Function - strlen
31
To determine length of a string :
strlen(str1)
Returns the length of str1. Exclude ‘\0’ in the
length count.
Example :
char CarName[20]=“Honda City”;
int length;
length = strlen(CarName);
printf("Car Name: %d“, length);
Output :
String Function - strcat
32
To combine strings : strcat(str1, str2)
Appends str2 (source) to the end of
str1(destination).
Returns str1
Example :
char faculty[40] = "Asasi ";
char university[20] = "UiTM, Shah Alam";
strcat(faculty, university);
printf("\n\nAfter concatenating,
%19s\n",faculty);
Output:
String Function - strcmp
33
To compare string : strcmp(str1, str2)
Compares str1 to str2. It returns
A negative value : if str1 < str2
0 : if str1 == str2
A positive value : if str1 > str2
char faculty[10] = “ASASI";
char input[10];
int i;
printf(“Enter your faculty:\n”);
gets(input);
i=strcmp(faculty, input);
if(i == 0)
{
printf(“You are from ASASI”);
}
String Comparison (strcmp)
34
Apple is less than Book
because
the first character of Apple
is less than the first
character of Book.
String Comparison (strcmp)
35
Apple is less than Ask
because:
the first character of both
strings are the same
but the second character
‘p’ of Apple is less than the
second character ‘s’ of Ask.
String Comparison (strcmp)
36
Sem is less than Semester
because:
the first three characters
of Sem and Semester are
the same
but the fourth character
of Sem which is ‘\0’ (null
character) is less than the
String Comparison (strcmp)
37
Door is less than door
because:
the first character ‘D’ of
Door is less than the first
character ‘d’ of door.
38
Test Your Understanding 2 – String
39
Write a statement of the following questions:
Declare a variable name carType. The data type
is char and contain 20 elements.
Assign “HONDA” to the carType variable.
Read an input from a user and assign into new
variable myCar.
Count the string that the user entered.
Combine the input from the user input (myCar)
to string[40]=“MyCar is ”
Compare the user input and the original data in
carType.
40
Examples of
Array
Application
Example 1: To Add Values in
Array
#include
41 <stdio.h>
int main(void)
{
int i,
//array initialization and declaration
int susun1[5]={2,4,6,8,10}, susun2[5], susun3[5];
Output :
printf(“Enter 5 numbers: ”); Enter 5 numbers:1 2 3 4 5
//input values into array
for(i=0; i<5; i++)
scanf(“%d”, &susun2[i]);
//display values from arrays
for(i=0;i<5;i++)
{
susun3[i]= susun1[i]+ susun2[i];
printf (“\nAddition of %d and %d is %d”, susun1[i], susun2[i], susun3[i]);
}
}
Example 2: To Determine the
Minimum value
42 #include <stdio.h>
int main(void)
{
int i, score[5], min; Output :
Enter 5 scores:
printf(“Enter 5 scores:\n”);
for(i=0; i<5; i++)
scanf(“%d”, &score[i]);
min = score[0];
for(i=1;i<5;i++)
{
if(score[i]< min ) The minimum score is
min = score[i];
}
printf(“\nThe lowest score is %d”, min);
}
Example 3: To Swap Values in
Array
43
WRONG !
!!
Example 3: To Swap Values in Array (cont’d)
44
CORREC
T
Example 3: To Swap Values in Array (cont’d)
45
int temp; // declare variable temp
int numbers[5] = {3,7,12,24,45}; // declare and
initialize the array numbers
temp = numbers[3];
numbers[3] = numbers[1];
numbers[1] = temp;
printf(“After exchange the value :\n“);
for(i=0; i<5; i++)
printf(“%d”, ‘ ’, numbers[i]);
Example 4: To Produce Frequency Distribution
and Histogram
46
Common statistical application using
array
Frequency distributions and histograms
Use frequency array to show number of
identical element in a series of number
Histogram shows a pictorial
representation of a frequency array
Example 4: To Produce Frequency Distribution
and Histogram (cont’d)
47
Scenario :
You were assigned to write program to calculate the
response (5-Very Difficult, 4- Difficult, 3-Moderate, 2-
Not Difficult 1-Very Not Difficult) of 10 students
regarding
Number of the difficulties of C Programming.
Students
response[9
Frequency Array Frequency Histogram
]
Very Difficult :*
Difficult :*
.. frequency[4
]
Moderate :***
.. frequency[3 Not Difficult: *
.. ]
frequency[2 Very Not Difficult :**
.. ] **
frequency[1
]
frequency[0
response[1
]
]
response[0 frequency
]
response
Example 4: To Produce Frequency Distribution
and Histogram (cont’d)
48
#include <stdio.h>
#define SIZE 10 // set the size of frequency
#define SCALE 6 // set the size of scale
int main()
{
int response[SIZE] = {1,2,1,1,2,1,3,5,4,4}; //initial values
int frequency[SCALE] = {0}; // set frequency to all zeros
int answer;
for(answer=0;answer<10;answer++) // looping for frequency
++frequency[response[answer]];// increase answer by 1 and increase response by 1
printf("Rating Frequency"); // just to display the message
int rating;
for(rating=1; rating<=SCALE-1;rating++)
printf("\n%d %10d \n", rating, frequency[rating]);
// to display the current value of rating
// and to display the value of current frequency
}
Test Your Understanding 3
49
Now, based on the previous Example 4
program,
Try your own to trace the following
statement:
for(answer=0;answer<10;ans
wer++)
+
+frequency[response[answer]
];
for(rating=1; rating<6;rating++)
Try your own
printf("\n%d to\n",
%10d trace the
rating, following
frequency[rating]);
statement
Test Your Understanding 4 : What is the
output?
50 #include <stdio.h>
int main()
{
int temp;
int numbers[5] = {3, 7, 12, 24, 25};
printf("Before exchange the value :\n");
int i;
for(i=0; i<5; i++)
printf("\nElement [%d] : %d",i, numbers[i]);
printf("\n\nStarting to exchange the value of element 1 and
element 3\n\n");
temp = numbers[3];
numbers[3] = numbers[1];
numbers[1] = temp;
printf("After exchange the value :\n");
int j;
for(j=0; j<5; j++)
printf("\nElement [%d] : %d",i, numbers[j]);
printf("\n");
}
Conclusion
51
Array of numbers vs. Array of characters
(strings)
Declare / Initialize
Input / display / swap
scanf vs. gets
String manipulation
strcpy, strlen, strcat and strcmp