0% found this document useful (0 votes)
0 views

ch 5 array cjr

Uploaded by

matias bahiru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

ch 5 array cjr

Uploaded by

matias bahiru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 8

1/ 8

Arrays, Strings & Structures


5.1 Array:
Array is a collection of items of same data type that are referenced by a common name. All the
variables are referred using an index value. The index value starts at 0 i.e., first value is referred. The
individual values are called elements. That element is referred by index of subscript. Array may have
several dimensions. 1) One-dimensional 2) Two-dimensional.

1. One-Dimensional Array: This is also called as a vector or list.


General form : Type-specifier Id-name [size]
Eg.,: int a[10]; a[0],a[1],a[2],………..,a[9]
float b[10]; Declares b as an array containing maximum of 10 real
elements.
Arrays can be initialized at the time of declaration only. But it is not a good practice.
Eg., : int i[5] = {1,2,3,4,5};
Character arrays hold the strings. Format: Char array-name [size] = ‘string’.
Eg., char b[7] = { ‘w’,’e’,’l’,’c’,’o’,’m’,’e’}

Program 1. To find maximum number in an array.

// to find the maximum element.


#include<iostream.h>
main()
{
int a[5], i, max;

// inputting the array elements


cout<<”Enter 5 numbers \n”;
for( i=0; i<5; i++ )
cin>>a[ i ];

// searching for the largest element.


max = a[0];
for (i=1; i<5; i++)
if (max < a[ i ])
max = a [ i ];

// print the maximum element in the list.


cout << “ Maximum element in the list is : “ << max;
}
Program 2. To sort the given numbers in ascending order using bubble sort.
// to sort the elements.
#include<iostream.h>
main()
{
int a[20], i , j, n, temp;
cout<<”enter the size of the array \n”;
cin>>n;
cout<<”enter the elements of the array \n”;
1/8
2/ 8

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


cin>>a[ i ];
for(i=0; i<n-1;i++)
for(j=i+1; j<n; j++)
if(a[ i ] >a[ j ])
{
temp = a[ i ]; a[ i ]= a[ j ]; a[ j ] = temp;
}
cout<< “ sorted list of elements : \n“;
for(i=0; i<n; i++)
cout<<a[ i ]<<” \t”;
}
2. Two-dimensional arrays:
This is an array of one-dimensional arrays. It can store table of values. It is also called as matrix
of elements. General form: type specifier array-name [row-size] [column-size];
The element declaration here is also done with ‘zero origin subscript’. Thus, an array a[3][3] will have
a[0][0] a[0][1] a[0][2] This may be called as Table or Matrix as they store
a[1][0] a[1][1] a[1][2] table of values in rows & columns.
a[2][0] a[2][1] a[2][2]
This can also be initialized by following declaration.
int a[2][3], b[3][3];

Program 4: For a two-dimensional array 3x3 find (1) sum of all elements.(2)row-wise sum. (3)Column
–wise sum.
// To sum elements row-wise.
// To find sum of matrix elements. for(i=0; i<m; i++)
#include<iostream.h> {
main() rsum = 0;
{ for(j=0; j<n; j++)
int a[10][10], i, j, sum, rsum, csum, m, n; rsum += a[i][j];
cout <<”enter the order of matrix \n”; cout<<"row number:"<<(i+1)<<"\t row sum =
cin>>m>>n; "<<rsum<<" \n";
cout<<”enter the elements of the matrix one by one \n”; }
for(i=0; i<m; i++)
for(j=0; j<n; j++) // To sum column-wise
cin>>a[ i ][j]; for(j=0; j<n; j++)
//to sum all elements of matrix. {
sum = 0; csum=0;
for(i=0; i<m; i++) for(i=0; i<m; i++)
for(j=0; j<n; j++) csum += a[i][j];
sum += a[i][j]; cout<<"column number:"<<(j+1)<<"\tcolumn
cout<<”sum of the elements of the matrix is : “<<sum; sum= "<<csum<<"\n";
}}
5.2 Strings:
A String is an array of characters i.e., they are defined between the single quotes.
A string is a character array terminated by a null character. Null character is specified as ‘ \0 ’.
So, the size should be equal to maximum on. of characters in the string plus one.
Eg: char name [5] = { ‘j’ , ‘o’, ‘n’, ‘y’, ‘\0’}
2/8
3/ 8

