Home | | Computer Science 11th std | C++: One-dimensional array

Declaration, Syntax, Example Program - C++: One-dimensional array | 11th Computer Science : Chapter 12 : Arrays and Structures

Chapter: 11th Computer Science : Chapter 12 : Arrays and Structures

C++: One-dimensional array

This is the simplest form of an array. A one dimensional array represents values that are stored in a single row or in a single column.

One-dimensional array

 

This is the simplest form of an array. A one dimensional array represents values that are stored in a single row or in a single column.

 

Declaration

Syntax:

<data type><array_name> [<array_size>];

data_type declares the basic type of the array, which is the type of each element in the array.

array_name specifies the name with which the array will be referenced.

array_size defines how many elements the array will hold. Size should be specified with square brackets [ ].

Example:

int num[10];

In the above declaration, an array named “num” is declared with 10 elements (memory space to store 10 different values) as integer type.

To the above declaration, the compiler allocated 10 memory locations (boxes) in the common name “num” as given below


Each element (Memory box) has a unique index number starting from 0 which is known as “subscript”. The subscript always starts with 0 and it should be an unsigned integer value. Each element of an array is referred by its name with subscript index within the square bracket. For example, num[3] refers to the 4th element in the array.

Some more array declarations with various data types:

char emp_name[25];      //       character array named emp_name with size 25

float salary[20];   // floating-point array named salary with size 20

int a[5], b[10], c[15]; // multiple arrays are declared of type int

 

Memory representation of an one dimensional array

The amount of storage required to hold an array is directly related with type and size. The following figure shows the memory allocation of an array with five elements.


The above figure clearly shows that, the array num is an integer array with 5 elements. As per the Dev-C++ compiler, 4 bytes are allocated for every int type variable. Here, there are totally 5 elements in the array, where for each element, 4 bytes will be allocated. Totally, 20 bytes will be allocated for this array.


The memory space allocated for an array can be calculated using the following formula:

 

Number of bytes allocated for type of array × Number of elements

 

Initialization

An array can be initialized at the time of its declaration. Unless an array is initialized, all the array elements contain garbage values.

 

Syntax:

<datatype> <array_name> [size] = {value-1,value-2,…………… ,value-n};

 

Example

int age[5]={19,21,16,1,50};

In the above example, the array name is ‘age’ whose size is 5. In this case, the first element 19 is stored in age[0], the second element 21 is stored in age[1] and so on as shown in figure 12.1


While  declaring    and    initializing values in an array, the values should be given within the curly braces ie. { ….. }

The size of an array may be optional when the array is initialized during declaration.

 

Example:

int age[]={ 19,21,16,1,50};

In the above initialization, the size of the array is not specified directly in the declaration with initialization. So, the size is determined by compiler which depends on the total number of values. In this case, the size of the array is five.

More examples of array initialization:

float x[5] = {5.6, 5.7, 5.8, 5.9, 6.1};

char vowel[6] = {'a', 'e', 'i', 'o', 'u', '\0'};

 

Accepting values to an array during run time :

Multiple assignment statements are required to insert values to the cells of the array during runtime. The for loop is ideally suited for iterating through the array elements.

 

// Input values while execution

#include <iostream>

using namespace std;

int main()

{

      int num[5];

      for(int i=0; i<5; i++)

      {

           cout<< "\n Enter value " << i+1 << "= ";

           cin>>num[i];

      }

}

In the above program, a for loop has been constructed to execute the statements within the loop for 5 times. During each iteration of the loop, cout statement prompts you to “Enter value …….” and cin gets the value and stores it in num[i];

The following table shows the execution of the above code block.


In for loop, the index i is declared with an initial value 0 (zero). Since in most of the cases, the initial value of the loop index will be used as the array subscript representation.

 

Accessing array elements

Array elements can be used anywhere in a program as we do in case of a normal variable. The elements of an array are accessed with the array name followed by the subscript index within the square bracket.

 

