Ad Code

c++ language Arrays or random

Arrays c++

Introduction

 We have started writing functions, which will become a part of our every program. As C language is a function-oriented language, so we will be dealing with too many functions. Our programming toolkit is almost complete but still a very important component is missing. We are going to discuss this component i.e. Arrays in this lecture.

Arrays:

In C language, every array has a data type i.e. name and size. Data type can be any valid data type. The rules of variable naming convention apply to array names. The size of the array tells how many elements are there in the array. The size of the array should be a precise number. The arrays occupy the memory depending upon their size and have contiguous area of memory.

Declaration:

The declaration of arrays is as follows:

 data_type array_name [size] ;

for example:

 int ages[10];

const int arraySize = 100;

This statement creates an identifier arraySize and assigns it the value 100. Now the

arraySize is called integer constant. It is not a variable. We cannot change its value in

the program. In the array declaration, we can use this as:

 int age [arraySize];

Now in the loop condition, we can write like this:

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

X==rand();

                      The random function generates an integer which is assigned to variables X.

Consider the function calling mechanism.

arrays


Sample Program 1

#include<iostream>

using namespace std;

main()

{

int z, i ;

 int a [ 100 ] ;

 // Initializing the array.

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

 {

 a [ i ] = i ;

 }

 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" ;

}

arrays

arrays


Tips 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

 

 

 

 

 

 

 

 

 

  

Post a Comment

0 Comments