Declaration of string variable: char string-name [size] { Size — No. of characters in the
String-name }
Eg., char sname[30],country[40];
Reading strings: cin operator can be used to read a string eg., char name[50];
Cin>>name; — terminates when first blank character is encountered.
Thus, usually we use a new command to read entire line
cin.getline(name,50); — reads entire string until terminated by the enter key or 49
characters are read(which ever occurs first).

String handling functions (string.h file to be included)


a) Length of a string (strlen): defines the length or number of characters in the specified string.

//Program to implement strlen function:


#include<iostream.h>
#include<string.h>
main()
{
char name[80];
int a;
cout<<” Enter the string \n”;
cin>>name;
a= strlen(name);
cout<<” \n length of string is “<<a;
}

b) String Concatenation (strcat): This function adds 2 strings & places in the first string. I.e., the
function appends the second string to the first.

Program to test the strcat function.


#include<iostream.h> cout<<”Enter the second string \n”;
#include<string.h> cin>>n2;
main() strcat(n1,n2);
{ cout<<” Concatenated strings are :”<< n1;
char n1[100], n2[50]; }
int i, c;
cout<<” enter the first string \n”;
cin>>n1;

c) Copying two strings (strcpy): This will assign the contents of one string or character array to
the string variable.
Eg. strcpy(n, "Ethiopia") Stores the character array ’Ethiopia’ in string n.
strcpy(n1,n2) Stores the contents of n2 to n1 erasing the contents of
n1 if any.

d) Comparing two strings (strcmp): This function is used to compare two strings. This compares
the ASCII values of the strings.
3/8
4/ 8

For example strcmp(s1,s2) will return:


(i) Zero if s1 & s2 are equal.
(ii) Positive value if s1>s2.
(iii) Negative value if s1<s2.
The comparison is done on their ASCII values.
[viz., ASCII value of A=65, Z=90, a=97, z=122]

e) Reversing the String (strrev): This function is used to reverse the given string.

Program. To count number of characters, words & blank spaces in the given line.
// to count no. of characters, words & blank spaces.
#include <iostream.h>
#include <conio.h>
#include <string.h>
void main()
{
int now,noc,nos,i;
char st[100];
cout<<"enter the string: ";
cin.getline(st,100);
noc=now=nos=0;
for(i=0;i<strlen(st);i++)
{
noc++;
if(st[i]==' ')
{
now++;
nos++;
noc--;
}
}
now++;
cout<<"\nno of characters "<<noc;
cout<<"\nno of words: "<<now;
cout<<"\n no of spaces: "<<nos;
getch();
}
Program 2. : To convert uppercase to lowercase & vice-versa.
#include<iostream.h>
#include<ctype.h>
#include<string.h>
main()
{
int i;
char str[50],ch=’y’;
while(ch==’y’)
{
cout<<”Enter the string to convert \n”;
4/8
5/ 8

cin.getline(str,20);
i= 0;
while(str[i]!=’\0’)
{
if(islower(str[i]))
str[i] = toupper(str[i]);
else
str[i] = tolower(str[i]);
i++;
}
cout<<”converted string is :”<<str<<”\n”;
cout<<”do U continue(y/n)? \n”;
cin>>ch;
}
}

Tutorial:
1. Write a program to extract left & right most ‘n’ Characters.[Hint : (a)Accept no. of characters from
left. Put condition up to that value & display. (b) Using strlen(),subtract the starting value of the right
most string & display]

5.3 Structures:
A Structure is a collection of data item or variables of different data types that are referred to same
name.
declaration: struct tag-name
{
data-type members;
}
struct — tells the computer structure is being defined, that may be used to create struct variable.
tag-name— identifies particular structure and its type specifier.
fields that comprise the structure are called structure elements. All elements are logically related to
each other.

eg: student database


struct stdrec
{
char name[20]; This describes a format called template to represent various
char idno[10]; data information.
int maths,phy,chem.;
};

We can declare structure variables using tag-name anywhere in the program.