Example:

cout<<num[3];

In the above statement, num[3] refers to the 4th element of the array and cout statement displays the value of num[3].

The subscript in bracket can be a variable, a constant or an expression that evaluates to an integer.

 

// Accessing array elements

#include <iostream>

using namespace std;

int main()

{

      int num[5] = {10, 20, 30, 40, 50};

      int t=2;

      cout<<num[2] <<endl; // S1

      cout<<num[3+1] <<endl; // S2

      cout<<num[t=t+1]; // S3

}

output:

30

50

40

 

In the above program, statement S1 displays the value of the 3rd element (subscript index 2). S2 will display the value of the 5th element (ie. Subscript value is 3+1 = 4). In the same way statement S3 will display the value of the 4th element.

The following program illustrates the writing and reading of array elements.

 

//Program to read and write the values from an array

#include <iostream>

using namespace std;

int main()

{

      int age[4];//declaration of array

      cout<< "Enter the age of four persons:" <<endl;

      for(int i = 0; i < 4; i++)//loop to write array elements

      cin>> age[i];

      cout<<"The ages of four persons are:";

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

           cout<< age[j]<<endl;

}

The following table shows the execution of the above code lines


After the successful execution of the above statements, the given values will be stored in memory like,


Second for loop:

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

      cout<< age[j]<<endl;

The above statements are used to read the values from the memory and display the values.

The following table shows the execution of the above code.


So, the final output will be:

Enter the age of four persons:

18

17

21

23

The ages of four persons are:

18

17

21

23

 

Traversal:

Accessing each element of an array at least once to perform any operation is known as “Traversal”. Displaying all the elements in an array is an example of “traversal”.

 

 Traversal of an array

#include <iostream>

using namespace std;

int main()

{

      int num[5];

      for (int i=0; i<5; i++)

      {

           cout<< "\n Enter value " << i+1 <<"= ";

           cin>>num[i]; // Reading from keyboard

           //Traversing the array elements sequentially and adding 1 to each element num[i] = num[i] + 1;

      }

      cout<< "\n After incrementing, the values in array num..." <<endl;

      for (int j=0; j<5; j++)

      {

      //Traversing the array elements sequentially and printing each one of them cout<<num[j] <<endl;

      }

}

Output:

Enter value 1= 10

Enter value 2= 20

Enter value 3= 30

Enter value 4= 40

Enter value 5= 50

After incrementing, the values in array num...

11

21

31

41

51

 

Program to read the marks of 10 students and to find the average of all those marks.

#include <iostream>

using namespace std;

int main()

{

      int marks[10], sum=0;

      float avg;

      for(int i=0; i<10; i++)

      {

           cout<< "\n Enter Mark " << i+1 << "= ";

           cin>> marks[i];

           sum=sum+marks[i];

      }

      avg=sum/10.0;

      cout<< "\n The Total Marks: " << sum;

      cout<< "\n The Average Mark: " <<avg;

}

Output:

Enter Mark 1= 41

Enter Mark 2= 98

Enter Mark 3= 65

Enter Mark 4= 75

Enter Mark 5= 35

Enter Mark 6= 82

Enter Mark 7= 64

Enter Mark 8= 5

Enter Mark 9= 58

Enter Mark 10= 68

The Total Marks: 591

The Average Mark: 59

 

C++ program to inputs 10 values and count the number of odd and even numbers

#include <iostream>

using namespace std;

int main()

{

      int num[10], even=0, odd=0;

      for (int i=0; i<10; i++)

      {

           cout<< "\n Enter Number " << i+1 <<"= ";

           cin>>num[i];

           if (num[i] % 2 == 0)

           ++even;

           else

           ++odd;

      }

      cout << "\n There are "<< even <<" Even Numbers";

      cout << "\n There are "<< odd <<" Odd Numbers";

}

Output:

Enter Number 1= 78

Enter Number 2= 51

Enter Number 3= 32

