0% found this document useful (0 votes)
1 views106 pages

Programming Language II

The document provides an overview of arrays in C++, including one-dimensional and multidimensional arrays, their initialization, and examples of various operations such as summing elements, finding averages, and manipulating array elements. It also covers null-terminated strings and includes multiple sample programs demonstrating array usage and manipulation techniques. The content is aimed at first-year students in a Control and Systems class, taught by Lecturer Karam Samir.

Uploaded by

Sadiq Salah
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)
1 views106 pages

Programming Language II

The document provides an overview of arrays in C++, including one-dimensional and multidimensional arrays, their initialization, and examples of various operations such as summing elements, finding averages, and manipulating array elements. It also covers null-terminated strings and includes multiple sample programs demonstrating array usage and manipulation techniques. The content is aimed at first-year students in a Control and Systems class, taught by Lecturer Karam Samir.

Uploaded by

Sadiq Salah
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

Subject: C++ Department: Control and systems

Class: first Lecturer: Karam Samir

L7-1 Array
An array is a data type used to represent a large number of values of the same type. An array
might be used to represent all the salaries in a company or all the weights of participants in a
fitness program. Each element in an array has a position, with the initial element having
position zero. An array element‟s position can be used as an index or subscript to access that
element. The elements of an array are randomly accessible through the use of subscripts.
Arrays of all types are possible, including arrays of arrays. A typical array declaration
allocates memory starting from a base address. An array name is, in effect, a pointer constant
to this base address. In C++, only one-dimensional arrays are provided, with the first element
always indexed as element zero.
To illustrate some of these ideas, let us write a small program that fills an array and sums the
elements of the array:

// Simple array processing


Void main()
{
int a[5]; // get space for a[0],·····,a[4]
int sum = 0;
for (int i = 0; i < 5; ++i) //input array elements
cin>>a[i];
for (i = 0; i < 5; ++i) //reads array elements
sum+ = a[i];
cout << "sum= " << sum ;
}

1
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
Example 1: The following program reads and stores ten integers and then prints the
largest:

#include <iostream.h>
Void main( ){
int i,max,num[10];
for(i=0 ; i<10;++i){
cout<<"\n Enter an integer:";
cin>>num[i];
}
max=num[0];
for(i=1;i<10;++i)
if(num[i]>max)
max=num[i];
cout<<"\n Maximum number is "<<max;
}
Example (2): The following program reads the group numbers and finds the
average:
#include <iostream.h>
void main( ){
int i;
float n[10],sum,average;
sum = 0;
for(i=0;i<10;++i){
cout<<"\n Enter a number:";
cin>>n[i];
sum + = n[i];
}
average =sum/10;
cout<<"\n Average = "<<average;
}

2
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
Example (3): The following example reads a set of integers and prints number of
even number
# include <iostream.h>
# define Length 100
void main( ){
int num[Length];
int i,size,count=0;
cout<<"\n Enter size of array:";
cin>>size;
for(i=0;i<size;++i){
cout<<"\n Enter element "<<i+1<<":";
cin>>num[i];
}
for(i=0;i<size;++i)
if(num[i]%2==0)
count+=1;
cout<<"\n Number of even elements: "<<count;
}
Initialization
Arrays can be initialized by a comma-separated list of expressions enclosed in braces:
int array[4] = { 9, 8, 7 }; // a[0]=9, a[1]=8, a[2]=7
When the list of initializers is shorter than the size of the array, the remaining elements are
initialized to 0. If uninitialized, external and static arrays are automatically initialized to 0.
This is not so for automatic arrays, which start with undefined values.
An array declared with an explicit initializer list and no size expression is given the size of the
number of initializers. The following two arrays are equivalent:
char laura[] = { 'l', 'm', 'p' };
char laura[3] = { 'l', 'm', 'p' };

3
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir

L7-3 Null Terminated Strings


The most common use of one dimensional array is for character strings. The null terminated
string is a character array with a null character at the end. The characters form the string with
a null character indicating the termination of the string. A null terminated string can be
declared as
char name[10];
It will hold 10 characters with a null at the end. The size of the array can be more than the
length of the array. The array can be initialized as
char name[10]={'j','e','s','u','s'};
The first 5 elements are initialized and rest elements are null characters. Here is a
program which calculates the length of the string.
#include<iostream.h>
main()
{
char name[15];
int i=0;
cout << " Enter your name " <<endl;
cin >> name;
while(name[i]!='\0')
{
i++;
}
cout << "Lenght of the name is :" << i << endl;

Enter your name


Sarmed
Length of the name is: 6

The character array is declared by the statement

4
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
char name[15];
The length of the name can be at most 15. The arrays is assigned by taking the input from the
user by the statements
cout << " Enter your name " << endl;
cin >> name
Variable name is assigned the string entered by the user. Each element of the array is
referenced and checked whether it is null or not by the statement
while(name[i]!='\0')
Until a null character is not encountered variable i is incremented by the statement
i++;
When a null character is encountered while loop is terminated and length is printed by the
statement
cout << "Length of the name is : " << i << endl;

L7-4 Multidimensional Arrays


The multidimensional arrays are arrays of arrays. The general form of a Multidimensional
array is: -
Type variable_name[Size1][Size2]..[Size n];
The two dimensional array can be declared as
int age[2][5];
this array has two rows and 5 columns. The three dimensional array can be declared as
int age[2][3][5];
When an element of the array of n dimensional is referenced it uses n index values. For
example first element of a two dimensional array declared above is referred as age[0][0] as
the index starts from zero and last element is referred as age[1][4]. Here is a program which
calculates the average of the elements of the row of the two dimensional array.

#include<iostream,h>
void main ()
{
int age[2][5]= { {12,13,14,15,15}, {12,16,17,13,12}};
int i,j;
5
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
int sum=0,avg=0;
for(i=0;i<2;i++)
{
for(j=0;j<5;j++)
{
sum=sum+age[i][j];
}
avg=sum/5;
cout << "Average of the elements of the
row " << i+1 << " is " << avg << endl;
sum=0;
}}

The program initializes and declares the two dimensional array by the statement
int age[2][5]= { {12,13,14,15,15}, { 12,16,17,13,12}};
Elements of the first row and second row are initialized as {12,13,14,15,15} and
{ 12,16,17,13,12} respectively. The elements are accessed using the statement as
sum=sum+age[i][j];
age[i][j] refers to the element of row i and column j. This statement calculates the sum of the
elements of the row. After the sum of the elements of a row is calculated then average is
calculated by the statement.
avg=sum/5;
Sum is again initialized to zero. Then again the same process repeats for the second.

6
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir

Example1: Write a program to fill the following array using a specific equation

#include <iostream.h>
main( ){
int i, j, num[3][4];
for(i=0;i<3;++i)
for(j=0;j<4;++j)
num[i][j]=(i*4)+j+1;
}

Example 2: write a program to read a set of number and store it in the matrix, then find
the average of each row.

#include <iostream.h>
#define rows 3
#define columns 5
main( ){
int i, j, matrix[rows][columns];
float sum, average;
for(i=0;i<rows;++i){ /*Read numbers into the matrix*/
cout<<"\n Enter "<<columns<<" elements for row "<<i+1<<":";
for(j=0;j<columns;++j)
cin>>matrix[i][j];
} /*Compute sum & average for each row*/
for(i=0;i<rows;++i){
sum=0;
for(j=0;j<columns;++j)
sum+=matrix[i][j];
average=sum/columns;
cout<<"\n Average row "<<i+1<<" = "<<average;
}}

7
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir

Example 3: writes a program to read a set of name and storing in one dimension array

#include <iostream.h>
void main( ){
char name[100][20];
int n, i;
n =0;
do{
cout<<"\n Enter name (press RETURN to stop):";
gets(name[n]);
}while(name[n++][0] != '\0');
for(i=0;i<n;++i)
cout<<"\n "<<name[i];
}

Example 4: Write a program to find the largest number of the main diagonal of two
dimensional array

#include <iostream.h>
main( )
{ int i ,max;
int x[3][3]={7, 12, 16, 3, 14, 25, 5, 2, 8};
max = x[0][0];
for(i=0;i<3;++i)
if(x[i][i] >max)
max = x[i][i];
cout>> max;
}

Example 5: Write a program to exchange the Elements secondary diagonal of array


A with main diagonal of the array B

8
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir

#include <iostream.h>
main( ){
int i,j,c;
int a[4][4]={16, 21, 23, 25, 14, 12, 31, 9, 7, 19, 17, 5, 18, 2, 1, 4};
int b[4][4]={1, 6, 5, 11, 3, 8, 2, 18, 7, 9, 10, 12, 16, 5, 14, 32};
for(i=0;i<4;++i)
for(j=0;j<4;++j)
if(i+j ==3){
c=a[i][j];
a[i][j]=b[i][i];
b[i][i]=c;}
cout <<"\n A=";
for(i=0;i<4;++i){
cout<<"\n";
for(j=0;j<4;++j)
cout <<"\t"<< a[i][j];}
cout<<"\n B=";
for(i=0;i<4;++i){
cout <<"\n";
for(j=0;j<4;++j)
cout<<" \t"<<b[i][j]);
}
}

Example 6 Writes a program to find the sum of the array those elements are

#include < iostream.h >


main()
{ int i,j,a[3][3]={8, 2, 4, 4, 6, 12, 5, 3, 8};
int sum = 0;
for(i=0;i<3;++i)
for(j=0;j<3;++j)
sum + = a[i][j];
cout<<"\n sum = "<<sum;
}

9
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir

Example 7: Writes a program to create array [C] whose that value result from adding of
array B and A and Minus the value of the matrix D

#include < iostream.h >


main( ){
int i, j, a[3][3] ={12, 6, 12, 8, 7, 5, 4, 9, 3};
int b[3][3]={6, 7, 8, 3, 4, 2, 5, 4, 4};
int c[3][3],d[3][3]={9, 21, 13, 7, 5, 12, 16, 24, 3};
for(i=0;i<3;++i) {
cout<<"\n";
for(j=0;j<3;++j) {
c[i][j] =(a[i][j] + b[i][j]) - d[i][j];
cout<<"\t "<< c[i][j];
}}}

Example 8: write a program to replace the main diagonal with the first row

#include < iostream.h >


main( ){
int i, j, b, a[3][3];
for(i=0;i<3;++i)
for(j=0;j<3;++j)
cin>> a[i][j];
for(i=0;i<3;++i)
for(j=0;j<3;++j)
if(i == 0){
b =a[i][j];
a[i][j] =a[j][j];
a[j][j] =b;
}
for(i=0;i<3;++i){
cout<<"\n";
for(j=0;j<3;++j)
cout <<"\t "<< a[i][j];
}}

11
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir

Example 9: Write a program to find the average of four students with four degree
using array

#include < iostream.h >


main( ){
int i, j, a[4][4];
float v[4];
for(i=0;i<4;++i)
{
v[i]=0.0;
for(j=0;j<4;++j)
cin>> a[i][j];
}
for(i=0;i<4;++i) {
for(j=0;j<4;++j)
v[i] += a[i][j];
v[i] = v[i]/4; }
for(i=0;i<4;++i)
cout<<"\n "<< v[i]);
}

Example 10: Write a program to replace the elements of row with column

#include < iostream.h >


main( )
{ int i, j, b;
int a[4][4]={16, 22, 18, 7, 15, 21, 22, 13, 35, 31, 15, 11, 8, 12, 21, 17}; for(i=0;i<4;++i)
for(j=0;j<4;++j)
if(j >i)
{ B = a[i][j];
a[i][j] = a[j][i];
a[j][i] = b;
}
for(i=0;i<4;++i)
{
Cout<<"\n";
for(j=0;j<4;++j)
cout<"\t "<< a[i][j];
}}
11
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir

Example 11: Write a program to multiply the first row of the Array [A] with first
column of array [B]

#include < iostream.h >


main( ){
int i, j, c=0, a[2][3]={2,3,5,4,2,7};
int b[3][3]={2,6,9,6,7,2,5,8,1};
for(i=0;i<3;++i)
c += a[0][i]*b[i][0];
printf("\n %d", c);
}

Example 12: Write a program to arrangement the Array A ascending

#include < iostream.h >


Void main( ){
int i, j, k, b;
int a[5] = {9,11,15,3,8};
for(i=0;i<5;++i)
{ k=i;
for(j=i;j<5;++j)
if(a[j] < a[k]) k = j;
b = a[i];
a[i] = a[k];
a[k] = b;
cout<<"\n "<< a[i];
}}

12
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir

Example 13: Write a program to find the numbers divisible by 3 within the matrix
[A] two-dimensional and find the sum of these numbers and the matrix is

#include < iostream.h >


main( ) {
int i, j, a[3][3] = {22,21,17,5,13,8,12,7,15};
int s = 0;
for(i=0;i<3;++i)
for(j=0;j<3;++j)
if(a[i][j]%3 == 0) {
cout<<"\n";
cout<<" \t"<< a[i][j];
s += a[i][j]; }
cout<<"\n "<< s;
}

Example 15: Write a program to read numbers in a matrix and arrangement


arranged inversely in other Matrix. Note that the matrices one-dimensional

#include < iostream.h >


main( ){
int i, x[4] = {11,8,5,6}, b[4];
for(i=0;i<4;++i) {
b[i] = x[3-i];
cout<<"\n"<<b[i];
}}

13
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir

Function
A function is a group of statements that together perform a task. Every C++ program has
at least one function, which is main, and all the most trivial programs can define additional
functions. You can divide up your code into separate functions. How you divide up your
code among different functions is up to you, but logically the division usually is so each
function performs a specific task. A function declaration tells the compiler about a
function's name, return type, and parameters. A function definition provides the actual
body of the function. The C++ standard library provides numerous built-in functions that
your program can call. For example, function strcat to concatenate two strings, function
memcpy to copy one memory location to another location and many more functions. A
function is knows as with various names like a method or a sub-routine or a procedure etc.
Why use function
Basically there are two reasons because of which we use functions
1. Writing functions avoids rewriting the same code over and over. For example - if you
have a section of code in a program which calculates the area of triangle. Again you want
to calculate the area of different triangle then you would not want to write the same code
again and again for triangle then you would prefer to jump a "section of code" which
calculate the area of the triangle and then jump back to the place where you left off. That
section of code is called „function'.
2. Using function it becomes easier to write a program and keep track of what they are
doing. If the operation of a program can be divided into separate activities, and each
activity placed in a different function, then each could be written and checked more or less
independently. Separating the code into modular functions also makes the program easier
to design and understand.

Properties of Functions
 Every function has a unique name. This name is used to call function from “main()”
function.

 A function performs a specific task.


14
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
 A function returns a value to the calling program.

Advantages of Functions in C++

 Functions has top down programming model. In this style of programming, the
high level logic of the overall problem is solved first while the details of each lower
level functions is solved later.

 A C++ programmer can use function written by others

 Debugging is easier in function

 It is easier to understand the logic involved in the program

 Testing is easier

Types of Function in C++:


(i). Library Functions in C++
C++ provides library functions for performing some operations. These functions are
present in the C++ library and they are predefined.
For example sqrt() is a mathematical library function which is used for finding the square
root of any number .
The function cin and cout are input and output library function similarly we have
strcmp() and strlen() for string manipulations. To use a library function we have to
include some header file using the preprocessor directive #include.

(ii). User Defined Functions in C++


A user can create their own functions for performing any specific task of program are
called user defined functions. To create and use these function we have to know these 3
elements.
1. Function Declaration
2. Function Definition
3. Function Call
1-Function Declarations:
15
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
A function declaration tells the compiler about a function name and how to call the
function. The actual body of the function can be defined separately.
A function declaration has the following parts:
return_type function_name (parameter list);

2- Defining a Function:
The general form of a C++ function definition is as follows
return_type function_name ( parameter list )
{
body of the function
}
A C++ function definition consists of a function header and a function body. Here are all
the parts of a function:

Return Type: A function may return a value. The return_type is the data type of the
value the function returns. Some functions perform the desired operations without
returning a value. In this case, the return_type is the keyword void.

Function Name: This is the actual name of the function. The function name and the
parameter list together constitute the function signature
Parameters: A parameter is like a placeholder. When a function is invoked, you pass a
value to the parameter. This value is referred to as actual parameter or argument. The
parameter list refers to the type, order, and number of the parameters of a function.
Parameters are optional; that is, a function may contain no parameters.
Any variable declared in the body of a function is said to be local to that function. Other
variables which are not declared either as arguments or in the function body are considered
“global” to the function and must be defined externally. For example
Void square (int a, int b) → a,b are the formal arguments.
Float output (void) → function without formal arguments
Example 1:
void printmessage ( ) Example 2:
{ int max (int a, int b)
{
int c;16
if (a > b) c = a;
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
cout << “University of Technology”;
}
void main ( )
{
printmessage( );
}

Function Body: The function body contains a collection of statements that define what
the function does.
Example:
Following is the source code for a function called max. This function takes two
parameters num1 and num2 and returns the maximum between the two:
// function returning the max between two numbers
int max(int num 1, int num 2)
{
// local variable declaration
int result;
if (num 1 > num 2)
result = num 1;
else
result = num 2;
return result;
}
For the above defined function max, following is the function declaration:
int max(int num 1, int num 2);
Parameter names are not important in function declaration only their type is required, so
following is also valid declaration:
int max(int, int);

17
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
Function declaration is required when you define a function in one source file and you call
that function in another file. In such case, you should declare the function at the top of the
file calling the function.
3- Calling a Function:
While creating a C++ function, you give a definition of what the function has to do. To
use a function, you will have to call or invoke that function.
When a program calls a function, program control is transferred to the called function. A
called function performs defined task and when its return statement is executed or when its
function ending closing brace is reached, it returns program control back to the main
program.
To call a function, you simply need to pass the required parameters along with function
name, and if function returns a value, then you can store returned value.
For example:
#include <iostream.h >
// function declaration
int max(int num 1, int num 2);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get m ax value.
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
// function returning the max between two numbers
int max(int num 1, int num 2)
{
// local variable declaration
18
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
int result;
if (num 1 > num 2)
result = num 1;
else
result = num 2;
return result;
}

Simple Example of Function in C++


#include <iostream.h>
int addition (int, int); //Function Declaration
int addition (int a, int b) //Function Definition
{ int r;
r=a + b;
return r;
}
int main()
{ int z;
z= addion(10,3); //Function Call
cout<< "the result of addition two = "<< z;
return 0; }
Output: The Result is 13

A function depending on whether arguments are present or not and whether a value is
returned or not may belong to any one of the following categories:
(i ) Functions with no arguments and no return values.
When a function has no arguments, it does not return any data from calling function.
When a function does not return a value, the calling function does not receive any data
from the called function. That is there is no data transfer between the calling function and
the called function.
#include <iostream.h>
void printmsg()
{ cout<<"Hello ! I Am A Function .";

19
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
}
int main()
{ printmsg();
return 0;
}
Output : Hello ! I Am A Function .
(ii) Functions with arguments and no return values.
When a function has arguments data is transferred from calling function to called function.
The called function receives data from calling function and does not send back any values
to calling function. Because it doesn‟t have return value.
#include <iostream.h>
void add(int,int);
void main() {
int a, b;
cout<<“enter value”;
cin>>a>>b;;
add(a,b); }
void add (intx, inty) {
int z ;
z=x+y;
cout<<"The sum =" <<z; }
output : enter values 2 3
The sum = 5

(iii) Functions with arguments and return values.


In this data is transferred between calling and called function. That means called function
receives data from calling function and called function also sends the return value to the
calling function.
Example #include < iostream.h>
int add( int, int);
void main() {
21
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
int a,b,c;
cout <<“enter value”;
cin >> a >> b;
c=add(a,b);
cout << "The sum = "<< c);
}
int add (int x, int y)
{ int z; z=x+y;
return z;
}
output : enter values 2 3
The sum = 5

(iv) Functions with no arguments and return values.


When function has no arguments data cannot be transferred to called function. But the
called function can send some return value to the calling function.
Example
#include<iostream.h>
int add( );
main() {
int c;
c=add();
cout <<"The sum ="<< c;
}
int add () {
int x,y,z;
cout << “enter value”;
cin << a << b;
z=x+y;
return z;
}
21
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
Output: enter values 2 3
The sum = 5
Function Arguments:
If a function is to use arguments, it must declare variables that accept the values of the
arguments. These variables are called the formal parameters of the function. The formal
parameters behave like other local variables inside the function and are created upon entry
into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a function:
Call Type Description
Call by value This method copies the actual value of
an argument into the formal parameter
of the function. In this case, changes
made to the parameter inside the
function have no effect on the argument.

This method copies the reference of an


argument into the formal parameter.
Inside the function, the reference is used
to access the actual argument used in the
call. This means that changes made to
the parameter affect the argument.
Call by pointer This method copies the address of an
argument into the formal parameter.
Inside the function, the address is used
to access the actual argument used in the
call. This means that changes made to
the parameter affect the argument.

Call by reference

22
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
Call by value
The call by value method of passing arguments to a function copies the actual value of an
argument into the formal parameter of the function. In this case, changes made to the
parameter inside the function have no effect on the argument.
By default, C++ uses call by value to pass arguments. In general, this means that code
within a function cannot alter the arguments used to call the function. Consider the
function swap() definition as follows.
// function definition to swap the values.
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}
Now, let us call the function swap() by passing actual values as in the following example:

#include <iostream.h>
// function declaration
void swap(int x, int y);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
// calling a function to swap the values.
swap(a, b);
cout << "After swap, value of a :" << a << endl;
23
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
cout << "After swap, value of b :" << b << endl;
return 0;
}
When the above code is put together in a file, compiled and executed, it produces the
following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :100
After swap, value of b :200
Which shows that there is no change in the values though they had been changed inside
the function.

Call by reference
The call by reference method of passing arguments to a function copies the reference of
an argument into the formal parameter. Inside the function, the reference is used to access
the actual argument used in the call. This means that changes made to the parameter affect
the passed argument.
To pass the value by reference, argument reference is passed to the functions just like any
other value. So accordingly you need to declare the function parameters as reference types
as in the following function swap(), which exchanges the values of the two integer
variables pointed to by its arguments.
// function definition to swap the values.
void swap(int &x, int &y)
{
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
return;
}

24
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
For now, let us call the function swap() by passing values by reference as in the following
example:

#include <iostream>
using namespace std;
// function declaration
void swap(int &x, int &y);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
/* calling a function to swap the values using variable reference.*/
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
return 0;
}
When the above code is put together in a file, compiled and executed, it produces the
following result:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
By default, C++ uses call by value to pass arguments. In general, this means that code
within a function cannot alter the arguments used to call the function and above mentioned
example while calling max() function used the same method.
Default Values for Parameters:

