







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A program is a precise sequence of steps to solve a particular problem. This course includes basic programming structure like loops, operator, memory allocation, reference, pointers etc. It teaches how to be a good programmer. This lecture handout is about: Introduction, Arrays, Initialization, Copying, Linear, Search, Keyword, Sample, Program, Functions, Data, Types, Function, oriented
Typology: Study notes
1 / 13
This page cannot be seen from the preview
Don't miss anything!








D eitel & Deitel - C++ How to Program chapter 4 4.2, 4.3, 4.
rrays Linear Search
Introduction Arrays Initialization of Arrays Sample Program 1 Copying A
The Keyword ‘const’ Tips
docsity.com
writing functions, which will become a part of our every program. As , so we will be dealing with too many programming toolkit is almost complete but still a very important omponent is missing. We are going to discuss this component i.e. Arrays in this
t, en sum up all the ges and divide this with 10 to get the average age. Suppose, we have 100 students ch student’s age. Is there ny other way to deal with this problem? Arrays are possible solution to the problem.
rray is a special data-type. If we have a collection of data of same type as in the case in ther
n C language, every array has a data type i.e. name and size. Data type can be any ing convention apply to array names. The ze of the array tells how many elements are there in the array. The size of the array eir size nd have contiguous area of memory. We can access the arrays using the array index.
arrays is as follows: data_type array_name [size] ;
r example:
is case it will occupy forty ytes (one int = 4 bytes). The elements of the array are manipulated using the index.
emory image of an array:
We have started C language is a function-oriented language functions. Our c lecture.
Let us consider an example about calculation of average age of 10 students. At firs we will declare 10 variables to store the age of each student and th a instead of 10, we have to declare 100 variables i.e. one for ea a
A of storage of ages of 100 students, arrays can be used. Arrays are data structure which identical data types are stored. The concept of arrays is being explained fur in the following parts of the lecture. Arrays I valid data type. The rules of variable nam si should be a precise number. The arrays occupy the memory depending upon th a
Declaration: The declaration of
fo int ages[10];
Let's consider an array int C[10]; This is an array of integer and has a name ’C'. It has a size ten which depicts that the array ‘C’ can contain ten elements of int data type. In the memory, the array occupies the contiguous area, in th b In C language, the index of array starts from zero and is one less than array's size. Index of array is also called subscript.
M
Name
docsity.com
ge[5], it means we are referring to the single element of the array not the whole
onsid the e ent’s ages again. Is there a way to calculate the average ge of a l the s ccessed with indexing. So we can use a ' for loop' as nder;
r (i = ; i < 1
se enter the age of the student “;
the above ' for loop ' the value of i is changing from 0 to 9. Here the loop condition i<10. This means that the cin and cout statements will be executed 10 times. We
t of
array age.
for (i = 0 ; i < 10 ; i++ )
totalAge += age [i];
the above loop, all the elements of the array age will be added to the variable alAge. When the value of i is 0 i.e. age[0] the value of first element will be added the totalAge. As the value of i is changing from 0 to 9 so all the 10 elements of the ay will be added to the totalAge. By dividing this totalAge by 10 we will get the rage age.
here are many ways to initialize an array. Don't use the default initialization of
lue.
a array.
C er xample of stud a l tudents in an array? As we know that arrays can be a u
fo 0 0 ; i++ ) { cout << “Plea cin >> age [i]; }
In is have used i as the index of the array. The index we are referring to the array needs to be an integer. It can be 4, 5 or an integer variable like i. In the first repetition, the value of i is 0, i.e. age[0] so the value of first element of the age will be read_._ In the second repetition, the value of i becomes 1 i.e. age[1] so the value of 2 nd^ elemen the age will be read and so on. We get all the 10 values from the user which will be stored in the
Now we will calculate the total of ages. We can use another ' for loop ' to add up all the elements of the array age.
int totalAge = 0;
In tot to arr ave
arrays. Compiler may assign some value to each declared array. Always initialize the array in such a manner that the process is clear.
We can initialize an array using a 'loop' while assigning some va
int i, age [10];
docsity.com
for ( i = 0; i < 10 ; i++ )
ith the help of this simple loop, we have initialized all the elements of array age to ero. I dition, we have used the condition i < 10, where the size of the now, the array index is one less than the size of the array. Here index of array and its values are from 0 to 9.
the array at the time of declaration as:
y using any other number stead of zero. However, generally, zero is used to initialize the integer variables. e can ing shortcut.
he above statement has also initialized all the elements of the array to zero.
of loop
Consider the following statement:
ize of the array. The compiler is quite intelligent as detects the initialization list which consists of ten 0’s. Therefore, it creates an array
starts from the index 0 and is up to one less than the size of e array. So if the size of the array is ten, the index will be from 0 to 9. Similarly, if of the array is 253, the index will be from 0 to 252.
age[i] = 0;
z n the loop con array is ten. As we k we are using i as the
We can also initialize
int age [10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
The above statement creates an array age of integers and initializes all the elements with zero. We can use any value to initialize the array b in W do it by using the follow
int age [10] = { 0 };
T
We have different ways of initializing the arrays. Initialization through the use is a better choice. If the size of the array gets larger, it is tedious to initialize at the declaration time.
int age [ ] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
Here we have not mentioned the s it of 10 integers and initializes all the elements with zero.
The index of the arrays th the size
docsity.com
int z , i = 0 ;
cout << “Please enter the number (-1 to end input) “ << endl; cin >> z ; ( z != -1 )
;
; while & i < 100 ) ;
cout << “ The total number of positive integers entered by user is “ << i -1;
do {
if { c[ i ] = z } i ++ } ( z != -1 &
T he above code shows that the assignment statement of the array is inside the if block. ere the numbers will be assigned to the array elements when the 'if statement' -1, the if statement will evaluate it false. So the ecuted and next i will be incremented. The while loop' will be tested. As the value of z is -1, the loop will be rminated. te how many positive numbers, the user has entered. In the ositive integers entered by the users is i -1. erms of its practical usage. Suppose we have to ents of the class. If we don’t know the exact number of ass, we can declare an array of integers of larger size and get the ages rom the user and use -1 to end the input from the user.
the program is as follow.
ease enter the number (-1 to end input) 1
evaluates to true. When the user enters assignment statement will not be ex condition in the ' te Now we have to calcula end, we have incremented i so the actual p The above example is very useful in t calculate the ages of stud students in the cl f
A sample out put of
Pl 2 3 4 5 6
The total number of positive integers entered by user is 6
Sometimes, we need to copy an array. That means after copying, both the arrays will contain elements with same values. For being copy able, both arrays need to be of same data type and same size. Suppose, we have two arrays a and b and want to copy array a into array b. Both arrays are of type int and of size 10.
int array a[10];
docsity.com
b[10];
e know that a value can be assigned to an element of array using the index. So we
0, its index will be from 0 to 9. Using the above technique, we another. Now if the array size is 100 or 1000, this method can e used. Is there some other way to do things in a better way? We can use the loop t to deal with this easily in the following way.
; i < 10 ; i ++)
loop, it becomes very simple. We are no more worried about the size ll work by just changing the condition. We are responding values of array a into array b. The value of first element f array a is assigned to the first element of array b and so on.
ake the sum of squares of 10 different numbers stored in an array.
ogram m of squares of numbers stored in an array.
t sum
cout << "Please enter the ten numbers one by one " << endl;
cin >> a [i];
int array
W can write assignment statements to copy these arrays as:
b[0] = a[0] ; b[1] = a[1] ; b[2] = a[2] ;
……
b[9] = a[9] ;
As the size of array is 1 can copy one array to b construc
for (i = 0 { b[i] = a[i]; }
With the help of of the array. The same loop wi assigning the cor o
Here is the code of the program:
// This pr calculates the su
#include <iostream.h>
main() { int a[10]; in OfSquares = 0 ; int i =0;
// Getting the input from the user. for (i = 0 ; i < 10 ; i++ ) {
docsity.com
// This program is used to find a number from the array. #include <iostream.h>
ain() { int z, i ; int a [ 100 ] ;
cout << “ Please enter a positive integer “ ; cin >> z ; int found = 0 ;
// loop to search the number. for ( i = 0 ; i < 100 ; i ++ ) { if ( z == a [ i ] ) { found = 1 ; break ; } } if ( found == 1 ) cout << “ We found the integer at index ” << i ; else cout << “ The number was not found ” ; }
m
// Initializing the array. for ( i =0 ; i < 100 ; i ++ ) { a [ i ] = i ; }
The following is an output of the program. Please enter a positive integer 34 We found the integer at index 34
The loop in the above program may run 100 times or less. The loop will terminate if the number is found before the 100th^ repetition. Therefore, in the linear search the maximum limit of the loop execution is the size of the list. If the size of list is 100, then the loop can execute a maximum of 100 times.
Using random function (Guessing Game): We can turn this problem into an interesting game. If we as programmers do not know, which number is stored in the array? We can make this a guessing game. How can we do that? We need some mechanism by which the computer generates some number. In all the C compilers, a random number generation function is provided. The function is rand() and is in the standard library. To access this function, we need to include <stdlib.h> library in our program. This function will return a random number. The number can be between 0 and 32767. We can use this function as:
docsity.com
= rand ( );
nerates an integer which is assigned to variable x. Let's consider the function-calling mechanism. The program starts its execution in the main nction. When the control goes to the statement containing a function call, the main program stops here and the control goes inside the function called. When the function ome value, the control comes back to the main program.
using rand().
eam.h>
main() {
nitializing th
cout << “ Please enter a positive integer “ ; cin >> z ; int found = 0 ;
// loop to search the number. for ( i = 0 ; i < 100 ; i ++ ) { if ( z == a [ i ] ) { found = 1 ; break ; } } if ( found == 1 ) cout << “ We found the integer at position ” << i ; else cout << “ The number was not found ” ; }
x
The random function ge
fu
completes or returns s
Here is the complete code of the program
// This program is used to find a number from the array.
#include <iostr #include <stdlib.h>
int z, i ; int a [ 100 ] ; // I e array.
for ( i =0 ; i < 100 ; i ++ ) { a [i] = rand() ;
The following is an output of the program. Please enter a positive integer 34 The number was not found
docsity.com
d
If we have to change the size of the array, we only have to change the value of arraySize where it is declared. The program will work fine in this case. This is a goo programming practice to use const for array size.
Initialize the array explicitly Array index (subscript) starts from 0 and ends one less than the array size To copy an array, the size and data type of both arrays should be same Array subscript may be an integer or an integer expression Assigning another value to a const is a syntax error
docsity.com