Enter Number 4= 66

Enter Number 5= 41

Enter Number 6= 68

Enter Number 7= 27

Enter Number 8= 65

Enter Number 9= 28

Enter Number 10= 94

There are 6 Even Numbers

There are 4 Odd Numbers

(HOTS : Rewrite the above program using the conditional operator instead of if)

 

Program to read the prices of 10 products in an array and then print the sum and average of all the prices

#include <iostream>

using namespace std;

int main()

{

      float price[10], sum=0, avg=0, prod=1;

      for(int i=0; i<10; i++)

      {

           cout<< "\n Enter the price of item " << i+1 <<"= ";

           cin>> price[i];

           sum+=price[i];

      }

avg=sum/10.0;

cout<< "\n Sum of all prices: " << sum;

cout<< "\n Average of all prices: " <<avg;

}

 

Program to accept the sales of each day of the month and print the average sales for each month

#include <iostream>

using namespace std;

int main()

{

      int days;

      float sales[5], avgSales=0, totalSales=0;

      cout<< "\n Enter No. of days: ";

      cin>> days;

      for (int i=0; i<days; i++)

      {

           cout<< "\n Enter sales on day - " << i+1 <<": ";

           cin>> sales[i];

           totalSales+=sales[i];

}

avg=total sales/days;

cout<< "\n Average Sales = " <<avgSales;

return 0;

}

.


Searching in a one dimensional array:

Searching is a process of finding a particular value present in a given set of numbers. The linear search or sequential search compares each element of the list with the value that has to be searched until all the elements in the array have been traversed and compared.

 

Program for Linear Search

#include <iostream>

using namespace std;

int Search(int arr[], int size, int value)

{

      for (int i=0; i<size; i++)

      {

           if (arr[i] == value)

           return i; // return index value

      }

return -1;

}

int main()

{

      int num[10], val, id;

      for (int i=0; i<10; i++)

      {

      cout<< "\n Enter value " << i+1 <<"= ";

      cin>>num[i];

      }

      cout<< "\n Enter a value to be searched: ";

      cin>>val;

      id=Search(num,10,val);

      if(id==-1)

      cout<< "\n Given value is not found in the array.."; else

      cout<< "\n The value is found at the position" << id+1; return 0;

}

The above program reads an array and prompts for the values to be searched. It calls Search( ) function which receives array, size and value to be searched as parameters. If the value is found, then it returns the array index to the called statement; otherwise, it returns -1.


Strings

A string is defined as a sequence of characters where each character may be a letter, number or a symbol. Each element occupies one byte of memory. Every string is terminated by a null (‘\0’, ASCII code 0) character which must be appended at the end of the string. In C++, there is no basic data type to represent a string. Instead, it implements a string as an one-dimensional character array. When declaring a character array, it also has to hold a null character at the end, and so, the size of the character array should be one character longer than the length of the string.

 

Character Array (String) creation

To create any kind of array, the size (length) of the array must be known in advance, so that the memory locations can be allocated according to the size of the array. Once an array is created, its length is fixed and cannot be changed during run time. This is shown in figure12.2


 

Syntax

Array declaration is:

char array_name[size];

In the above declaration, the size of the array must be an unsigned integer value.

For example,

char country[6];

Here, the array reserves 6 bytes of memory for storing a sequence of characters. The length of the string cannot be more than 5 characters and one location is reserved for the null character at the end.

 

Program to demonstrate a character array.

#include <iostream>

using namespace std;

int main()

{

      char country[6];

      cout<< "Enter the name of the country: ";

      cin>>country;

      cout<<" The name of the country is "<<country;

}

OUTPUT

Enter country the name: INDIA

The country name is INDIA

 

Initialization

The character array can be initialized at the time of its declaration. The syntax is shown below:

char array_name[size]={ list of charecters separated by comma or a string } ;

For example,

char country[6]=“INDIA”;

