Sie sind auf Seite 1von 16

Introduction

Each data type defined so far is stored in a single unique location and referred to as a single
variable having its own name like ‘sum’, ‘count’, etc. Suppose, we have to make a program to
store the names of ten items, we could start creating variables ‘item1’, ‘item2’, and ‘item3’ and
so on but what if we have to create a program to store names for say 100 or say a 1000 items
then what? We could use the same approach but then the resulting program will be too long and
cumbersome. Now suppose that instead of treating them as 100 similar but separate data items
we could set aside a space large enough for storing all 100 values and assign a name to the
storage area. Data items stored in this way are termed as ‘arrays’.

The difference between an array and a structure is that array consists of a set of variables of the
same data type. A Structure, on the other hand, can consist of different data types.

Declaring Arrays

• An array is a sequence of objects all of which have the same type.


• The objects are called elements of the array and are numbered consecutively 0, 1, 2, and
so on. These numbers are called the index values or subscripts of the array.
• The elements of a one-dimensional array store all the elements in a consecutive order of
entry into an array name.
• A one-dimensional array is a list of variables that are all of the same type and referenced
through a common name.
• An individual variable in the array is called an array element.

void main()
{
clrscr();
int num1, num2, num3, num4, num5;
int sum=0;
cout<<” Enter the five values”;
sum=num1+ num2+ num3+ num4+ num5;
cout<<” The sum of the five values “<<sum;
}

Syntax:
Where ‘data_type’ is any C++ data type,
data_type array_name[subscripted range];
‘array_name’ is the name of the array and ‘subscripted range’ is the length of the array.

1
Example :- Write a program to enter five integer values from the user and print their sum
on the screen.

// Header Files
# include<iostream.h>
# include<conio.h>
// Main Function
void main()
{
// Declaring an array 'num'
int num[5];
int i, sum=0;
// Inputting the values in the array
for ( i=0; i<5;i++ )
{
cout<<" Enter value "<<i<<"->";
cin>>num[i];
}
// Calculating the sum of the values
for ( i=0; i<5;i++)
{
sum = sum + num[i];
}
cout<<" The sum of all the five elements is"<<sum;
}

Output:-
2
Enter value 0 -> 100
Enter value 1 -> 50
Enter value 2 -> 400
Enter value 3 -> 300
Enter value 4 -> 250
The sum of all the five elements is 1100

Example:-
Suppose that in your computer science class, each student secures a certain percentage of marks
and the teacher decides to give grace of 10 % to each student. If the class contains 20 students,
write a C++ program to do the needful?

# include <iostream.h>
# include <conio.h>
// Main Function
void main() {
// Variable Declrations
float per[20];
int i;
cout<<" Enter the students percentages for the 20 students";
// Entering student information from the student
for( i=0;i<20;i++) {
cin>>per[i];
}
// Display the increased percentage of the 20 students
for (i=0;i<20;i++) {
per[i] = per[i] + 10;
cout<<per[i]<<endl;
}
getch();
}
Common Programming Errors

3
The subscripts of all the arrays should always begin with 0. For example in the array int a [5],
the subscripts should begin with 0 as explained above.
� When using loops to initialize values into the array one should make sure that the index
variable always contains a positive value.
� If the number of values assigned exceeds the size of the array or the program tries to access
an index outside the bounds of the array such a statement is an example of a logical error. As the
concurrent C++ compilers are very user friendly the compiler may not give an error but it will
although produce unexpected results.
For example, int A[3]={9,5,2,3} is an incorrect statement as we are assigning an integer value
‘3’ to unallocated set of memory.

Passing arrays as parameters to functions


Arrays are passed to functions as reference parameters. To pass an array argument to a function
the array name is specified without any brackets. The syntax for passing arrays to functions is
given below:
Syntax:- return_type function_name( data_type array_name)
For example, if array ‘weeklyupdate’ is defined as:
int weeklyupdate[10];
then the function call for a function ‘modifyarray’ which takes in an array as a parameter would
look like ‘modifyarray(weeklyupdate);’. Let us take up a program to further understand the
concept of passing arrays to a function.
Program:- // Header Files
# include<iostream.h>
# include<conio.h>
void calculate( int arr[5]){
for (int i=0 ; i<5 ;i++){
arr[i] = arr[i] + 10;
}
}
void main(){
clrscr();
int array_example[5];
cout<<" Enter the elements of the array";
for (int a=0; a<5; a++){
cin>>array_example[a];
}
// Modifying array
calculate(array_example);
cout<<" The modified array is as follows\n";
for (a=0; a<5;a++){
cout<<array_example[a]<<"\n";
}
getch();
}

4
Arrays as strings:-

C++ does not have a string data type rather it implements strings as single-dimension character
arrays. A string is defined as a character array that is terminated by a null character ‘/0’. For this
reason, the character arrays are declared one character longer than the largest string they can
hold. This makes room for the null character at the end of the string. Individual characters of a
string can be easily accessed as they make the elements of the character array. The index – refers
to the first character, the index 1 to the second, 2 to the third, and so forth. The end of a string is
determined by checking for a null character.
For example,

A character array can be initialized using a string literal.