25
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
When you define a function, you can specify a default value for for each of the last
parameters. This value will be used if the corresponding argument is left blank when
calling to the function.
This is done by using the assignment operator and assigning values for the arguments in
the function definition. If a value for that parameter is not passed when the function is
called, the default given value is used, but if a value is specified this default value is
ignored and the passed value is used instead. Consider the following example:
#include <iostream>
using namespace std;
int sum(int a, int b=20)
{
int result;
result = a + b;
return (result);
}
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int result;
// calling a function to add the values.
result = sum(a, b);
cout << "Total value is :" << result << endl;
// calling a function again as follows.
result = sum(a);
cout << "Total value is :" << result << endl;
return 0;
}
When the above code is compiled and executed, it produces the following result:
Total value is :300
26
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
Total value is :120

27
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
Q1 Write a function named "sum_from_to" that takes two integer arguments, call
them "first" and "last", and returns as its value the sum of all the integers between
first and last inclusive. Thus, for
example,
cout << sum_from_to(4,7) << endl; // will print 22 because 4+5+6+7 = 22
cout << sum_from_to(-3,1) << endl;
// will print -5 'cause (-3)+(-2)+( 1)+0+1 = -5
cout << sum_from_to(7,4) << endl; // will print 22 because 7+6+5+4 = 22
cout << sum_from_to(9,9) << endl; // will print 9
Sol:-
int sum_from_to (int first, int last)
{
int i, partial_sum = 0;
if (first <= last)
for (i = first; i <= last; ++i)
partial_sum += i;
else
for (i = first; i >= last; --i)
partial_sum += i;
return partial_sum;
}

Q2 Write a function named "is_prime" that takes a positive integer argument and returns
as its value the integer 1 if the argument is prime and returns the integer 0 otherwise
Sol:-
#include<iostream.h>
int is_prime (int n)
{
int j=0 ;
for ( int i = 1 ; i <= n ; i++)
28
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
if ( n % i == 0 )
++j;
if (j==2)
return 1;
else
return 0;
}
void main ()
{
int x;
cin>> x;
cout<< is_prime(x);
}
Q3 Write a function named "enough" that takes one integer argument, call it "goal"
and returns as its value the smallest positive integer n for which 1+2+3+. . . +n is at
least equal to goal .
Thus, for example,
cout << enough(9) << endl; // will print 4 because 1+2+3+4 _ 9 but 1+2+3<9
cout << enough(21) << endl;// will print 6 'cause 1+2+ . . .+6 _ 21 but 1+2+ . . . 5<21
cout << enough(-7) << endl;// will print 1 because 1 _ -7 and 1 is the smallest
// positive integer
cout << enough(1) << endl; // will print 1 because 1 _ 1 and 1 is the smallest
// positive integer
Sol:-
int enough (int goal)
{
int n = 1, sum = 1;
while (sum < goal)
sum += ++n;
return n;
}
29
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
Q4 Write a function named "g_c_d" that takes two positive integer arguments and
returns as its value the greatest common divisor of those two integers. If the function
is passed an argument that is not positive (i.e., greater than zero), then the function
should return the value 0 as a sentinel value to indicate that an error occurred. Thus,
for example,
cout << g_c_d(40,50) << endl; // will print 10
cout << g_c_d(256,625) << endl; // will print 1
cout << g_c_d(42,6) << endl; // will print 6
If both arguments are positive, then Euclid's Algorithm for the g.c.d. is employed. The
first integer is Divided by the second, and then the second is divided by the remainder, and
then the first remainder is divided by the second, and so on until a remainder of 0 is
obtained. The g.c.d. will be the divisor that produced 0 remainder.

