0% found this document useful (0 votes)
9 views15 pages

Arrays, Strings, and Structures in C++

Chapter Four covers arrays, strings, and structures in programming. It explains one-dimensional and two-dimensional arrays, including their initialization and basic operations like finding maximum values and sorting. The chapter also introduces strings as character arrays, string manipulation functions, and structures as collections of different data types, with examples of their usage in programs.

Uploaded by

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

Arrays, Strings, and Structures in C++

Chapter Four covers arrays, strings, and structures in programming. It explains one-dimensional and two-dimensional arrays, including their initialization and basic operations like finding maximum values and sorting. The chapter also introduces strings as character arrays, string manipulation functions, and structures as collections of different data types, with examples of their usage in programs.

Uploaded by

stotaw abe
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1/ 15

Chapter Four

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()
{
1
2/ 15

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”;
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> {
Int 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";
}}

2
3/ 15

return 0;}
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 number of characters in the string plus one.
Eg: char name [5] = { ‘j’ , ‘o’, ‘n’, ‘y’, ‘\0’}

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
[Link](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 string concatination 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;

3
4/ 15

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.
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: ";
[Link](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>
4
5/ 15

#include<ctype.h>
#include<string.h>
main()
{
int i;
char str[50],ch=’y’;
while(ch==’y’)
{
cout<<”Enter the string to convert \n”;
[Link](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.
5
6/ 15

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];
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., [Link].

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”<< [Link]<<”\n”;
cout<<” enter name \n”; cout<<” total marks”<<total;
[Link]([Link],10); }
cout<<” enter idno \n”;
[Link]([Link],10);
cout<<” enter marks \n”;
cin>>[Link]>> [Link]>> [Link];
total = [Link]+ [Link]+ [Link];

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
6
7/ 15

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>
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”; {
[Link](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()
7
8/ 15

{
struct mark
{
char name[20];
int S[2];
}sem;
int i;
cout<<" Enter name \n";
[Link]([Link],20);
cout<<"Enter 2 marks \n";
for(i=0;i<2;i++)
cin>>sem.S[i];
cout<<"name "<<[Link]<<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”;
[Link](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.


8
9/ 15

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

Functions

1 Simple Functions
A function is a complete unit of executable code that can perform specific task. Function is considered
as a fundamental building of a programming language. In order to avoid complexity of a program while
coding debugging & testing, the program is divided into functional part or subprograms.
General form: type-specifier function-name (argument declaration)
{
body of the function;
return (expression);
}
Type-specifier — specifies type of value (data type) that the return statement of function returns. By
default function returns integer value if not specified.
Argument — is a comma separated list of variable names that receive the values, when function is
called, (parenthesis required even no arguments)
eg., : int dol() returns int value to main.
float sum() returns float value to main.
Return — (a) Causes an immediate exit from the function
(b) Returns the value. When this is encountered, control is passed back to the calling
function. If function is declared void then there is no need to include return statement.

Basic Structure of a C++ Program

The basic components necessary to create a C++ program are: preprocessor directives, global
declarations, the main() function, user defined functions and comments. All C++ program follow the
same basic structure. Even a larger complex C++ program has the same layout as short programs.

C++ PROGRAM

PREPROCESSOR DIRECTIVES

GLOBAL DECLARATION
9

main ( ) FUNCTION
10/ 15

LIBRARY FUNCTIONS (function that have their own header files)


iostream.h Standard input /output streams like cin, cout etc.
math.h Mathematical functions like sin(), cos(), sqrt(),log() etc.
stdlib.h Standard library functions like conversion of one type to other etc.
String.h String manipulation functions like strcpy (), strcat(), strcmp() etc.
time.h Includes date & time functions.

2 Function prototyping:
The prototype describes the function interface to the compiler by giving details such as the number and
type of arguments and the type of return values.
Function prototype is a declaration statement in the calling program and the general form is
return_type fun_name(arg_list);
Ex: float volume(int,float,float);

Program to implement void function : To find out the number is even or not.
#include<iostream.h>
main()
{
int a;
void even(int);
cout<<”enter a number \n”;
cin>>a;
even(a);
}
void even(int x)
{
if ((x % 2)== 0 )
cout<<”\n number is even”;
else
cout<<”\n number is odd”;
}
Program to illustrate use of return which returns value:
Program to read the temperature in Fahrenheit and convert it into calicoes.
#include<iostream.h>
void main()
{
float f,celicious;

10
11/ 15

float cel(float x);


cout<<"Enter the temperature in forenheat:";
cin>>f;
celicious=cel(f);
cout<<"The temperature in calicoes is: "<<celicious;
}

float cel(float x)
{
float p; or
p=(5.0 / 9)*(x - 32); return(5.0 / 9)*(x - 32);
return p;
}

3. Local variables:
Variables declared within a function are called as local variables. They are created when the function
is called and destroyed automatically when the function is exited.
Scope of the local variable is with in the function only; it is not valid out side of the function.
Example:
main ( )
{
int m=1000,n=999;
function2 ( );
function1 ( );
cout<<m<<endl<<n;
}
function1 ( )
{
int m=10; Output
cout<<m<<endl;
} 10
100
function2 ( ) 1000
{ 999
int m=100;
cout<<m<<endl;
//cout<<n; Creates an error like undefined symbol n
}

A program with two sub programs function1 ( ) and function2 ( ) is shown. m is an automatic
variable and it is declared at the beginning of the each function. m is initialized to 10, 100, 1000 in
function1, function2 and main( ) respectively.

4. Global variables:

11
12/ 15

Global variables are declared separately, preferably outside the main function. They are accessible to
all functions included in the program.
So, Scope of the global variable is throughout the program
Unlike local variables, global variables can be accessed by any function in the program.
Once a variable has been declared as global, any function can use it and change its value.

Consider a program segment as shown below.


int y;
main( )
{
y=5;
-
-
}
function1( )
{
y=y+1;
cout<<y;
}
y is defined as global so that function1() also accessed the variable.

Calling a Function:
Function can be called in 2 ways. (a) Call by value (b) Call by reference
a) Call by Value:
This is one way of data transformation from calling portion to called portion. Means changes
inside the function cannot affect the main program.
b) Call by reference:
This is two way of data transformation from calling portion to called portion and called
portion to calling portion. Means when function is called by reference, Changes inside the function
affect main program also. When function is called, argument corresponding to a reference parameter is
not copied. A reference is an alias for another variable & when we specify a function argument as a
reference type, Function will use pass-by-reference technique for passing the variables. Reason for this
is because the parameter name simply becomes alias for the argument value in the calling program.
Whenever variable name is used in the body, it will access argument value in the calling function
directly.

//An example program illustrating Call_by_value and Call-by_reference


#include<iostream.h>
void main()
{
int x,y,p,q; Local variable declaration
void swap1( int p, int q);
void swap2( int &x, int &y); Function prototypes
cout<<"enter values for p,q,x and y: ";
cin>>p>>q>>x>>y;
swap1(p,q); Function calling
12
13/ 15

cout<<" p,q after calling swap1: "<<endl;


cout<<" p = "<<p<<" and q = "<<q<<endl;
swap2(x,y); x, y called as actual parameters
cout<<" x,y after calling swap2: "<<endl;
cout<<" x = "<<x<<" and y = "<<y<<endl;
p, q called as formal parameters

}
void swap1(int p, int q) called function
{
int temp;
temp = p;
Body of the function
p = q;
q = temp;
}
void swap2(int &x, int &y)
{
int temp;
temp = x;
x = y;
y = temp;
}

Program 1. To find the largest of 2 numbers.


#include<iostream.h>
void main()
{
int a, b, big;
int large(int, int);
cout<<"Enter the 2 numbers\n";
cin>>a>>b;
big=large(a,b);
cout <<"Largest of two numbers "<<big;
}

int large(int x, int y)


{
return (x > y ? x : y);
}

5) Argument passing:
Functions depend on whether arguments are present or not, whether a value is returned or not, can be
classified as:
Category (types) of functions:
a. Functions with no arguments & no return values.
b. Functions with arguments & no return values.
13
14/ 15

c. Functions with arguments & return values.

a)Functions with no arguments & no return values:


This kind is peculiar in 2 aspects:
(i) A function with no argument does not receive data from calling function.
(ii) With no return value, does not give any data to calling function.
Thus the function can be used as an independent statement but not as an expression.
\\ Sample program to only accept values from the user.
#include<iostream.h>
void main()
{
int ch;
void error(void);
cout <<"Enter any number from 1 to 4";
cin>>ch;
If (ch<1) && (ch>4)
error(); Here if the user enters a value > 4 function error()
else is called to display the error message.
cout<<"Yes, you entry is correct";
}

void error()
{
cout<<"Invalid entry, try again";
}

b)Functions with arguments & no return values:


Here the function will receive data from calling function, But will not return any data to it.
// Sample program to display Biggest of 3 numbers.
void main()
{
int a, b, c;
void big(int, int, int);
cout<<”\n Enter 3 numbers \n”;
cin>>a>>b>>c;
big(a, b, c);
}

void big(int x, int y, int z)


{
if (x>y && x>z)
cout<<”\n a is the biggest”;
else if (y>z && y>x)
cout<<” \n b is the biggest”;
else
cout<<” \n c is the biggest”;
14
15/ 15

c)Functions with arguments & return values:


Here two way data communication takes place i.e., both the called & calling functions receive and
transfer data from each other.

//Program to calculate area of a triangle.

#include<iostream.h>
int main()
{
float x, y, c;
float area(float, float);
cout<<" \n Enter base & height ";
cin>>x>>y;
c=area(x, y);
cout<<”\n area is “ <<c;
return 0;
}
float area(float b, float h)
{
return( 0.5 * b * h);
}
Function overloading allows you to create multiple functions with the same name but different
parameters. This improves code readability and organization.
Here's an example:
#include <iostream>
#include <string>
using namespace std;

void print(int i) {
cout << "Printing int: " << i << endl;
}

void print(double d) {
cout << "Printing double: " << d << endl;
}
void print(string s) {
cout << "Printing string: " << s << endl;
}

int main() {
print(5);
print(3.14);
print("Hello");
return 0;
}
15

You might also like