for Example : stdrec Iyear,IIyear,IIIyear; declares I,II,III year as the variables of the
type struct stdrec.
This can be declared as follows:
struct stdrec
{
char name[20];
5/8
6/ 8

char idno[10];
int maths,phy,chem.;
}I year,II year,IIIyear;
Usage of tag-name is also optional i.e., without stdrec is also valid, but does not have a tag-name for
later use.
Referencing structure elements is members must be linked to struc variables in order to make them
more meaningful. This is established through dot operator called as member operator or period
operator. for eg., Iyear.phy.

Example program to assign values to members.


#include<iostream.h>
main()
{
struct stdrec
{
char name[20];
char idno[10];
int maths, phy, chem;
};
stdrec markrec;
int total; cout<<”name is \t”<< markrec.name<<”\n”;
cout<<” enter name \n”; cout<<” total marks”<<total;
cin.getline(markrec.name,10); }
cout<<” enter idno \n”;
cin.getline(markrec.idno,10);
cout<<” enter marks \n”;
cin>>markrec.maths>> markrec.phy>> markrec.chem;
total = markrec.maths+ markrec.phy+ markrec.chem;

Structure initialization:
struct stdrec
{
char name[20];
char idno[10];
int maths, phy, chem;
}markrec = {“raju”,”reg 01/94”,60,70,76}; Here initial values are assigned to respective fields
correspondingly.

Array of structures:
This is most commonly used structures. To define this first the structure must be defined and then
array variable must be declared.
eg., emp empinfo[10];
This creates 10 sets of variables that are organized as defined in structure ‘emp’. array structure begin
their indexing at 0. array of structures is stored in memory as multidimensional array.

// program to illustrate usage of array of structures.


#include<iostream.h>
6/8
7/ 8

main()
{
struct empinfo
{
char name[20];
int empno,basic;
};
empinfo emp[10];
int n,i;
cout<<” Enter how many employees \n”;
cin>>n;
for(i=0; i<n; i++)
{ for(i=0; i<n; i++)
cout<<”Enter name \n”; {
cin.getline(emp[i].name,20); cout<<”\n name of employee”<<emp[i].name;
cout<<”\n Employee no. is ”<<emp[i].empno;
cout<<” Enter employee no \n”; cout<<”\n Basic salary ”<<emp[i].basic;
cin>> emp[i].empno; }
}
cout<<” Enter employee basic pay \n”;
cin>> emp[i].basic;
}

Array with structures:


We can use single or multi-dimensional arrays of data type int or float inside a structure.
Eg., : struct stdrec
{ Here marks contain 3 elements, Marks[0], Marks[1],
int num; Marks[2] thus indicating marks obtained in 3 different
float marks[3]; subjects. The statement markrec[1].marks[2] refers to 2nd
} markrec[5]; mark record & marks obtained in 3rd subject.

//Program to show array within record


#include<iostream.h>
#include<conio.h>
main()
{
struct mark
{
char name[20];
int S[2];
}sem;
int i;
cout<<" Enter name \n";
cin.getline(sem.name,20);
cout<<"Enter 2 marks \n";
for(i=0;i<2;i++)
cin>>sem.S[i];
7/8
8/ 8

cout<<"name "<<sem.name<<endl;
for (i=0; i<2; i++)
cout<<sem.S[i]<<"\n";
getch();
}

Program to print maximum marks along with the name of the student.
#include<iostream.h>
#include<string.h>
main()
{
struct stdrec
{
char name[20];
int s1, s2, s3;
};
struct stdrec mark[5];
int i, tot[5], high;
char tname;
for (i=0; i<5; i++) // Input details
{
cout<<”\n enter name \n”;
cin.getline(mark[i].name,20);
cout<<”enter marks of 3 subjects”;
cin>> mark[i].s1>>mark[i].s2>>mark[i].s2;

//calculate total marks


tot[i] = mark[i].s1+ mark[1].s2+ mark[1].s3;
}

//Printing name with total marks .


for(i=0; i<5; i++)
cout<< mark[i].name<<”\t”<<tot[i];

//Printing highest marks with name.


high=tot[0];
for(i=1; i<5; i++)
if(high<tot[i])
{
strcpy(tname,mark[i].name);
high=tot[i];
}
cout<<”\n name is :”<<tname<<”max marks “<<high;
}

8/8

You might also like