Lecture 18 Arrays 2
Lecture 18 Arrays 2
Arrays
Sample Programs
- Recap the previous lecture
- Correction of Count the number of positive integers
- Linear search
- Selection sort
-
arrays and function
Use of rand() and srand(time(0))
Arrays:
• Arrays are like the data structure in which identical data types are
stored.
• An array has a name, data type, and size
• They occupy the consecutive area of memory
• Can we save height and weight information in same array? (context
should be same)
Syntax: name
Correction of code
int main()
{
int a[3] = { 0 }, i = 0, input = 0;
do
{
cout <<Entered the positive number (enter -1 for end of input):";
cin>> input;
if (input != -1)
{
a[i] = input;
i++;
}
return 0;
int main()
{
int arr[SIZE];
int num=0, flag = 0, i = 0;
return 0;
}
Example 6: Use the random function
• The function is rand() and is in the standard library.
• To access this function, we need to include <cstdlib> library in our program.
• This function will return a random number.
The number can be between 0 and 32767.
#include<cstdlib> // for rand() and srand()
#include<ctime> // for time(0)
#define SIZE 100
int main()
{
srand(time(0));// To make rand() as the real random number generator
int arr[SIZE];
int num=0, flag = 0, i = 0;
arr[i] = rand();
}
/*
for (i = 0; i < SIZE; i++)
{
printf( "%d " ,arr[i]);
}
*/
printf("\nPlease enter the positve number ");
scanf("%d", &num);
return 0;
}
What is the output of the following expressions:
rand() % 6
1+ rand() % 6
rand() % 2
1+ rand() % 2
rand() % 100
1+ rand() % 100
getInput(array, 10);
// Selection Sort:
int temp;
for (int i = 0; i < 10; i++)
{
for (int j = i + 1; j < 10; j++)
{
if (array[i] > array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
cout << "\nAfter applying Selection Sort: ";
cout << "\nArray in asending order: ";
Next class…..
• Linear Vs binary search
• Character arrays
o character array and value of \0
o determine the length of the character array
o Comparison of arrays (Note in case of character arrays upper
and lower case array of same characters are different ; ali != ALI)