Programming Language II
Programming Language II
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:
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
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;
#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;
}
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
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
Example 8: write a program to replace the main diagonal with the first row
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
Example 10: Write a program to replace the elements of row with column
Example 11: Write a program to multiply the first row of the Array [A] with first
column of array [B]
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
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.
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.
Testing is easier
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;
}
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
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;
}
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;
}
Q9 writes a function to Calculates and returns the sum of the numbers in an array.
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: -
#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>
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);
strncat(stri,name,4);
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," ");
strcat(name,name1);
strupr(name);
strlwr(name);
convert the string name from small to capital and then from capital to small.
The statement
strset(name,'k');
The statement
strnset(name,'a',4);
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>
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);
}
#include<ctype.h>
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
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 << "length of str1 = " << strlen (str1 ) << endl;
cout << "length of str2 = " << strlen (str2 ) << endl;
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];
e) ++z;
f) char s[10];
cout << strncpy ( s, "hello ", 5 ) << endl;
g) char s[12];
strcpy ( s, "Welcome Home " );
)11(
cstring Functions
)18(
C++ Lectures- Control & systems Department Lecturer : Karam Samir
char s1[50]
= "jack";
char s2[50]
= "jill";
char s3[50];
a) jill
b) jack and jill
c) 8
d) 13
#include<iostream>
using namespace std;
int main( )
{
char str[80];
return 0;
}
#include<iostream>
int main( )
char str[80];
cin.getline(str, 80);
return 0;
#include<iostream>
int main( )
char str[80];
cin.getline(str,80);
words++;
56
C++ Lectures- Control & systems Department Lecturer : Karam Samir
return 0;
#include<iostream>
int main( )
cin.getline(str1, 80);
cin.getline(str2, 80);
57
C++ Lectures- Control & systems Department Lecturer : Karam Samir
str1[l++] = str2[i];
str1[l] = '\0';
return 0;
58
C++ Lectures- Control & systems Department Lecturer : Karam Samir
int main( )
gets(str1);
gets(str2);
int i;
if(str1[i] - str2[i] == 0)
else
return 0;
59
C++ Lectures- Control & systems Department Lecturer : Karam Samir
int main( )
char str[80];
cin.getline(str, 80);
61
C++ Lectures- Control & systems Department Lecturer : Karam Samir
int i;
if(i == l/2)
else
return 0;
#include<iostream>
int main( )
cin.getline(str1, 80);
61
C++ Lectures- Control & systems Department Lecturer : Karam Samir
cin.getline(str2, 80);
int i, j;
if(str1[i] == str2[j])
j++;
else
j = 0;
62
C++ Lectures- Control & systems Department Lecturer : Karam Samir
if(j == l)
else
return 0;
#include<iostream>
int main( )
char str[80];
cin.getline(str, 80);
63
C++ Lectures- Control & systems Department Lecturer : Karam Samir
int temp;
temp = str[i];
str[i] = str[j];
str[j] = temp;
return 0;
#include<iostream>
int main( )
64
C++ Lectures- Control & systems Department Lecturer : Karam Samir
char str[80];
cin.getline(str, 80);
for(int i=0;str[i]!='\0';i++)
return 0;
int main( )
char str[80];
65
C++ Lectures- Control & systems Department Lecturer : Karam Samir
cin.getline(str,80);
return 0;
Q11 Write the output of the following program. Assume that all
necessary header files are included.
void Encrypt(char T[])
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()
Encrypt(text);
return 0;
Ans: @a@E@E#rTH
if (islower(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];
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;i<=w;i++)
ki[i].len=0;
// for ( m; m<j;m++)
// cout << str[m];
71
C++ Lectures- Control & systems Department Lecturer : Karam Samir
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;}
Q ) write a C++ program to Replace the max word with min word.
71
C++ Lectures- Control & systems Department Lecturer : Karam Samir
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;
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:
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
*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++)
{
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
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;
}
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.
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
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()
{
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.
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;
}
84
C++ Lectures- Control & systems Department Lecturer : Karam Samir
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);
}
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;
}
#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;
struct Day
{
int month, date, year;
};
struct Student
{
int rollno, age;
char name[80];
Day date_of_birth;
float marks;
};
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
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;
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
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
}
void main()
{
readcom();
addcom();
subcom();
}
#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;
};
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;
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);
Display(Z);
}
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.
{if (((s->m1<50) && (s->m2 <50))|| ((s->m1 <50) && (s->m3 <50)) || ((s-
>m2 <50) && (s->m3 <50)))
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