Sol:-
int g_c_d (int a, int b)
{
if (a <= 0 || b <= 0) // a parameter is not positive
return 0; // exit and return the error sentinel
int remainder = a % b;
// Get remainder when a is divided by b.
while (remainder != 0)
{
a = b;
b = remainder;
remainder = a % b;
}

Q6 Write a function named "digit_name" that takes an integer argument in the


range from 1 to 9 , inclusive, and prints the English name for that integer on the
computer screen. No newline character should be sent to the screen following the
digit name. The function should not return a value. The cursor should remain on the
31
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
same line as the name that has been printed. If the argument is not in the required
range, then the function should print "digit error" without the quotation marks but
followed by the newline character. Thus, for example,
the statement digit_name(7); should print seven on the screen;
the statement digit_name(0); should print digit error on the screen and place
the cursor at the beginning of the next line

Sol:-.
void digit_name (int digit_value)
{
switch (digit_value)
{
case 1 : cout << "one"; break;
case 2 : cout << "two"; break;
case 3 : cout << "three"; break;
case 4 : cout << "four"; break;
case 5 : cout << "five"; break;
case 6 : cout << "six"; break;
case 7 : cout << "seven"; break;
case 8 : cout << "eight"; break;
case 9 : cout << "nine"; break;
default : cout << "digit error" << endl;
}
}
Q6 write a function to implement the factorial
#include < iostream.h>
int fact (int);
void main( )
{ int res;
int n=5;
res=fact(n);
31
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
cout << res;
}
int fact(int n )
{ int f=1;
for(int i=1;i<=n;i++)
{
f*=i;
}
return f;
}

Q7 write a function to Sorts the three values passed to it into increasing order.
#include < iostream.h>
void sort3 (float & x, float & y, float & z);
void swap_floats( float &, float & );
void main ) (
{float x,y,z;
cin>>x>>y>>z;
sort3 (x,y,z);
cout << x<<y<<z;

}
void swap_floats( float &a, float &b)
{float temp;
temp=a;
a=b;
b=temp;
}

void sort3 (float & x, float & y, float & z)


{

if (x <= y && y <= z) // the values are already in order;


; //do nothing
else if (x <= y) // then z < y (or we'd have stopped above)
{
swap_floats (z, y);
// After this call, y < z and x <= z are true
//but we don't know how x and y compare.
if (x > y)
32
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
swap_floats (x, y);
// Now x < y <= z must be true.
}
else
// If neither of the above is true, then we know that y < x
{
swap_floats (x, y); // After this call, x < y is true.
if (y <= z)
// the values are now in correct order;
; //do nothing
else // it must be the case that z < y
{
swap_floats (y, z); // After this call, y <= z is true.
if (x > y)
swap_floats (x, y(;
}
}
}

Q8 write a function in order to reverses the order of the objects in an array.

void reverse (float a[], int n)


{
int i = 0, j = n - 1;
while (i < j)
swap_floats (a[i++], a[j--]);
}

Q9 writes a function to Calculates and returns the sum of the numbers in an array.

float sum (const float a[], int n)


{
float sum_so_far = 0.0;
int i;
for (i = 0; i < n; ++i)
sum_so_far += a[i];
return sum_so_far;
33
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
}

Q10 write a function to return the location of target number in an array.

int location_of_target (const int a[], int n, int target)


{
int location = -1; // Target not seen yet.
int i;
for (i = 0; i < n; ++i)
if (a[i] == target)
location = i;
return location;
}
Q11 write a function to duplicate number
Example a=2 o/p a= 4
b=4 o/p b=16
// passing parameters by reference
#include <iostream.h>
void duplicate (int& a, int& b, int& c)
{
a*=2;
b*=2;
c*=2;
}
int main ()
{
int x=1, y=3, z=7;
duplicate (x, y, z);
cout << "x=" << x << ", y=" << y <<
", z=" << z;
return 0;
}

Default values in parameters.


When declaring a function we can specify a default value for each of the last

34
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
parameters. This value will be used if the corresponding argument is left blank when
calling to the function. To do that, we simply have to use the assignment operator and a
value for the arguments in the function declaration. If a value for that parameter is not
passed when the function is called, the default value is used, but if a value is specified this
default value is ignored and the passed value is used instead. For example:
// default values in functions
#include <iostream>
using namespace std;
int divide (int a, int b=2)
{
int r;
r=a/b;
return (r);
}
int main ()
{
cout << divide (12);
cout << endl;
cout << divide (20,4);
return 0;
}
O/p
6
5
As we can see in the body of the program there are two calls to function divide.
In the first one:
divide (12) we have only specified one argument, but the function divide allows up to two.
So the function divide has assumed that the second parameter is 2 since that is what we
have specified to happen if this parameter was not passed (notice the function declaration,
which finishes with int b=2, not just int b). Therefore the result of this function call is 6
(12/2).
In the second call:
divide (20,4) there are two parameters, so the default value for b (int b=2) is ignored and b
takes the value passed as argument, that is 4, making the result returned equal to 5 (20/4).

Overloaded functions.

35
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
In C++ two different functions can have the same name if their parameter types or number
are different. That means that you can give the same name to more than one function if
they have either a different number of parameters or different types in their parameters.
For example:
// overloaded function
#include <iostream.h>
int operate (int a, int b)
{
o/p
return (a*b);
10
} 2.5
float operate (float a, float b)
{
return (a/b);
}
int main ()
{
int x=5,y=2;
float n=5.0,m=2.0;
cout << operate (x,y);
cout << "\n";
cout << operate (n,m);
cout << "\n";
return 0;}

In this case we have defined two functions with the same name, operate, but one of them
accepts two parameters of type int and the other one accepts them of type float.
The compiler knows which one to call in each case by examining the types passed as
arguments when the function is called. If it is called with two ints as its arguments it calls
to the function that has two int parameters in its prototype and if it is called with two floats
it will call to the one which has two float parameters in its prototype.

36
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
In the first call to operate the two arguments passed are of type int, therefore, the function
with the first prototype is called; This function returns the result of multiplying both
parameters. While the second call passes two arguments of type float, so the function with
the second prototype is called. This one has a different behavior: it divides one parameter
by the other. So the behavior of a call to operate depends on the type of the arguments
passed because the function has been overloaded.
Notice that a function cannot be overloaded only by its return type. At least one of its
parameters must have a different type.

37
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
Recursivity.
Recursivity is the property that functions have to be called by themselves. It is
useful for many tasks, like sorting or calculate the factorial of numbers. For example, to
obtain the factorial of a number (n!) the mathematical formula would be:
n! = n * (n-1) * (n-2) * (n-3) ... * 1
more concretely, 5! (factorial of 5) would be:
5! = 5 * 4 * 3 * 2 * 1 = 120
and a recursive function to calculate this in C++ could be:
// factorial calculator
#include <iostream.h>
long factorial (long a)
{
if (a > 1)
return (a * factorial (a-1));
else
return (1);
}
int main ()
{
long number;
cout << "Please type a number: ";
cin >> number;
cout << number << "! = " <<
factorial (number);
return 0;}
Notice how in function factorial we included a call to itself, but only if the argument
passed was greater than 1, since otherwise the function would perform an infinite
recursive loop in which once it arrived to 0 it would continue multiplying by all the
negative numbers (probably provoking a stack overflow error on runtime). This function
has a limitation because of the data type we used in its design (long) for more simplicity.

38
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
The results given will not be valid for values much greater than 10! Or 15!, depending on
the system you compile it.

39
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
string.h, math.h and ctype.h
String functions:

The string functions can analyze and transform null terminated strings. In order to manipulate null
terminated strings header file <string.h> is included in the program. Commonly used string functions are: -

 strcat(s1, s2) - It concatenates two strings. It concatenates s2 at the end of s1.


 strcmp (s1, s2) – It is used to compare strings. It returns 0 if they are equal and less than 0 if s2<s1 and
greater than 0 if s2>s1.
 strlen(s1) – It returns the length of the string s1.
 strcpy(s1, s2) - It copies s2 into s1.
 strncat(s1, s2, n) - It appends substring to the string. It takes first n characters of string s2 and appends
s1.
 strncmp(s1,s2,n) – It compares first n characters of string s1 with first n characters of string s2.
 strchr(s1, ch) – Finds character ch in string s1. It returns the pointer at the first occurrence of ch.
 strstr(s1, s2) – Finds substring s2 in s1. It returns a pointer at the first occurrence of s1.
 strset(s1,ch) – Set characters of string s1 with character ch;

 strnset(s1,no,ch)—Set characters of string s1 with character ch from beginning to the location.

 strrev(s1)—Reverse string s1.

 struper(s1)--Convert string s1 from capital to small.

 strlwr(s1)—Convert string s1 from small to capital.

Here is a program which illustrates the working of string functions.

#include<iostream.h>
#include<string.h>
int main ()
{ int l;
char name[40]=" Tom is a good boy";
char name1[40]="Mary is a good girl";
char stri[40];
l=strlen(name);
cout << "The lenght of the string 1 is : " << l << endl;
if(strstr(name,"good"))
cout << "Substring good appears in string 1 " << endl;
if(strchr(name1,'M'))
cout << "Character M appears in sting 1 " << endl;
if(strcmp(name,name1)>0)
cout << "String 2 appears after string" << endl;
strcpy(stri,name1);
cout << "The copied string : " << stri << endl;
strncat(stri,name,4);
cout << " The modified string : " << stri << endl;
41
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
if(strncmp(stri,name1,3)==0)
cout << "First 3 characters of two strings are equal" << endl;
strcat(name," ");
strcat(name,name1);
cout << name << endl;
strupr(name);
cout << name << endl;
strlwr(name);
cout << name << endl;
strset(name,'k');
cout << name << endl;
strnset(name,'a',4);
cout << name << endl;
return(0); }
The result of the program is:-
The lenght of the string 1 is : 18
Substring good appears in string 1
Character M appears in sting 1
The copied string : Mary is a good girl
The modified string : Mary is a good girl Tom
First 3 characters of two strings are equal
Tom is a good boy Mary is a good girl
TOM IS A GOOD BOY MARY IS A GOOD GIRL
tom is a good boy mary is a good girl
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
aaaakkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
Press any key to continue
The statement

#include<string.h>

includes a header file <string.h> into the program. The statement

l=strlen(name);

computes the length of the string name. The function strlen(name) returns the length of the string name. The
length of the string is 18. The statement

if(strstr(name,"good"))

checks whether substring “good” appears in the string name. The function strstr(name,”good”) returns true as
“good” appears in string name. The statement

41
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
if(strchr(name1,'M'))

checks whether character ‘M’ appears in string name1. The function strchr(name1,’M’) returns true as character
‘M’ appears in string name1. The statement

if(strcmp(name,name1)>0)

compares two strings name and name1. It returns false as string name< string name1.

The statement

strcpy(stri,name1);

copies content of string name1 into string stri. The statement

strncat(stri,name,4);

concatenates first 4 letters of string name to string stri. The statement

if(strncmp(stri,name1,3)==0)

compares first 3 characters of string name1 with first 3 characters of string stri. It returns true as first 3
characters of name1 and stri are same. The statement

strcat(name," ");

concatenates whitespace at the end of the string name. The statement

strcat(name,name1);

The two statements

strupr(name);

strlwr(name);

convert the string name from small to capital and then from capital to small.

The statement

strset(name,'k');

set the characters of the string names to the character k.

The statement

strnset(name,'a',4);

set the first 4 characters of string name to character a;

Math functions:

The mathematical functions provide the functionality of automatically computing some of the functions such
as trigonometric functions, hyperbolic functions, exponential and logarithmic functions and other miscellaneous

42
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
functions. In order to use these functions header file <math.h> is included into the program. Some of the
commonly used functions are:-

 abs() – The function abs() returns the absolute value of integer parameter.
 acos() -The function acos() returns the arc cosine of the argument. The range of the argument is from -1
to 1. Any argument outside this range will result in error.
 asin()- The function asin() returns the arc sine of the argument. The range of the argument is from -1 to 1.
Any argument outside the range will result in error.
 atan()- The function atan() returns the arc tangent of the argument.
 atan2()- The function atan2() returns the arc tangent of y/x. It accepts two arguments.
 ceil()- The function ceil() returns the smallest integer which is not less than the argument.
 cos() – The function cos() returns the cosine of the argument. The value of the argument must be in
radians.
 cosh() –The function cosh() returns the hyperbolic cosine of the argument.
 exp()- The function exp() returns the exponential of the argument.
 fabs()- The function fabs() returns the absolute value of floating point parameter.
 floor()- The function floor() returns the largest integer which is not greater than the argument.
 fmod()- The function fmod() returns the remainder of floating point division of the two arguments.
 log() – The function log() returns the natural logarithm of the argument. An error is encountered if the
argument is negative or zero.
 log10()- The function log10() returns base 10 logarithm of the argument. An error occurs if the argument
is negative or zero.
 pow()- The function pow() returns the base raised to the power.
 sin()- The function sin() returns the sine of the argument. The value of the argument must be in radians.
 sinh()- The function sinh() returns hyperbolic sine of the argument.
 sqrt()- The function sqrt() the square root of the argument. An error occurs if the value of the argument is
negative.
 tan()- The function tan() returns the tangent of the argument. The value of the argument must be in
radians.
 tanh()- The function returns the hyperbolic tangent of the argument.
Here is a program which illustrates the working of the math functions.

#include<iostream.h>
#include<math.h>
int main()
{
double a=-0.707;
double a1=(45.0*3.14)/180;
double a2=2;
double b=0.0;
b=acos(a);
cout << "The arc cosine of " << a << ": " << b << endl;
b=asin(a);
cout << "The arc sin of" << a << ": " << b << endl;
b=atan(a);
cout << "The arc tangent of " << a << " : " << b << endl;
b=ceil(a);

43
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
cout << "The ceiling of " << a << " : " << b << endl;
cout << "The floor of " << a << " : " << floor(a) << endl;
cout << "The cosine of " << a1 << " : " << cos(a1) << endl;
cout << "The exponential of " << a2 << " : " << exp(a1) << endl;
cout << "The log of " << a2 << " : " << log(a2) << endl;
cout << "The base " << a2 << " raised to the power " << b << " : " << pow(a2,b) << endl;
cout << "The square root of " << a2 << " : " << sqrt(a2) << endl;
return(0);
}
The result of the program is:-
The arc cosine of -0.707: 2.35604
The arc sin of-0.707: -0.785247
The arc tangent of -0.707 : -0.615409
The ceiling of -0.707 : 0
The floor of -0.707 : -1
The cosine of 0.785 : 0.707388
The exponential of 2 : 2.19241
The log of 2 : 0.693147
The base 2 raised to the power 0 : 1
The square root of 2 : 1.41421
Press any key to continue

The statement

#include<math.h>

includes a header file <math.h> into the file. The statement

b=acos(a);

returns the arc cosine of argument a. The arc cosine of -0.707 is 2.35604. The statement

b=asin(a);

returns the arc sine of argument a. The arc sin of a -0.707 is -0.785247. The statement

b=atan(a);

returns the arc tangent of argument a. The arc tangent of -0.707 is -0.615409. The statement

b=ceil(a);

44
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
returns the ceiling of argument a. The ceiling of -0.707 is 0. The statement

cout << "The floor of " << a << " : " << floor(a) << endl;

displays the floor of argument a. The floor of -0.707 is -1. The statement

cout << "The cosine of " << a1 << " : " << cos(a1) << endl;

displays the cosine of the argument a1. The cosine of 45 degrees is 0.707. The argument a1 contains the radian
value of 45 degrees. The statement

cout << "The exponential of " << a2 << " : " << exp(a1) << endl;

displays the exponential of argument of a2. The exponential of 2 is 2.19241. The statement

cout << "The log of " << a2 << " : " << log(a2) << endl;

displays the logarithm of argument a2. The logarithm of 2.0 is 0.69. The statement

cout << "The base " << a2 << " raised to the power " << b << " : " << pow(a2,b);

displays the base a2 raised to the argument b. The base 2.0 raised to the power 0 is 1. The statement

cout << "The square root of " << a2 << " : " << sqrt(a2) << endl;

displays the square root of the argument a2. The square root of 2.0 is 1.414.

Character Functions

The C++ char functions are extremely useful for testing and transforming characters. These functions are
widely used and accepted. In order to use character functions header file <cctype> is included into the program.
Some of the commonly used character functions are:

 isalnum()- The function isalnum() returns nonzero value if its argument is either an alphabet or integer.
If the character is not an integer or alphabet then it returns zero.
 isalpha() - The function isalpha() returns nonzero if the character is an uppercase or lower case letter
otherwise it returns zero.
 iscntrl() - The function iscntrl() returns nonzero if the character is a control character otherwise it returns
zero.
 isdigit()- The function isdigit() returns nonzero if the character is a digit, i.e. through 0 to 9. It returns zero
for non digit character.
 isgraph()- The function isgraph() returns nonzero if the character is any printable character other than
space otherwise it returns zero.
 islower()- The function islower() returns nonzero for a lowercase letter otherwise it returns zero.
 isprint()- The function isprint() returns nonzero for printable character including space otherwise it
returns zero.
 isspace()- The function isspace() returns nonzero for space, horizontal tab, newline character, vertical tab,
formfeed, carriage return; otherwise it returns zero.
 ispunct()- The function ispunct() returns nonzero for punctuation characters otherwise it returns zero.
The punctuation character excludes alphabets, digits and space.
 isupper() - The function isupper() returns nonzero for an uppercase letter otherwise it returns zero.

45
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
 tolower()- The function tolower() changes the upper case letter to its equivalent lower case letter. The
character other than upper case letter remains unchanged.
 toupper()- The function toupper() changes the lower case letter to its equivalent upper case letter. The
character other than lower case letter remains unchanged.
 isxdigit() - The function isxdigit() returns nonzero for hexadecimal digit i.e. digit from 0 to 9, alphabet 'a'
to 'f' or 'A' to 'F' otherwise it returns zero.
Here is a program which illustrates the working of character functions.

#include<iostream.h>
#include<ctype.h>

int main ()
{
char ch='a';
char ch1='Z';
char ch2=' ';
char ch3='0';
char ch4='?';
char ch5='F';
if(isalpha(ch))
{
if(islower(ch))
{
cout << "The character 'a' is an lower case letter." << endl;
}
}
if(isupper(ch5))
{
if(isxdigit(ch5))
{
cout << "The character 'F' is a upper case letter and hexadecimal digit" << endl;
}
}
if(isalnum(ch3))
{
if(isdigit(ch3))
{
cout << "The character '0' is an alphanumeric character and a digit" << endl;
}
}

46
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
if(isprint(ch2))
{
if(isspace(ch2))
{
if(isgraph(ch2))
{
cout << "The character is a graphic character" << endl;
}
else
{
cout << "The character " " is a printable character and space" << endl;
}
}
}
if(ispunct(ch4))
{
cout << "The character '?' is a punctuation character" << endl;
}
cout << "The uppercase letter of 'a' is : " << static_cast<char>(toupper(ch)) << endl;
return(0);
}

The result of the program is:-


The character 'a' is an lower case letter.
The character 'F' is a upper case letter and hexadecimal digit
The character '0' is an alphanumeric character and a digit
The character is a printable character and space
The character '?' is a punctuation character
The uppercase letter of 'a' is : A
Press any key to continue
The statement

#include<ctype.h>

includes a header file <ctype.h> into the program. The statement

if(isalpha(ch))

checks whether character ch is alphanumeric. It returns nonzero value as 'a' is alphanumeric. The statement

if(islower(ch))
47
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
checks whether character ch is a lower case letter. It returns nonzero value as 'a' is lower case letter. The
statement

if(isupper(ch5))

checks whether character ch5 is a upper case letter. It returns nonzero value as 'F' is a upper case letter. The
statement

if(isxdigit(ch5))

checks whether character ch5 is a hexadecimal digit. It returns nonzero value as 'F' is a hexadecimal digit. The
statement

if(isalnum(ch3))

checks whether character ch3 is a alphanumeric character. It returns nonzero value as '0' is an alphanumeric
character. The statement

if(isdigit(ch3))

checks whether character ch3 is a digit. It returns nonzero value as '0' is digit. The statement

if(isprint(ch2))

checks whether character ch2 is a printable character . It returns nonzero value as character ch2 ' ' is a printable
character. The statement

if(isspace(ch2))

checks whether character ch2 is a space character . It returns nonzero value as character ch2 ' ' is space. The
statement

if(isgraph(ch2))

checks whether character ch2 is a graphical character . It returns zero value as character ch2 is not a graphical
character. The statement

if(ispunct(ch4))

checks whether character ch4 is punctuation character. It returns nonzero value as character ch4 '?' is a question
mark. The statement

cout << "The uppercase letter of 'a' is : " << static_cast<char>(toupper(ch)) << endl;

displays the upper case equivalent of letter 'a'. The function toupper(ch) converts lower case letter to upper case
letter and i`1t returns integer value therefore type casting is used to convert integer type value to character type
value. If type casting is not used then it will return the ASCII code of upper case letter.

# include <iostream>
# include <cstring>
using namespace std;
int main ( )
48
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir
{
char str1 [30] = "Nour", str2 [30] = "Noor", str3 [30] = "Noura";
cout << strcmp (str1, str2) << endl; 1

cout << strcmp (str1, str3) << endl; -1

cout << strcmp (str2, str1) << endl; -1

cout << strcmp (str2, str3) << endl; -1

cout << strcmp (str3, str1) << endl; 1

cout << strcmp (str3, str2) << endl; 1

cout << strncmp (str1, str2, 2) << endl; 0

cout << strncmp (str1, str2, 3) << endl; 1

cout << strncmp (str1, str2, 5) << endl; 1

cout << strncmp (str2, str1, 2) << endl; 0

cout << strncmp (str2, str1, 3) << endl; -1

cout << strncmp (str2, str1, 5) << endl; -1

cout << strncmp (str1, str3, 3) << endl; 0

cout << strncmp (str1, str3, 4) << endl; 0

cout << strncmp (str1, str3, 5) << endl; -1

cout << strncmp (str3, str1, 5) << endl; 1


return 0;
}

49
Subject: C++ Department: Control and systems
Class: first Lecturer: Karam Samir

# include <iostream>
# include <cstring>
using namespace std;
int main ( )
{
char str1 [30], str2 [30], str3 [30];

cout << "enter your name: ";

cin.getline (str1, 30, '\n');

cout << "str1 = " << str1 << endl;

cout << "enter your son's name: ";

cin >> str2;

cout << "str2 = " << str2 << endl;

cout << "length of str1 = " << strlen (str1 ) << endl;

cout << "length of str2 = " << strlen (str2 ) << endl;

return 0; enter your name: hamada shaban


}
str1 = hamada shaban
enter your son's name: abdul rahman
str2 = abdul
length of str1 = 13
length of str2 = 5
cstring Functions

Find the error in each of the following program segments. Assume the
following declarations and statements:

int *zPtr;
int *aPtr = 0;
int number;
int z[5] = { 1, 2, 3, 4, 5}

a) ++zPtr;

b) number = zPtr;

c) number = *zPtr[2];

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


cout << zPtr[i] << endl;

e) ++z;

f) char s[10];
cout << strncpy ( s, "hello ", 5 ) << endl;

g) char s[12];
strcpy ( s, "Welcome Home " );

h) if ( strcmp ( string1, string2 ) )


cout << "The strings are equal " << endl;

a) zPtr has not been initialized.


zPtr = z;

b) The pointer is not dereferenced.


number = *zPtr;

c) zPtr[2] is not a pointer and should not be dereferenced.


number = zPtr[2];
‫حرشلا‬
d) referring to an array element outside the array bounds.
for ( int i = 0; i < 5; i++ )
cout << zPtr[i] << endl;

e) Trying to modify an array name with pointer arithmetic

f) Function strncpy does not write a terminating null character to array s,


because its third argument is equal to the length of the string "hello ".
strncpy ( s, "hello ", 6 );

g) Character array s is not large enough to store the terminating null


character.
Declare an array with more elements.

h) Function strcmp will return 0 if the strings are equal.


if ( strcmp ( string1, string2 ) == 0 )
cout << "The strings are equal " << endl;

‫كيهع نأ مغر نأ كدالوأ نولعفيس ابالغ سكع‬


‫طبضماب نكم‬، ‫او نىقت مهم‬
.‫رمتست يف مهبح ردقالب هتاذ‬

)11(
cstring Functions

)18(
C++ Lectures- Control & systems Department Lecturer : Karam Samir

What prints when each of the following statements is


performed? Assume the following declarations:

char s1[50]
= "jack";
char s2[50]
= "jill";
char s3[50];

a) cout << strcpy ( s3, s2 ) << endl;


b) cout << strcat ( strcat ( strcat ( s3, s1 ), " and " ), s2 ) <<
endl;
c) cout << strlen ( s1 ) + strlen ( s2 ) << endl;
d) cout << strlen ( s3 ) << endl;

a) jill
b) jack and jill
c) 8
d) 13

Q1 Write a program to find the length of string

#include<iostream>
using namespace std;

int main( )
{
char str[80];

cout<<"Enter string: ";


cin.getline(str, 80);

int i; //Hold length of string

for(i = 0; str[i] != '\0'; i++);


54
C++ Lectures- Control & systems Department Lecturer : Karam Samir

cout << "Length of string is: " << i;

return 0;
}

Q2 Write a program to display string from backward.

#include<iostream>

using namespace std;

int main( )

char str[80];

cout<<"Enter string: ";

cin.getline(str, 80);

int l; //Hold length of string

//Find the length of the string

for(l = 0; str[l] != '\0'; l++);

//Display the string backwards

for(int i = l - 1; i >= 0; i--)

cout << str[i];


55
C++ Lectures- Control & systems Department Lecturer : Karam Samir

return 0;

Q3 Write a program to count number of words in string.

#include<iostream>

using namespace std;

int main( )

char str[80];

cout << "Enter a string: ";

cin.getline(str,80);

int words = 0; // Holds number of words

for(int i = 0; str[i] != '\0'; i++)

if (str[i] == ' ') //Checking for spaces

words++;

56
C++ Lectures- Control & systems Department Lecturer : Karam Samir

cout << "The number of words = " << words+1 <<


endl;

return 0;

Q4 Write a program to concatenate one string contents to


another.

#include<iostream>

using namespace std;

int main( )

char str1[80], str2[80];

cout<<"Enter first string: ";

cin.getline(str1, 80);

cout<<"Enter second string: ";

cin.getline(str2, 80);

57
C++ Lectures- Control & systems Department Lecturer : Karam Samir

int l = 0; //Hold length of first string

//Find length of first string.

for(l = 0; str1[l] != '\0'; l++);

//Adding second string content in first

for(int i = 0; str2[i] != '\0'; i++)

str1[l++] = str2[i];

str1[l] = '\0';

cout << "\nThe first string after adding second


string content:\n\n" << str1;

return 0;

Q5 Write a program to compare two strings they are exact equal


or not.
#include<iostream>

using namespace std;

58
C++ Lectures- Control & systems Department Lecturer : Karam Samir

int main( )

char str1[80], str2[80];

cout<<"Enter first string: ";

gets(str1);

cout<<"Enter second string: ";

gets(str2);

int i;

for (i = 0; str1[i] == str2[i] && str1[i]!= '\0'


&& str2[i] != '\0'; i++);

if(str1[i] - str2[i] == 0)

cout << "Strings are equal";

else

cout << "Strings are not equal";

return 0;

59
C++ Lectures- Control & systems Department Lecturer : Karam Samir

Q6 Write a program to check a string is palindrome or not.


#include<iostream>

using namespace std;

int main( )

char str[80];

cout<<"Enter string: ";

cin.getline(str, 80);

int l; //Hold length of string

//finding length of string

for(l = 0; str[l] != '\0'; l++);

//Comparing first element with last element till


middle of string

61
C++ Lectures- Control & systems Department Lecturer : Karam Samir

int i;

for(i = 0; (i < l/2) && (str[i] == str[l - i -


1]); i++);

if(i == l/2)

cout << "Palindrome";

else

cout << "Not a palindrome";

return 0;

Q7 Write a program to find a substring within a string. If found


display its starting position

#include<iostream>

using namespace std;

int main( )

char str1[80], str2[80];

cout<<"Enter first string: ";

cin.getline(str1, 80);
61
C++ Lectures- Control & systems Department Lecturer : Karam Samir

cout<<"Enter second string: ";

cin.getline(str2, 80);

int l = 0; //Hold length of second string

//finding length of second string

for(l = 0; str2[l] != '\0'; l++);

int i, j;

for(i = 0, j = 0; str1[i] != '\0' && str2[j] !=


'\0'; i++)

if(str1[i] == str2[j])

j++;

else

j = 0;

62
C++ Lectures- Control & systems Department Lecturer : Karam Samir

if(j == l)

cout<<"Substring found at position "<< i - j +


1;

else

cout<<"Substring not found";

return 0;

Q8 Write a program to reverse a string.

#include<iostream>

using namespace std;

int main( )

char str[80];

cout<<"Enter string: ";

cin.getline(str, 80);

int l; //Hold length of string

63
C++ Lectures- Control & systems Department Lecturer : Karam Samir

for(l = 0; str[l] != '\0'; l++); //finding


length of string

int temp;

for(int i = 0, j = l - 1; i < l/2; i++, j--)

temp = str[i];

str[i] = str[j];

str[j] = temp;

cout << "Reverse string: " << str << endl;

return 0;

Q9 Write a program to convert a string in lowercase.

#include<iostream>

using namespace std;

int main( )

64
C++ Lectures- Control & systems Department Lecturer : Karam Samir

char str[80];

cout<<"Enter string: ";

cin.getline(str, 80);

for(int i=0;str[i]!='\0';i++)

str[i] = (str[i] >= 'A' && str[i] <= 'Z') ?


(str[i] + 32) : str[i];

cout<<"Lowercase string: " << str << endl;

return 0;

Q10 Write a program to convert a string in uppercase.


#include<iostream>

using namespace std;

int main( )

char str[80];

65
C++ Lectures- Control & systems Department Lecturer : Karam Samir

cout << "Enter a string: ";

cin.getline(str,80);

for(int i = 0; str[i] != '\0'; i++)

str[i] = (str[i] >= 'a' && str[i] <= 'z') ?


(str[i] - 32) : str[i];

cout << "\nConverted string: " << str;

return 0;

Q11 Write the output of the following program. Assume that all
necessary header files are included.
void Encrypt(char T[])

for (int i = 0; T[i] != '\0'; i += 2)

if (T[i] == 'A' || T[i] == 'E')

T[i] = '#';

else if (islower(T[i]))

T[i] = toupper(T[i]);

else
66
C++ Lectures- Control & systems Department Lecturer : Karam Samir

T[i] = '@';

int main()

char text[]="SaVE EArtH";

Encrypt(text);

cout << text << endl;

return 0;

Ans: @a@E@E#rTH

Q12 Write the output of the following program


int main()

char name[] = "CoMPutER";

for (int x = 0; x < strlen(name); x++)

if (islower(name [x]))

name [x] = toupper(name[x]);

else

if (isupper(name[x]))

if (x % 2 == 0)

name[x] = tolower(name[x]);
67
C++ Lectures- Control & systems Department Lecturer : Karam Samir

else

name[x] = name[x-1];

cout << name;

return 0;} Ans:


cOmmUTee

68
C++ Lectures- Control & systems Department Lecturer : Karam Samir

Q write a C++ program to split the word of string then print each word with its length.
#include < iostream.h>
#include< string.h>
void main ()
{
char str[100]="control and system ";
int i,j,k=0,m;
for ( i=0; str[i]!='\0';i++)
{m=i;
k=0;
for ( j=i; str[j]!=' ';j++)
k++;
//cout << str[j];
//}

for ( m; m<j;m++)
cout << str[m];
cout << endl;
cout << "lenght=" << k<<endl;

i=j;
}
}

Write a C++ program to find the length of each word in string then print the lagrgest word with its
length.
#include < iostream.h>
#include< string.h>
struct ki{
int len;
int loc;

69
C++ Lectures- Control & systems Department Lecturer : Karam Samir

}ki[100];

void main ()
{
char str[100]="karamsasa samir kahlid essa";
int y= strlen(str);
str[y]=' ';
int i,j,m,w,z,k;

for ( i=0; str[i]!='\0';i++)


{
if( str [i] == ' ')
w++;
}

for (i=0;i<=w;i++)
ki[i].len=0;

for ( z=0,i=0; str[i]!='\0';i++, z++)


{m=i;
k=0;
for ( j=i; str[j]!=' ';j++)
k++;
ki[z].len=k;
ki[z].loc=i;

//cout << str[j];


//}

// for ( m; m<j;m++)
// cout << str[m];
71
C++ Lectures- Control & systems Department Lecturer : Karam Samir

// cout << endl;


// cout << "lenght=" << k<<endl;

i=j;
w=0;
k=0;
}
int max = ki[0].len;
int p=0;

for (i=0;i<100;i++)
if (max < ki[i].len)
{max = ki[i].len;
p=i;}

//cout << max <<"p="<<p <<endl;


//int l=ki[p].len + ki[p].loc;
//cout<<"l="<<l;

for (j=ki[p].loc; j<ki[p].len + ki[p].loc;j++)


cout << str[j];
cout << " \n max length = " << ki[p].len;

// cout <<ki[0].len<< ki[0].loc <<endl;


//cout <<ki[1].len<< ki[1].loc <<endl;
//cout <<ki[2].len<< ki[2].loc <<endl;

Q ) write a C++ program to Replace the max word with min word.

71
C++ Lectures- Control & systems Department Lecturer : Karam Samir

C program to Replace a word in a text by another


given word
.

72
C++ Lectures- Control & systems Department Lecturer : Karam Samir

A
Pointers Lec. (12)
point
er is a variable that is used to store a memory address. The address is the location of the variable in
the memory. Pointers help in allocating memory dynamically. Pointers improve execution time and
saves space. Pointer points to a particular data type. The general form of declaring pointer is:-
type *variable_name;
type is the base type of the pointer and variable_name is the name of the variable of the pointer. For
example,
int *x;
x is the variable name and it is the pointer of type integer.
Pointer Operators
There are two important pointer operators such as ‘*’ and ‘&’. The ‘&’ is a unary operator. The unary
operator returns the address of the memory where a variable is located. For example,
int x*;
int c;
x=&c;
variable x is the pointer of the type integer and it points to location of the variable c. When the
statement
x=&c;
is executed, ‘&’ operator returns the memory address of the variable c and as a result x will point to
the memory location of variable c.
Example:
Consider the following code fragment:

andy = 25;
fred = andy;
ted = &andy;

The values contained in each variable after the execution of this, are shown in the following diagram:

73
C++ Lectures- Control & systems Department Lecturer : Karam Samir

First, we have assigned the value 25 to andy (a variable whose address in memory we have
assumed to be 1776).

The second statement copied to fred the content of variable andy (which is 25). This is a
standard assignment operation, as we have done so many times before.

Finally, the third statement copies to ted not the value contained in andy but a reference to it
(i.e., its address, which we have assumed to be 1776). The reason is that in this third
assignment operation we have preceded the identifier andy with the reference operator (&), so
we were no longer referring to the value of andy but to its reference (its address in memory).

The variable that stores the reference to another variable (like ted in the previous example) is
what we call a pointer. Pointers are a very powerful feature of the C++ language that has many
uses in advanced programming. Farther ahead, we will see how this type of variable is used
and declared.

#include <iostream.h>
int main ()
{
int firstvalue = 5, secondvalue = 15;
int * p1, * p2;

p1 = &firstvalue; // p1 = address of firstvalue


p2 = &secondvalue; // p2 = address of secondvalue
*p1 = 10; // value pointed by p1 = 10
*p2 = *p1; // value pointed by p2 = value
// pointed by p1
p1 = p2; // p1 = p2 (value of pointer is copied)
*p1 = 20; // value pointed by p1 = 20
cout << "firstvalue is " << firstvalue << endl;
cout << "secondvalue is " << secondvalue << endl;
return 0;}
The result: firstvalue is 10
secondvalue is 20

74
C++ Lectures- Control & systems Department Lecturer : Karam Samir

Pointer Arithmetic:
There are only two arithmetic operations that can be performed on pointers such as addition and
subtraction. The integer value can be added or subtracted from the pointer. The result of addition and
subtraction is an address. The difference of the two memory addresses results an integer and not the
memory address. When a pointer is incremented it points to the memory location of the next element
of its base type and when it is decremented it points to the memory location of the previous element
of the same base type. For example
int *x;
int *p;
p=x++;
here x and p are pointers of integer type. Pointer x is incremented by 1. Now variable p points to the
memory location next to the memory location of the pointer x. Suppose memory address of x is 2000
and as a result p will contain memory address 2002 because integer type takes two bytes so the
memory address is incremented by 2. Incrementing the pointer results in incrementing the memory
address by the number of bytes occupied by the base type. For example,
double *x;
double *p;
p=x++;
variables x and p are pointers of double type. Pointer x is incremented by 1. Now if the memory
address of x was 2000 and after incrementing p will contain memory address 2008 as double takes 8
bytes. Decrementing the pointer results in decrementing the memory address by the number of bytes
occupied by the base type. You cannot add two pointers. No multiplication and division can be
performed on pointers. Here is a program which illustrates the working of pointer arithmetic.

Example:

Suppose that we define three pointers in this compiler:

char *mychar;
short *myshort;
long *mylong;

and that we know that they point to memory locations 1000, 2000 and 3000 respectively.

75
C++ Lectures- Control & systems Department Lecturer : Karam Samir

So if we write:

mychar++;
myshort++;
mylong++;

mychar, as you may expect, would contain the value 1001. But not so obviously, myshort would

contain the value 2002, and mylong would contain 3004, even though they have each been
increased only once. The reason is that when adding one to a pointer we are making it to point to the
following element of the same type with which it has been defined, and therefore the size in bytes of
the type pointed is added to the pointer.

This is applicable both when adding and subtracting any number to a pointer. It would happen exactly
the same if we write:

mychar = mychar + 1;
myshort = myshort + 1;
mylong = mylong + 1;

Both the increase (++) and decrease (--) operators have greater operator precedence than the
dereference operator (*), but both have a special behavior when used as suffix (the expression is
evaluated with the value it had before being increased). Therefore, the following expression may lead
to confusion:

*p++

Because ++ has greater precedence than *, this expression is equivalent to *(p++). Therefore, what it
does is to increase the value of p (so it now points to the next element), but because ++ is used as
postfix the whole expression is evaluated as the value pointed by the original reference (the address
the pointer pointed to before being increased).
76
C++ Lectures- Control & systems Department Lecturer : Karam Samir

Notice the difference with:


(*p)++
Here, the expression would have been evaluated as the value pointed by p increased by one. The
value of p (the pointer itself) would not be modified (what is being modified is what it is being pointed
to by this pointer).
If we write:

*p++ = *q++;

Because ++ has a higher precedence than *, both p and q are increased, but because both increase
operators (++) are used as postfix and not prefix, the value assigned to *p is *q before both p and q
are increased. And then both are increased. It would be roughly equivalent to:

*p = *q;
++p;
++q;

Like always, I recommend you to use parentheses () in order to avoid unexpected results and to give
more legibility to the code.
Pointers and Arrays
The pointers and arrays have a very close relationship. The pointer can be set to the address of the
first element of the array. For example,
int age[];
int *p;
p=&age; // or p=age or p=&age[0]

where in array
age≡ &age ≡ &age[0]
p will point to the address of the first element of the array. For example
(p+4)
will point to the fifth element of the array. Pointers are helpful where size of the array is unknown.
Declaring the array with a size of large value wastes lot of space. Pointers improve the execution time.
Here is a program which illustrates the working of arrays and pointers.
Example: The result:
Enter the age of a student
#include<iostream.h>
16
int main() Enter the age of a student
{ 20
int age[5]; Enter the age of a student
int *p; 21
int sum=0,i; Enter the age of a student
77 19
Enter the age of a student
18
The sum of the ages94
The age of the last student is : 18
C++ Lectures- Control & systems Department Lecturer : Karam Samir

char yes='y';
p=age;
for(i=0;i<5;i++)
{

cout << "Enter the age of a student" << endl;


cin >> *p;
sum=sum+*p;
p++;
}
p=age;
cout << "The sum of the ages" << sum << endl;\
cout << "The age of the last student is : " << *(p + 4) << endl;
return(0);
}

Example:

#include<iostream.h>
int main()
{
int a[10]={10,20,30,40,50,60,70,80,90,100};
int *pa;
pa=a;
for(int i=0;i<10;i++)
cout<<a[i]<<" ";
cout<<endl;
for(i=0;i<10;i++)
cout<<pa[i]<<" ";
cout<<endl;
for(i=0;i<10;i++)
cout<<*(a+i)<<" ";
cout<<endl;
for( i=0;i<10;i++)
cout<<*(pa+i)<<" ";
cout<<endl;
for(i=0;i<10;i++)
cout<<*pa++<<" "; // *a++ it is wrong the name of array cannot be
// incremented or decremented
pa=a;
cout<<endl;
cout<<++*pa<<endl;
cout<< *++pa<<endl;
cout<< *pa++<<endl;
return 0; }

the result:
10 20 30 40 50 60 70 80 90 100

78
C++ Lectures- Control & systems Department Lecturer : Karam Samir

10 20 30 40 50 60 70 80 90 100
10 20 30 40 50 60 70 80 90 100
10 20 30 40 50 60 70 80 90 100
10 20 30 40 50 60 70 80 90 100
11
20
20
Example:
#include<iostream.h>
int main()
{
char s[20]="hello world";
char *sp;
sp=s;
cout<<++*sp<<endl;
cout<<*++sp<<endl;
cout<<*sp++<<endl;
cout<<sp<<endl;
cout<<s;
return 0;
}
The result:
i
e
e
llo world
iello world

Pointers to pointers
C++ allows the use of pointers that point to pointers, that these, in its turn, point to data (or even to
other pointers). In order to do that, we only need to add an asterisk (*) for each level of reference in
their declarations:

char a;
char * b;
char ** c;
a = 'z';
b = &a;
c = &b;

This, supposing the randomly chosen memory locations for each variable of 7230, 8092 and 10502,
could be represented as:

79
C++ Lectures- Control & systems Department Lecturer : Karam Samir

The value of each variable is written inside each cell; under the cells are their respective addresses in
memory.
The new thing in this example is variable c, which can be used in three different levels of indirection,
each one of them would correspond to a different value:
c has type char** and a value of 8092

*c has type char* and a value of 7230

**c has type char and a value of 'z'

Pointer with function

We can passing the address of variables to function(passing by address) so that any change of
the content of these variables in function will pass to main program and vice versa the
following examples:

#include<iostream.h>
void swap(int*x,int*y);
int main()
{
int x=10;
int y=20;
swap(&x,&y);
cout<<”x=”<<x<<" "<<”y=”<<y;
return 0;}
void swap(int *x,int * y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}

The result : x=20 y=10

Example:
#include<iostream.h>
int strlength(char *s);

81
C++ Lectures- Control & systems Department Lecturer : Karam Samir

void main(){
char *s=”hello world”;
int len=strlength(s);
cout<<len<<endl;
}
int strlength(char *s)
{ int i=0;
char *sp=s;
while(*sp!=‟\0‟) {
*sp++;
i++;
}
return i;
}
The result is: 11

void pointers

The void type of pointer is a special type of pointer. In C++, void represents the absence of type, so
void pointers are pointers that point to a value that has no type (and thus also an undetermined
length and undetermined dereference properties).

This allows void pointers to point to any data type, from an integer value or a float to a string
of characters. But in exchange they have a great limitation: the data pointed by them cannot be
directly dereferenced (which is logical, since we have no type to dereference to), and for that
reason we will always have to cast the address in the void pointer to some other pointer type
that points to a concrete data type before dereferencing it.

One of its uses may be to pass generic parameters to a function:

The result: y, 1603


#include <iostream.h>
void increase (void* data, int psize)
{
if ( psize == sizeof(char) )
{ char* pchar; pchar=(char*)data;

81
C++ Lectures- Control & systems Department Lecturer : Karam Samir

++(*pchar); }
else if (psize == sizeof(int) )
{ int* pint; pint=(int*)data; ++(*pint); }
}

int main ()
{
char a = 'x';
int b = 1602;
increase (&a,sizeof(a));
increase (&b,sizeof(b));
cout << a << ", " << b << endl;
return 0;
}

sizeof is an operator integrated in the C++ language that returns the size in bytes of its
parameter. For non-dynamic data types this value is a constant. Therefore, for example,
sizeof(char) is 1, because char type is one byte long.

Null pointer

A null pointer is a regular pointer of any pointer type which has a special value that indicates that it is
not pointing to any valid reference or memory address. This value is the result of type-casting the
integer value zero to any pointer type.

int * p;
p = 0; // p has a null pointer value

Do not confuse null pointers with void pointers. A null pointer is a value that any pointer may
take to represent that it is pointing to "nowhere", while a void pointer is a special type of
pointer that can point to somewhere without a specific type. One refers to the value stored in
the pointer itself and the other to the type of data it points to.

82
C++ Lectures- Control & systems Department Lecturer : Karam Samir

Structures Lec. (13)


Structure

A structure is a collection of variable which can be same or different types. You can
refer to a structure as a single variable and to its parts as members of that variable by
using the dot (.) operator. The power of structures lies in the fact that once defined, the
structure name becomes a user-defined data type and may be used the same way as
other built-in data types, such as int, double, char.
struct Student
{
int rollno, age;
char name[80];
float marks;
};

int main()
{

// declare two variables of the new type Student


s1, s3;

//accessing of data members


cin >> s1.rollno >> s1.age >> s1.name >> s1.marks;
cout << s1.rollno << s1.age << s1.name << s1.marks;

//initialization of structure variable


Student s2 = {100, 17, "Aniket", 92};
cout << s2.rollno << s2.age << s2.name << s2.marks;

//structure variable in assignment statement


s3 = s2;
cout << s3.rollno << s3.age << s3.name << s3.marks;

return 0;
}

Defining a structure

When dealing with the students in a school, many variables of different types are
needed. It may be necessary to keep track of name, age, Rollno, and marks point
for example.

83
C++ Lectures- Control & systems Department Lecturer : Karam Samir

struct Student
{
int rollno, age; char
name[80]; float
marks;
};

Student is called the structure tag, and is your brand new data type, like int, double or char.

rollno, name, age, and marks are structure members.

Declaring Variables of Type struct

The most efficient method of dealing with structure variables is to define the structure
globally. This tells "the whole world", namely main and any functions in the program,
that a new data type exists. To declare a structure globally, place it BEFORE void
main(). The structure variables can then be defined locally in main, for example…
struct Student
{
int rollno, age; char
name[80]; float
marks;
};

int main()
{
// declare two variables of the new type
Student s1, s3;
………
………
return 0;
}

Alternate method of declaring variables of type struct:


struct Student
{
int rollno, age; char
name[80]; float
marks;
} s1, s3;

84
C++ Lectures- Control & systems Department Lecturer : Karam Samir

Accessing of data members

The accessing of data members is done by using the following format:


structure variable.member name
for example

cin >> s1.rollno >> s1.age >> s1.name >> s1.marks;

Initialization of structure variable

Initialization is done at the time of declaration of a variable. For example

Student s2 = {100, 17, "Aniket", 92};

Structure variable in assignment statement

s3 = s2;

The statement assigns the value of each member of s2 to the corresponding member of
s3. Note that one structure variable can be assigned to another only when they are of
the same structure type, otherwise complier will give an error.

For another example, you can have a structure of type employee which stores name,
age, qualification, and telephone no and other information about the employee under
one data type. A structure can be declared as:-

#include<iostream.h>
struct Employee
{
char name[50];
int age;
char quali[70];
int teleno;

85
C++ Lectures- Control & systems Department Lecturer : Karam Samir

char info[80];
}emp1;
int main ()
{
Employee emp2;
cout << "Enter the name of the employee" << endl;
cin >> emp1.name;
cout << endl << "Enter the age of the employee" << endl;
cin >> emp1.age;
cout << endl << "Enter the qualification of the employee" << endl;
cin >> emp1.quali;
cout << endl << "Enter the telephone no of the employee" << endl;
cin >> emp1.teleno;
cout << endl << "Enter other information about the employee" << endl;
cin >> emp1.info;
emp2=emp1;
cout << endl << "The name of the employee : " << emp2.name << endl;
cout << "The age of the employee : " << emp2.age << endl;
return(0);
}

The result of the program is:-


Enter the name of the employee
ahmed
Enter the age of the employee
21
Enter the qualification of the employee
engineer
Enter the telephone no of the employee
123456
Enter other information about the employee
good worker
The name of the employee86: ahmed
The age of the employee : 21
C++ Lectures- Control & systems Department Lecturer : Karam Samir

Arrays of Structures
An array of structures can be declared. For example, if we want to store information about 50
employees of the company then we can declare an array of structure of type Employee. For
example,

Employee emp[100];

declares array emp of type Employee. Each variable can be accessed using an index. The index
begins with zero like other arrays. For example,
cout << "Name of the first employee" << emp[0].name << endl;

will display the name of the first employee. Similarly emp[0].age contains the age of the first
employee.

Example:- Define addresses 5 people where the title includes the following fields (Name, city,
the street ).

#include <iostream.h>
int main ()
{
struct address
{
char name[20];
char city[15];
char street[20];
};
address information[5];
cout<<"Enter Information\n";
int i;
for(i=0;i<5;i++)

87
C++ Lectures- Control & systems Department Lecturer : Karam Samir

{
cin>>information[i].name;
cin>>information[i].city;
cin>>information[i].street;
}
cout<<"**** Print Information ****\n";
cout<<"===========================\n";
cout<<"No\tName\tCity\t Street\n";
for(i=0;i<5;i++)
{
cout<<i+1<<"\t";
cout<<information[i].name<<"\t";
cout<<information[i].city<<"\t";
cout<<information[i]. street<<"\t";
cout<<"\n";
}
return 0;
}

Nested structure (Structure within structure)

It is possible to use a structure to define another structure. This is called nesting of


structure. Consider the following program

#include<iostream.h>
int main ()
{
struct name
{
char first[20],middle[20],family[20];
};
88
C++ Lectures- Control & systems Department Lecturer : Karam Samir

struct full_name
{
struct name n;
long university_no;
};
full_name f={{"Mohmmed","Abdallah","Ali"},1809992};
cout<<"*** personal information ***\n";
cout<<"-----------------------------------\n";
cout<<"full name:"<<f.n.first<<" "<<f.n.middle;
cout<<" "<<f.n.family<<"\n";
cout<<"university number:"<<f.university_no<<"\n";
return 0;

another example of nested structure

struct Day
{
int month, date, year;
};

struct Student
{
int rollno, age;
char name[80];
Day date_of_birth;
float marks;
};

Accessing Member variables of Student

To access members of date_of_birth we can write the statements as below :

Student s; // Structure variable of Student

s.date_of_birth.month = 11;
s.date_of_birth.date = 5;
s.date_of_birth.year = 1999;
89
C++ Lectures- Control & systems Department Lecturer : Karam Samir

Passing Structures to Functions


The structures and their members can be passed to functions. The structure and member can act
as an argument for the function. Here is a program which shows how structures are passed to
functions.
#include<iostream.h>
struct Employee
{
char name[50];
int age;
char quali[70];
int teleno;
char info[80];
}emp1;
void display(Employee emp3,char name3[50], int age2);
int main()
{
cout << "Enter the name of the employee" << endl;
cin >> emp1.name;
cout << endl << "Enter the age of the employee" << endl;
cin >> emp1.age;
cout << endl << "Enter the qualification of the employee" << endl;
cin >> emp1.quali;
cout << endl << "Enter the telephone no of the employee" << endl;
cin >> emp1.teleno;
cout << endl << "Enter other information about the employee" << endl;
cin >> emp1.info;
display(emp1,emp1.name,emp1.age);
return(0);}
void display(Employee emp3, char name3[50],int age3)
{ cout << endl << "The name of the employee : " << name3 << endl;

91
C++ Lectures- Control & systems Department Lecturer : Karam Samir

cout << "The age of the employee : " << age3 << endl;
cout << "The qualification of the employee : " << emp3.quali << endl;
cout << "The telephone no of the employee : " << emp3.teleno << endl;}
The result of the program is:-
Enter the name of the employee
ahmed
Enter the age of the employee
21
Enter the qualification of the employee
engineer
Enter the telephone no of the employee
12345
Enter other information about the employee
Good worker
The name of the employee : ahmed
The age of the employee : 21
The qualification of the employee : engineer
The telephone no of the employee : 12345
The statement
void display(Employee emp3,char name3[50], int age2);
declares a function whose parameter are emp3 of type Employee, name3 of char type and age2
of type integer. The statement
display(emp1,emp1.name,emp1.age);

make a call to the function display. The arguments are emp1 of type Employee, emp1.name
and emp1.age which are members of emp1. The arguments are mapped to the parameters of the
function. The information of emp1 is mapped to emp3. The members emp1.name and
emp1.age are mapped to name3 and age3 respectively. The statements
cout << endl << "The name of the employee : " << name3 << endl;
cout << "The age of the employee : " << age3 << endl;
cout << "The qualification of the employee : " << emp3.quali << endl;

91
C++ Lectures- Control & systems Department Lecturer : Karam Samir

cout << "The telephone no of the employee : " << emp3.teleno << endl;

display the information of emp1.

Pointers and Structures

There can be pointers to structures. Pointers are used for structures for passing structures by
reference and for creating linked lists. The structure pointers can be declared as follows:-
Employee *emp1;
Now emp1 is a pointer to the type Employee. The members of the structure using a pointer are
accessed using an arrow operator. The '->' is called an arrow operator which consists of
minus sign followed by a greater than operator. The members are accessed using arrow
operator in the same way as they are accessed using a dot operator. Here is a program which
illustrates the working of pointers and structures.
#include<iostream.h>
struct Employee
{
char name[50];
int age;
char quali[70];
int teleno;
char info[80];
}emp1;
void display(Employee *emp3);
int main()
{
cout << "Enter the name of the employee" << endl;
cin >> emp1.name;
cout << endl << "Enter the age of the employee" << endl;
cin >> emp1.age;
cout << endl << "Enter the qualification of the employee" << endl;

92
C++ Lectures- Control & systems Department Lecturer : Karam Samir

cin >> emp1.quali;


cout << endl << "Enter the telephone no of the employee" << endl;
cin >> emp1.teleno;
cout << endl << "Enter other information about the employee" << endl;
cin >> emp1.info;
display(&emp1);
cout << endl << "The modified age of the Employee : " << emp1.age << endl;
cout << " The modified telephone no of the Employee : " << emp1.teleno << endl;
return(0);
}
void display(Employee *emp3)
{
emp3->age=emp3->age+10;
emp3->teleno=3299574;
}
The result of the program is:- Enter the name of the employee
ahmed
Enter the age of the employee
21
Enter the qualification of the employee
engineer
Enter the telephone no of the employee
12345
Enter other information about the employee
good worker
The modified age of the Employee : 31
The modified telephone no of the Employee : 3299574
The statement
void display(Employee *emp3);

declares a function whose parameter is a pointer of type Employee. The statement

93
C++ Lectures- Control & systems Department Lecturer : Karam Samir

display(&emp1);
passes the address of emp1 to the function. In the function the statements
emp3->age=emp3->age+10;
emp3->teleno=3299574;

modify the values of the member age and telephone of emp3. The member age and teleno are
accessed using an arrow operator. The age is incremented by 10 and telephone no is changed.
The statements

cout << endl << "The modified age of the Employee : " << emp1.age << endl;
cout << " The modified telephone no of the Employee : " << emp1.teleno <<endl;

print the modified age and telephone of the employee. The function alters the arguments passed
as this pass by reference.

94
C++ Lectures- Control & systems Department Lecturer : Karam Samir

Q1: Create a structure complex number having real and imaginary part as
properties. Write functions to add and subtract the two complex numbers.

#include <iostream.h>
struct complex
{
int real, img;
};
struct complex a, b, c;

void readcom(){
cout <<"Enter a and b where a + ib is the first complex number.\n";
cout<<"a.real = ";
cin >>a.real;
cout<< " a.img =";
cin>>a.img;
cout<<"b.real = ";
cin>>b.real;
cout<< " b.img =";
cin>>b.img;
}
void addcom(){
c.real = a.real + b.real;
c.img = a.img + b.img;
if (c.img>=0)
cout<<"Sum of two complex numbers"<<c.real<<"+"<<c.img<<"i";
else
cout<<"Sum of two complex numbers"<<c.real<<c.img<<"i";

}
void subcom(){

95
C++ Lectures- Control & systems Department Lecturer : Karam Samir

c.real = a.real - b.real;


c.img = a.img - b.img;
if (c.img>=0)
cout<<"\nDifference of two complex numbers = "<<c.real<<"+"<<c.img<<"i";
else
cout<<"\nDifference of two complex numbers = "<<c.real<<c.img<<"i";

}
void main()
{
readcom();
addcom();
subcom();
}

2. Define a structure called student having the properties of student_id, student


name and branch of the student with a substructure of marks of 3 subjects. Write
a function to
A. Enter 100 students with their information's.
B. Display all student details
C. Calculate the average of three subject's degree for each student.
D. Display average of each student.
E. Display the id and name for each student when his branch is control.
F. Display the students information for each students pass in examinations
G. increases the degree of each subject with 10 degrees.

#include <iostream.h>
#include <string.h>

struct Student {
char name[20];
char branch[20];
char id[20];
96
C++ Lectures- Control & systems Department Lecturer : Karam Samir

int m1,m2,m3;
float avg;
};

void read(Student *s,int size)


{cout<< "std id " << "std name " <<" std branch " << "std degree1 "<<"std degree2 "<<"std
degree2 "<<endl;
for (int i=0;i<size;i++)
{ cin>> s->id>>s->name>>s->branch>>s->m1>>s->m2>>s->m3;
s++;
if (i<size-1)
cout << " enter the information of the next student ";
}
}
//---------------------------------------------------------------------------------------------------------------//
void display(Student *s,int size)
{
for (int i=0;i<size;i++)
{cout <<"ID="<<s->id<<"\n name: "<<s->name <<"\n branch: " << s->branch <<"\n
degree1: "<<s->m1 <<"\n degree2: "<<s->m2 <<"\n degree3: "<<s->m3 <<"\n avarage: "<< s-
>avg<<endl;
s++;
cout<<endl;}
}
//---------------------------------------------------------------------------------------------------------------//
void calc_average(Student *s,int size)
{int sum=0;
for (int i=0;i<size;i++)
{ sum= s->m1+ s->m2+ s->m3;
s->avg=(float)sum/3;
s++;}

97
C++ Lectures- Control & systems Department Lecturer : Karam Samir

}
//---------------------------------------------------------------------------------------------------------------//
void disaverage(Student *s,int size)
{
for (int i=0;i<size;i++)
{
cout <<"name: "<< s->name<< "\n avarge = " << s->avg<<endl;
s++;}
}
//---------------------------------------------------------------------------------------------------------------//
void search_branch (Student *s,int size,char a[])
{cout << "branch: "<< a<<endl;
for (int i=0;i<size;i++)
{

if (strcmp(s->branch,a)==0)
{
cout<<s->id <<" " <<s->name <<endl;}
s++;
}
cout <<" ___________________________________"<<endl;
}
//---------------------------------------------------------------------------------------------------------------//
void incdegree( Student *s,int size)
{for (int i=0;i<size;i++)
{
s->m1+=10;
s->m2+=10;
s->m3+=10;
s++;
}

98
C++ Lectures- Control & systems Department Lecturer : Karam Samir

}
//---------------------------------------------------------------------------------------------------------------//
void success_std(Student *s,int size)
{
for (int i=0;i<size;i++)
{if ((s->m1 >=50) && (s->m2 >=50) &&(s->m3 >=50))
cout<<s->id <<" " <<s->name << " "<<s->avg <<endl;
s++;}
cout <<" ___________________________________"<<endl;
}
void main( )
{
Student std1[3]={{"noor","computer","1",70,50,60,0.0},
{"ali","control","2",20,20,20,0.0},{"ahmed","control","3",10,30,30,0.0}};

cout << std1[0].id<< " " << std1[0].name<< " " << std1[0].branch<<std1[0].m1
<<std1[0].m2<<std1[0].m3 <<endl;

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


{
cout << std1[i].id <<" " << std1[i].name << " " << std1[i].branch << " " <<std1[i].m1<< " "<<
std1[i].m2 <<" "<<std1[i].m3<<" " <<std1[i].avg<<endl;
}
//---------------------------------------------------------------------------------------------------------------//
Student std[100];
read(std,100);
display(std,100);
//---------------------------------------------------------------------------------------------------------------//
incdegree(std1,3);
display(std1,3);
//---------------------------------------------------------------------------------------------------------------//

99
C++ Lectures- Control & systems Department Lecturer : Karam Samir

calc_average (std1,3);
disaverage(std1,3);
//---------------------------------------------------------------------------------------------------------------//
search_branch (std1,3,"computer");
search_branch (std1,3,"control");
//---------------------------------------------------------------------------------------------------------------//
success_std(std1,3);

Question 1 Give the output of the following program


#include<iostream.h>
struct Pixel
{
int C,R;
};
void Display(Pixel P)
{
cout<<"Col”<<P.C<<"Row"<<P.R<<endl;
}
void main()
{
Pixel X={40,50},Y,Z;
Z=X;
X.C+=10;
Y=Z;
Y.C+=10;
Y.R+=20;
Z.C-=15;
Display(X);
Display(Y);
111
C++ Lectures- Control & systems Department Lecturer : Karam Samir

Display(Z);
}

Question 2 Find the output of the following program:


#include <iostream.h>
struct PLAY
{
int Score, Bonus;
};
void Calculate(PLAY &P, int N=10)
{
P.Score++;
P.Bonus+=N;
}
void main()
{
PLAY PL={10,15};
Calculate(PL,5);
cout<<PL.Score<<”:”<<PL.Bonus<<endl;
Calculate(PL);
cout<<PL.Score<<”:”<<PL.Bonus<<endl;
Calculate(PL,15);
cout<<PL.Score<<”:”<<PL.Bonus<<endl;
}

111
C++ Lectures- Control & systems Department Lecturer : Karam Samir

Question 3 #include<iostream.h>
struct MyBox
{
int Length, Breadth, Height;
};
void Dimension (MyBox M)
{
cout<<M.Length<<"x"<<M.Breadth<<"x";
cout<<M.Height<<endl;
}
void main ()
{
MyBox B1={10,15,5}, B2, B3;
++B1.Height;
Dimension(B1);
B3 = B1;
++B3.Length;
B3.Breadth++;
Dimension(B3);
B2 = B3;
B2.Height+=5;
B2.Length--;
Dimension(B2);
}

Question 4 Rewrite the following program after removing the syntactical errors (if any).
Underline each correction.

112
C++ Lectures- Control & systems Department Lecturer : Karam Samir

#include <iostream.h>
struct Pixels
{
int Color, Style;
}
void ShowPoint(Pixels P)
{
cout<<P.Color, P.Style<<endl;
}
void main()
{
Pixels Point1=(5,3);
ShowPoint(Point1);
Pixels Point2=Point1;
Color.Point1+=2;
ShowPoint(Point2);
}

Question 5 Declare a structure to represent a complex number (a number having a real part
and imaginary part). Write C++ functions to add, subtract, multiply and divide
two complex numbers.

Question 6 An array stores details of 25 students (rollno, name, marks in three subject).
Write a program to create such an array and print out a list of students who have
failed in more than one subject.

void fail ( Student *s, int size)


113
C++ Lectures- Control & systems Department Lecturer : Karam Samir

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

{if (((s->m1<50) && (s->m2 <50))|| ((s->m1 <50) && (s->m3 <50)) || ((s-
>m2 <50) && (s->m3 <50)))

cout << s->name<<endl;

s++;

114
C++ Lectures- Control & systems Department Lecturer : Karam Samir

Q7 Write a program to print all employees whose live in Baghdad, each employee have name,
city, age, salary.

#include <iostream.h>
#include <string.h>
struct empl{
char name[40];
char city[40];
int age,salary;
};

void main ()
{empl s[5]={{"ahmed","baghdad",30,500},{"ali","mousl",22,300},
{"mohammed","baghdad",26,800},{"sara","basra",34,900},{"samar","baghdad",40,1000}};
for (int i=0;i<5;i++)
if (strcmp(s[i].city,"baghdad")==0)
cout <<s[i].name<<endl;

115
Lecture C++ programing
M.Sc Karam Samir class: 2nd

Q2- write a C++ program to create a table of books, each book have number,
title_name,auther_name,date, publisher city, publishing date, then enter information for 10
books and print all book where publishing date between (2013 to 2018).

116

You might also like