In the above example, the text “INDIA” has 5 letters which is assigned as initial value to array country. The text is enclosed within double quotes. The memory representation is shown in Figure 13.3


In the above memory representation, each character occupies one byte in memory. At the end of the string, a null character is automatically added by the compiler.

C++ also provides other ways of initializing the character array:

 

char country[6]={‘I’, ‘N’, ‘D’, ‘I’, ‘A’, ‘\0’};

char country[]=INDIA”;

char country[]={‘I’, ‘N’, ‘D’, ‘I’, ‘A’, ‘\0’};

 

If the size of the array is not explicitly mentioned, the compiler automatically calculate the size of the array based on the number of elements in the list and allocates space accordingly.

In the initialization of the string, if all the characters are not initialized, then the rest of the characters will be filled with NULL.

 

Example:

char str[5]={'5','+','A'};

str[0]; ---> 5

str[1]; ---> +

str[2]; ---> A

str[3]; ---> NULL

str[4]; ---> NULL

 

During initialization, the array of elements cannot be initialized more than its size.

 

For example

char str[2]={'5','+','A','B'}; // Invalid

In the above example, the compiler displays “initialize-string for array of chars is too long” error message.

 

Write a program to demonstrate various methods of initializing the character arrays

#include <iostream>

using namespace std;

int main()

{

      char arr1[6]="INDIA";

      char arr2[6]={'I','N','D','I','A','\0'};

      char arr3[]="TRICHY";

      char arr4[]={'T','R','I','C','H','Y','\0'};

      char arr5[8]="TRICHY";

      cout<<"arr1 is :" <<arr1<< " and its size is "<<sizeof(arr1)<<endl;

      cout<<"arr2 is :" <<arr2<< " and its size is "<<sizeof(arr2)<<endl;

      cout<<"arr3 is :" <<arr3<< " and its size is "<<sizeof(arr3)<<endl;

      cout<<"arr4 is :" <<arr4<< " and its size is "<<sizeof(arr4)<<endl;

      cout<<"The elements of arr5"<<endl;

      for(int i=0;i<8;i++)

      cout<<arr5[i]<<" ";

      return 0;

}

Output

arr1 is :INDIA and its size is 6

arr2 is :INDIA and its size is 6

arr3 is :TRICHY and its size is 7

arr4 is :TRICHY and its size is 7

The elements of arr5

T R I C H Y

 

Read a line of Text

In C++, cin.get() is used to read a line of text including blank spaces. This function takes two arguments. The first argument is the name of the string and second argument is the maximum size of the array.

 

Write a program to display a line of text using get() function.

//str10.cpp

//To read a line of text

#include <iostream>

using namespace std; int main()

{

char str[100];

cout<< "Enter a string: ";

cin.get(str, 100);

cout<< "You entered: " <<str<<endl;

return 0;

}

Output

Enter a string: I am a student

You entered: I am a student

In the above program, str is the name of the string and 100 is the maximum size of the character array that represents the string str.

In C++, getline() is also used to read a line of text from the input stream. It can read the characters till it encounters a newline character or a delimiter specified by the user. This function is available in the <string> header.

 

Write a Program to check palindrome or not

#include<iostream>

using namespace std;

int main( )

{

      int i, j, len, flag =1;

      char a [20];

      cout<<"Enter a string:";

      cin>>a;

      for(len=0;a[len]!='\0';++len)

for(!=0,j=len-1;i<len/2;++i,--j)

      {

      if(a[j]!=a[i])

           flag=0;

      }

      if(flag==1)

           cout<<"\n The String is palindrome";

      else

           cout<<"\n The String is not palindrome";

      return 0;

}

Output:

Enter a string : madam

The String is palindrome

 

Tags : Declaration, Syntax, Example Program , 11th Computer Science : Chapter 12 : Arrays and Structures
Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
11th Computer Science : Chapter 12 : Arrays and Structures : C++: One-dimensional array | Declaration, Syntax, Example Program


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.