char myfirststring[] = “Hello”;

This statement declares a character string ‘myfirststring’. The size of the string is automatically
determined by the compiler based upon the length of the string. In this example, the compiler
would determine the size of the string as ‘6’. As this string consists of ‘5’ characters and a
special null character (‘\0’) included at the end of each string. Strings can also be declared using
the following syntax:
char myfirststring[] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’};

5
String functions

6
The <string.h> header file enlists a number of useful functions for dealing with null terminated
strings. A brief description of the functions is given in table

7
8
9
10
Solved Examples
Example :-
Write a program to check whether the string entered by the user is a palindrome or not?
// Preprocessor Directives
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
// Main Function
void main()
{
clrscr();
char string[40],i;
int j=0,flag=0;
cout<<" Enter string";
gets(string);
j=strlen(string)-1;
for (i=0;i<strlen(string)-1;i++)
{
if (string[i] != string[j])
{
flag++;
}
j--;
}
if (flag==0)
Output Screen
ARRAYS
My first string
168
{
cout<<" \n |Entered string is palindrome|";
}
else
cout<<" Entered string is not a palindrome";
getch();
}
OUTPUT SCREEN

Enter the string MaM


|Entered string is a palindrome|

11
Example:-
Write a program to enter a string from the user and then display the inputted string with
all the spaces converted into ‘#’s?
// Preprocessor Directives
# include<iostream.h>
# include<conio.h>
# include<string.h>
# include<stdio.h>
// Main Function
void main()
{
clrscr();
char string[15];
cout<<" Enter the string";
gets(string);
for (int i=0;i<strlen(string);i++)
{
if (string[i]==' ')
{
string[i]='#';
}
}
cout<<" \n Displaying the converted string \n";
puts(string);
Enter the string MaM
|Entered string is a palindrome|
Part I: Chapter 5 169
Arrays
getch();
}
Output Screen

Enter the string My sisters name is Deepti


Displaying the converted string
My#sisters#name#is#Deepti

12
Example:-
Write a program to count the no. of vowels in the given string?
// Header Files
# include<iostream.h>
# include<conio.h>
# include<string.h>
# include<stdio.h>
void main()
{
clrscr();
char string[15];
int vowels=0;
cout<<" Enter the string";
gets(string);
for (int i=0;i<strlen(string);i++)
{
if (string[i]=='a' || string[i]=='e' || string[i]=='o' ||string[i]=='i' ||
string[i]=='u')
{
vowels++;
}
}
cout<<" \n The no. of vowels are"<<vowels;
getch();
}

OUTPUT SCREEN
Enter the string Ankit
The no. of vowels are 2

Two-dimensional arrays

A two-dimensional array is an array in which each element is itself an array. For instance, an
array A[M][N] is an M by N table with M rows and N columns containing M * N elements
figure

13
Figure: Two Dimensional Arrays

The number of elements in a 2-D array can be determined by multiplying number of rows with
number of columns. For example, the number of elements in an array A[5][3] is calculated as 15.

The simplest form of a multi-dimensional array, the two-dimensional array, is an array having
single-dimension arrays as its elements. The general form of a two-dimensional array declaration
in C++ as follows:

Where type is the base data type of the array having name array-name; rows, the first index,
refers to the number of rows in the array and columns, the second index, refers to the number of
columns in the array. The following declaration declares a character array ‘name’ having ‘5’
rows and ‘25’ columns.

Just like one dimensional arrays two dimensional arrays can also be initialized at the time of
declaration. The following declaration assigns values for three grades for each of the first two
students in the array.

14
Accessing Two Dimensional Arrays
Two dimensional arrays are accessed/ initialized with the help of two square brackets. The
following piece of code given below is used to access an array ‘A’ of size ‘M*N’ (‘M rows, N
columns) and initialize all its members to zero.

When accessing two dimensional arrays it is important to put each subscript in its own, correct
pair of brackets. Trying to initialize or access elements of a two dimensional array would
produce syntax errors. For example,

Passing Two Dimensional Arrays as a Parameter to Functions

As one dimensional array, two dimension arrays are also passed to functions by reference
automatically. Program 5.5 declares a two dimensional array ‘actual_2darray’ which is
initialized by the user and then passed to the function ‘display’ where it is displayed in matrix
form.
Two dimensional arrays as function arguments
15
// Header Files
# include<iostream.h>
# include<conio.h>
// Function prototype
void display(int formal_2darray[3][3]);
// Main Function
void main(){
clrscr();
int actual_2darray[3][3];
// Enter 2d Array
cout<<" Enter the elements of the 2 dimensional array:";
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
cin>>actual_2darray[i][j];
}
}
//Passing 2d array to function
display(actual_2darray);
}
/******************************
Name: display
Purpose: To display the 2d array in Matrix form
**************************************/
void display(int formal_2darray[3][3]){
cout<<endl<<" Displaying the 2d array in Matrix Form... \n"<<endl;
for (int i=0; i<3; i++){
for (int j=0; j<3; j++){
cout<<"\t"<<formal_2darray[i][j]<<" ";
}
cout<<endl;
}
}

16

Das könnte Ihnen auch gefallen