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

C++ Programming

The document is a comprehensive guide on C++ programming, authored by Dr. Mallika Verma, Dr. Sonam Singh, and Dr. Anjali Sharma from Miranda House, University of Delhi. It includes various C++ programs with flowcharts covering topics such as polynomial evaluation, quadratic equations, searching algorithms, and matrix manipulation, aiming to enhance students' understanding and practical skills in C++. The document also provides learning objectives, programming exercises, and a bibliography for further study.

Uploaded by

P B
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

C++ Programming

The document is a comprehensive guide on C++ programming, authored by Dr. Mallika Verma, Dr. Sonam Singh, and Dr. Anjali Sharma from Miranda House, University of Delhi. It includes various C++ programs with flowcharts covering topics such as polynomial evaluation, quadratic equations, searching algorithms, and matrix manipulation, aiming to enhance students' understanding and practical skills in C++. The document also provides learning objectives, programming exercises, and a bibliography for further study.

Uploaded by

P B
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

C++ Programming

Paper: Microprocessor and Computer Programming


Chapter: C++ Programming
Author: Dr Mallika Verma, Dr Sonam Singh & Dr Anjali
Sharma
College/ Department: Miranda House, University of Delhi

Institute of Lifelong Learning, University of Delhi 1


C++ Programming

Table of Contents

Introduction

C++ Programs with flowcharts

1. To evaluate a Polynomial: - (1) Converting Temperature from Fahrenheit to Celsius,


(2) Area of a Circle, (3) Volume of Sphere

2. To find the Roots of a Quadratic Equation: Real and Distinct, Repeated and Imaginary

3. To locate a Number in a Given List


 Linear search
 Binary search

4. (i) To find the Largest of Three Numbers.


(ii) To find the Largest Number in a Given List of Numbers

5. To find the sum and average of a list of numbers with and without arrays

6. (i) To calculate Factorial of a Number.


(ii) To calculate the first few Factorials.

7. (i) To check whether a entered Number is Prime


(ii) To calculate the first 100 prime numbers.

8. To rearrange a List of Numbers in Ascending and Descending Order.


(i) Sequential Sort program
(ii) Bubble Sort program

9. Manipulation of Matrices
(i) Add and subtract two Matrices.
(ii) Product of two Matrices

10. Calculate the value of 


 Sum of series of finite number of terms
 Random number generation

11. Solution of nonlinear equations


 Bisection method
 Newton Raphson method

Review Exercises
Programming Exercises
Bibliography

Institute of Lifelong Learning, University of Delhi 2


C++ Programming

C++ Programming

Learning Objectives:

C++ has become the most preferred and widely used programming language today as it
offers a powerful way of solving complex problems. Students need ample practice to master
C++ programming as is the case for any other programming languages. This chapter provides
numerous complete programs written in a simple format to improve clarity and facilitate
better understanding. These C++ programs try to provide answers to problems in a simple
and easy way. Wherever necessary, pictorial descriptions of programs (flowcharts) and
comments in programs have been included. Language tips and other special considerations
are highlighted as notes wherever essential.

The compiler used for the programs is Turbo C++ for Windows 4.5. Any compiler (Visual
C++, gcc or g++ in windows or Linux platforms) can be used with slight modifications in the
programs. The C++ examples listed are designed to give ample practice to the fresh
students. All the topic will concentrate on the fundamentals but exposing the C++‟s behavior,
feature, in-depth and in details. It is combination of the notes, examples, questions and
quizzes. The program topics listed below have been arranged in the learning sequence order
with the aim that students will be able to write programs in C++.

Institute of Lifelong Learning, University of Delhi 3


C++ Programming

C++ Computer Programming

1. To evaluate a polynomial:
(i) Area of Circle
(ii) Volume of Sphere
(iii) Conversion of temperature from Fahrenheit to Celsius

Institute of Lifelong Learning, University of Delhi 4


C++ Programming

// To evaluate a polynomial: 1: Area of Circle 2. Volume of Sphere


// 3. Conversion of temperature from Fahrenheit to Celsius
# includeiostream.h
# includeconio.h
void main( )
{
clrscr();
float A, r, V, F, C ;
int ch;
do
{ // beginning of do-while loop
cout<<”Enter 1 for area of circle \n”;
cout<<”Enter 2 Conversion of temperature from Fahrenheit to Celsius \n”;
cout<<”Enter 3 for volume of sphere \n”;
cin>> ch;
switch (ch)
{ // beginning of switch statement
case 1:
{
cout “ Enter the value of radius r \n”;
cin r; //accepting the input
A = 3.1415 * r * r; //calculating area
cout<<”Area of circle is :” << A;
break; }
case 2:
{
cout “ Enter the value of temperature in F \n”;
cin F; //accepting the input
C = 0.55 * (F – 32); //calculating temperature
cout<<” Value of temperature in Celsius is :” << C;
break;
}

case 3:
{
cout “ Enter the value of radius r \n”;
cin r; //accepting the input
V = 3.1415 * r * r * r; //calculating volume
cout<<”Volume of sphere is :” << V;
break;
}

default:
cout<<” Wrong choice entered! \n”
} // end of switch
} while (ch <=3); // end of do while
getch()
} //END OF PROGRAM

Institute of Lifelong Learning, University of Delhi 5


C++ Programming

2. To find the Roots of a Quadratic Equation: Real and Distinct, Repeated and
Imaginary

Institute of Lifelong Learning, University of Delhi 6


C++ Programming

// Roots of a Quadratic equation


# includeiostream.h
# includeconio.h
# includecmaths.h
void main( )
{
Float a,b,c,d, r,r1,r2 ;
clrscr();
cout<<”To Find The Roots Of A Quadratic Equation \n”;
do //beginning of do-while loop
cout “ Enter the three coefficients of the Quadratic equation of the form
a x 2  bx  c  0 \ n”;
cin a  b  c; //accepting the coefficients
if (a= =0) //checking if coefficient of x*x is zero
{
cout<<”Equation is Linear”;
}
else
{
  
d  b *b  4 * a * c ;  //calculating the discriminant
if(d > 0 ) //condition for real & distinct root
{
cout “ Roots are real and distinct\n”;
  
r1  b  sqrt(d ) 2 * a ;
r 2   b  sqrt(d ) 2 * a ;
cout “ the Roots are \n”  r1  “&” r2;
}
else if (d = = 0) //condition for repeated roots
{
cout “ Roots are repeated\n”;
 
r   b 2* a ; 
cout “ The Roots are \n”  r ;
}
else if (d < 0 ) //condition for imaginary roots
{
cout “ Roots are imaginary\n”;
d = -d;
  
r1  b 2 * a ;
r 2 sqrt(d ) 2 * a  ;
cout “ the Roots are \n”  r1  “+i” r2  “&” r1  “-i” r2 ;
//display imaginary root
}
}
cout<<”\n Do You Want To Solve Another Equation: Yes = 1 , No = 0 “ <<”\n”;
// accepting user choice to continue program
cin>>ch;
}
while (ch= =1); //checking do-while loop condition
Institute of Lifelong Learning, University of Delhi 7
C++ Programming

}
getch()
} //END OF PROGRAM
3. To locate a Number in a Given List
(i) Linear search Program

Institute of Lifelong Learning, University of Delhi 8


C++ Programming

// Locate a number in a list


# includeiostream.h //for header files
# includeconio.h //for clrscr()
void main ( )
{
int a [10], n, num, f, pos, i; // declaring variables
clrscr( );
cout “ To locate a number in a given list ( Linear Search)\n”;
cout “ enter the list size\n”;
cin>> n; //total number in the list
cout “ Enter an array of” <<n << “ elements:\n”;
for (i=0;i<n;i++)
{
cin>> a[i]; // entering numbers in an array using for loop
}
cout “ Enter the number to be searched:\n”;
cin>>num; //accepting number to be searched
for (i=0; i<n; i++)
{
if (a[i] = = num)
{
f = 1; // flag set to 1
pos = i;
}
}
iff = = 0) //checking whether flag is reset
{
cout “ The number does not exist in the list:\n”;
}
else
{
cout “ the number” <<num<< “ exists at the position” <<pos+1<<”in the list”;
// printing position of the number
}
getch( );
} // End of Program

Institute of Lifelong Learning, University of Delhi 9


C++ Programming

Institute of Lifelong Learning, University of Delhi 10


C++ Programming

3. To locate a Number in a Given List


(ii) Binary Search

Binary Search Algorithm


Step 1: Sort the numbers in ascending order
Step 2: Find the middle element of the sorted list
Step 3: Compare the number to be searched with the middle element of the list.
Step 4: If the number to be searched is equal to the middle element the “number if found” and corresponding index
is returned.
Step 5: If the number to be searched is smaller than the middle element of the sorted array, repeat step 2 to 4 for
the sub-list to the left of the middle element.
Step 6: If the number to be searched is greater than the middle element of the sorted list, repeat step 2 to 4 for the
sub-array to the right of the middle element.
Step 7: If the remaining list is searched for the number then the number is “not present in the list”.

Program 1:
// Locate a number in a list using Binary search
# includeiostream.h //for header files
# includeconio.h //for clrscr()
int search (int[], int, int);
int main ( )
{
int a [100], n, i, f, num, res; // declaring variables
clrscr( );
cout “ To locate a number in a given list ( Binary Search)\n”;
cout “ enter the list size\n”;
cin>> n; //total number in the list
cout “ Enter elements of the list in ascending order” << “\n”;
for (i=0; i<n; ++i )
{
cin>> a[i]; // entering numbers in an array using for loop
}
cout “ Enter the number to be searched:\n”;
cin>>num; //accepting number to be searched
res= search(a, n, num) // calling function search with actual parameters
if (res!=0)
cout << “ \n Number is in list at “ << res+1 << “position”;
else
cout << “ \n Number is not in the list “ ;
getch();
} // End of Program

int search(int x[],int n, int e) // function defined after the program


{
int lo, hi, mid;
lo=0; //low
hi=n-1; // high
while (lo < = hi) // while loop
{
mid = (lo + hi)/2 // middle position of the list
if(e ==x[mid]) // If the number to be searched is equal to the middle element
return mid; // return the corresponding index or position
else
if ( e > a[mid]) // If the number to be searched is greater than the middle element
lo = mid+1; // is repeated the process starting from right of mid position/index
else

Institute of Lifelong Learning, University of Delhi 11


C++ Programming

hi = mid-1;} // else the process is repeated starting from left of mid position/index
} // end of function

Program 2: A step by step approach to understand Binary Search


// A program to search a number randomly picked between 1 to 8 using Binary search
# includeiostream.h //for header files
# includeconio.h //for clrscr()
int main ( )
{
char A;
clrscr( );
cout “ Select a number between 1 – 8” << endl; //user selects a number
cout “ Is the number selected less than 5? Give us a hint (y or n) ? \n”;
cin>>A; //enter y or n

if (A == „y‟) // the selected number is between 1 and 4


{
cout “ Is the number less than 3? (y/n)? \n”;
cin>>A; //enter y or n
if (A == „y‟) // the selected number is 1 or 2
{
cout “ Is the number less than 2? (y/n)? \n”;
cin>>A; //enter y or n
if (A == „y‟)
cout<< “ The selected number is 1”<< endl;
else cout<< “ You have selected number 2”<< endl;
}
else // The selected number is either 3 or 4
{
cout “ Is the number less than 4? (y/n) ? \n”;
cin>>A; //enter y or n
if (A== „y‟)
cout<< “ The selected number is 3”<< endl;
else cout<< “ You have selected number 4”<< endl;
}
}
else // The selected number is in between 5 and 8 and the above process is repeated
cout “ Is the number less than 7? (y/n) ? \n”;
cin>>A; //enter y or n
if (A == „y‟) // the number is 5 or 6
{
cout “ Is the number less than 6? (y/n)? \n”;
cin>>A; //enter y or n
if (A == „y‟)
cout<< “ The selected number is 5”<< endl;
else cout<< “ You have selected 6”<< endl;
}
else // the number is 7 or 8
cout “ Is the number less than 8? (y/n)? \n”;
cin>>A; //enter y or n
if (A == „y‟)
cout<< “ The selected number is 7”<< endl;
else cout<< “ You have selected number 8”<< endl;
}

Institute of Lifelong Learning, University of Delhi 12


C++ Programming

}
getch( );
} // End of Program

Institute of Lifelong Learning, University of Delhi 13


C++ Programming

4. (i) To find the Largest of Three Numbers

// Largest of three numbers


# includeiostream.h //for header files
# includeconio.h //for clrscr()
void main ( )
{
float a, b, c; //declaring float type variables
clrscr( );
cout “ Find the Largest of Three Numbers\n”;
cout “ Enter the three numbers one by one:\n”;
cin>> a >> b>>c; //accepting the numbers one by one
if (a > b && a > c)
cout “ The largest number is:” << a << “\n”; //comparing a with b and c
else if (b > a && b > c )
cout “ The largest number is:” << b << “\n”; //comparing b with a and c
else
cout “ The largest number is:” << c << “\n”; //comparing c with b and b
getch( );

Institute of Lifelong Learning, University of Delhi 14


C++ Programming

} // End of Program

4. (ii) To find the Largest Number in a Given List of Numbers

Institute of Lifelong Learning, University of Delhi 15


C++ Programming

// Largest from a list of n numbers


# includeiostream.h //for header files
# includeconio.h //for clrscr()
voidmain ( )
{
int i = 0, largest, n; //declaring integer type variable
int num[20]; //declaring an array of size 20
cout “ To find the largest in a given list\n”;

cout “ Enter the list size:\n”;


cin>> n; //total number of elements in the list
cout “ Enter the numbers one by one:\n”;
for (i=0; i<n; i++) // entering numbers in array using for loop
{
cin>> num[i];
}
largest = num[0]; // assume largest number at position 1
for (i=0; i<n; i++)
{ //comparing other values of array (defines by variable d) with largest
int d = num[i];
if (d > largest)
largest = d; // if d is larger than largest then swap
}
cout<< “ the largest number is :” << largest << “\n”;
getch( );
} //End of Program

Institute of Lifelong Learning, University of Delhi 16


C++ Programming

5. To find the sum and average of a Given List of Numbers with and without array

Institute of Lifelong Learning, University of Delhi 17


C++ Programming

// Sum and Average of a list of n numbers using array


# includeiostream.h //for header files
# includeconio.h //for clrscr()
int main ( )
{
int i = 0, sum = 0, n; //declaring integer type variable
int num[20]; //declaring number as an array of size 20
float avg; // declaring average as float
cout “ To find the sum and average of a given list\n”;
cout “ Enter the list size:\n”;
cin>> n; //total number of elements in the list
cout “ Enter the numbers one by one:\n”;
for (i=0; i<n; i++) // entering numbers in array using for loop
{
cin>> num[i];
sum + = num[i]; // calculating sum using composite assignment operator
}
avg = sum/n; // calculating average
cout<< “ Sum is =” << sum << “\n and average is =” << avg;

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


{ //calculating deviation of numbers in the list about average
float d = num[i] - avg;
cout<< “ i =” << i+1 << “ number = “<< num[i]<< “ Deviation “ << d<< “\n “;
getch( );
} //End of Program

// Sum and Average of a list of n numbers using while loop without array
# includeiostream.h //for header files
# includeconio.h //for clrscr()
int main ( )
{
int i = 0, n; //declaring integer type variable
double sum = 0, avg; // declaring sum and average as double
cout “ To find the sum and average of 10 numbers\n”;
while (i < 10 )
{
cout “ Enter a number n \n”;
cin>>n; // entering numbers using while loop
sum = sum + n; // calculating sum
i++ // updating count variable
}
avg = sum/10; // calculating average
cout<< “ Sum is =” << sum << “\n and average is =” << avg;
getch( );
} //End of Program

Institute of Lifelong Learning, University of Delhi 18


C++ Programming

6. Calculation of Factorial of an integer

// Factorial of a number
# includeiostream.h //for header files
# includeconio.h //for clrscr()
void main ()
{
int i,n; // Declaring integer type variable
int f =1, //initializing f to be 1
clrscr ( );
cout “ To Calculate Factorial of a Number\n”;
cout<< “Enter Number = “;
cin>> n;
for(i=1; i<=n; i++) // Loop to calculate factorial of a number
f = f*i; // evaluating factorial
cout “ Factorial of the number” << n << “ is ” <<f;
getch( );
} //End of Program

Institute of Lifelong Learning, University of Delhi 19


C++ Programming

6. (ii) To calculate the first few Factorials

// Factorial of first few integers


# includeiostream.h //for header files
# includeconio.h //for clrscr()
int main ( )
{
int i,j,n; // Declaring integer type variable
int f =1,
clrscr ( );
cout “ To Calculate first few Factorials\n”;
cout<< “Enter a Number n = “;
cin>> n; // accepting number whose first few factorials is to be calculated
for (i=1; i<=n; i++) // Loop to calculate factorial of a number from 1 to n
{
int f = 1 //initializing f to be 1
for ( j = i; j > 0; j- -) // Loop to calculate factorial of a number
{
f = f*j; // evaluating factorial of a number
}
cout “ Factorial of the number” <<i<< “ is ” <<f<<”\n”;// printing factorials
}

Institute of Lifelong Learning, University of Delhi 20


C++ Programming

getch( );
} //End of Program
7. (i) To check whether a Given Number is a Prime Number

// Program to check whether a number entered is prime or not?


# includeiostream.h //for header files
# includeconio.h //for clrscr()
int main ( )
{
int i, n, c = 0; // declaring variables
clrscr( );
cout“To check whether a given Number is Prime or not\n”;
cout “Enter the number\n”;

Institute of Lifelong Learning, University of Delhi 21


C++ Programming

cin>> n;
for ( i = 2; i < n; i ++ )//loop to check the divisibility of the number by 2 to n
{
if ( n % i ) ==0) //checking whether the no is divisible by i
{
c++;//flag whose value is incremented whenever the no is divisible by i
}
}
if (c = = 0) // when flag is zero the number is prime
cout n << “ is a prime number\n”;
else
cout n << “ is not a prime number \n”;
}
getch( );
} //End of program

7. (ii)To calculate the first 100 prime numbers

Institute of Lifelong Learning, University of Delhi 22


C++ Programming

// A program to calculate and display the first 100 prime numbers


# includeiostream.h //for header files
# includeconio.h //for clrscr()
void main ( )
{
int i, j = 2, c, y = 0; // declaring variables
clrscr( );
cout “To calculate the first 100 prime numbers\n”;
do // starting do – while loop
{
c= 0; // initializing flag to 0
i = 2;
for( j = 2; j< i; j ++ )//loop to check the divisibility of the number by 2 to n
{
if ( i % j ) = = 0) //checking whether the no is divisible by i
c++; //flag whose value is incremented whenever the no is divisible by i
}
if (c = = 0) // when flag is zero the number is prime
{
cout i<< “\t”;
y++; //increments y which counts the number of prime numbers
}
i++; // i is incremented which stores the number being checked for prime
}
while (y!=100); //y is not equal to 100
getch( );
} //End of program

Institute of Lifelong Learning, University of Delhi 23


C++ Programming

8. (i) To rearrange a List of Numbers in Ascending and Descending Order using


sequential sorting of numbers

Institute of Lifelong Learning, University of Delhi 24


C++ Programming

// To arrange a list of numbers in ascending and descending order using


sequential sorting
# includeiostream.h //for header files
# includeconio.h //for clrscr()
int main ()
{
int n, i, j, a[20], k, temp, ch, x; //declaring variables
clrscr( );
cout<< “To arrange a list of numbers in ascending and << “descending order using
sequential sorting \n”;
cout<< “ Enter the list size\n”;
cin>> n;
cout<< “ Enter the numbers one by one\n”; // entering numbers in an array
for ( i = 0; i < n; i ++)
{
cin>> a[i];
}
do // beginning of do-while loop
{
cout<< “ Enter your choice: 1: Ascending order, 2: Descending order\n”;
cin>> ch; // switch variable
switch(ch);
{
case 1; // subprogram case1 for arranging in ascending order
for(j = 0; j < n; j++)
{
for (k = j + 1; k < n; k ++)
{
if( a[j] > a[k] // check condition by comparing numbers of the list
{
temp = a[j];
a[j] = a[k];
a[k] = temp; // if condition not satisfied swapping of numbers
}
}
}
cout<< “ The numbers arranged in ascending order are \n”;
for( i = 0; i < n; i ++) // Loop for displaying the sorted number list
{
cout<< a[i]<< “\t”;
}
break; //for ending first case

case 2; // subprogram case 2 for arranging in descending order


for(j = 0; j < n; j++)
{
for (k = j + 1; k < n; k ++)
{
if( a[j] < a[k]
{
temp = a[j];

Institute of Lifelong Learning, University of Delhi 25


C++ Programming

a[j] = a[k];
a[k] = temp;
}
}
}
cout<< “ The numbers arranged in descending order are \n”;
for ( i = 0; i < n; i ++)
{
cout<< a[i] << “\t”;
}
break;
}
cout<< “ \n Do you want to start the program again?:1 = yes; 0 = no \n”
cin>> x;
}
while(x = = 1); // checking do-while loop condition
getch( );
} //End of Program

Institute of Lifelong Learning, University of Delhi 26


C++ Programming

8 (ii). To rearrange a List of Numbers in Ascending and Descending Order using


Bubble sort technique

Institute of Lifelong Learning, University of Delhi 27


C++ Programming

// To arrange a list of numbers in ascending and descending order using Bubble


sort technique
# includeiostream.h //for header files
# includeconio.h //for clrscr()
void main ( )
{
int n, i, j, a[20], k, temp, ch, x, ; //declaring variables
clrscr( );
cout<< “To arrange a list of numbers in ascending and “”
<< “descending order using bubble sort \n”;
cout<< “ Enter the list size\n”;
cin>> n;
cout<< “ Enter the numbers one by one\n”; // entering numbers in an array
for ( i = 0; i < n; i ++)
{
cin>> a[i];
}
do // beginning of do-while loop
{
cout<< “ Enter your choice: 1: Ascending order, 2: Descending order\n”;
cin>> ch;
switch(ch);
{
case 1; // subprogram case1 for arranging in ascending order
for (j = 1; j < n; j++)
{
for (k = 0; k < j; k ++)
{
if( a[j] < a[k] // check condition by comparing numbers of the list
{
temp = a[j];
a[j] = a[k];
a[k] = temp; // if condition not satisfied swapping of numbers
}
}
}
cout<< “ The numbers arranged in ascending order are \n”;
for( i = 0; i < n; i ++) // Loop for displaying the sorted number list
{
cout<< a[i] << “\t”;
}
break; //for ending first case

case 2; // subprogram case 2 for arranging in descending order


for(j = 1; j < n; j++)
{
for (k = 0; k < j; k ++)
{
if ( a[j] > a[k] // check condition by comparing numbers of the
list
{
temp = a[j];
a[j] = a[k];

Institute of Lifelong Learning, University of Delhi 28


C++ Programming

a[k] = temp; // if condition not satisfied swapping of numbers


}
}
}
cout<< “ The numbers arranged in descending order are \n”;
for ( i = 0; i < n; i ++) // Loop for displaying the sorted number list
{
cout<< a[i] << “\t”;
}
break; //for ending second case
}
cout<< “ \n Do you want to continue:1 = yes; 0 = no \n”
cin>> x;
}
while(x = = 1); // checking do-while loop condition
getch( );
} //End of Program

9 Manipulation of Matrices:

Institute of Lifelong Learning, University of Delhi 29


C++ Programming

(i) Add and subtract two Matrices

Institute of Lifelong Learning, University of Delhi 30


C++ Programming

// Program for Addition and subtraction of two matrices


# includeiostream.h
# includeconio.h
int main ( )
{
intr1, c1, r2, c2,i ,j, x, ch; // declaring variables
inta[10][10], b[10][10], c[10][10]; //initialization of size of 2 dimendional array for
matrix
clrscr ( );
cout<< “Addition and Subtraction of two matrices \n”;
cout<< “ Enter the number of rows and columns of Matrix A\n”;
cin>> r1 >> c1; // size of matrix A
cout<< “ Enter the number of rows and columns of Matrix B\n”;
cin>> r2>> c2; // size of matrix B
if( ( r1 = = r2) && ( c1 = = c2)) //condition for addition and subtraction
{
cout “ Matrices can be added or subtracted\n”;

cout “ Input the Matrix Arow wise:\n”;


for (i =0; i < r1; i++)
{
for (j=0;I <c1; j++)
{
cout<< “ Matrix A [“<< i << ”][“<< j << “] = “;
cin>>a[ i ][j]; // entering values for Matrix A
}
}
cout “ Matrix A is :\n”;
for (i = 0; i < r1; i++)
{
for (j = 0; j < c1; j++)
{
cout<< a [i] [j] << “\t“ ; // displaying Matrix A
}
cout<< “\n”;
}

cout “ Input the Matrix B row wise:\n”;


for (i =0; i <r2; i++)
{
for (j=0; j < c2; j++)
{
cout<< “ Matrix B [“<< i << ”][“<< j << “] = “;
cin>>b [ i ][j]; // entering values for Matrix B
}
cout<< endl;
}
cout “ Matrix B is :\n”;
for (i = 0; i < r1; i++)
{
for (j = 0; j < c1; j++)
{
cout<< b [i] [j] << “\t“ ; // displaying Matrix B

Institute of Lifelong Learning, University of Delhi 31


C++ Programming

}
cout<< “\n”;
}

do
{
cout<< “ Enter choice 1: Addition 2: Subtraction \n”;
cin>> ch; //accepting choice
switch(ch)
{
case1: // The sum of the two matrices A and B
for (i=0; i<r1; i ++)
{
for (j=0; j< c1; j++)
{
c [i] [j] = a [i] [j] + b[i] [j];
}
cout “ The Sum of the two matrices A and B is :\n”;
for (i = 0; i < r1; i++)
{
for (j = 0; j < c1; j++)
{
cout<< c [i] [j] << “\t“ ; // displaying the sum Matrix
}
cout<< “\n”;
}
break;

}
Case2: // The difference of the two matrices A and B
for (i = 0; i < r1; i ++)
{
for ( j = 0; j < c1; j++)
{
c [i] [j] = a [i] [j] - b[i] [j];
}
cout “ The Difference of the two matrices A and B is :\n”;
for (i = 0; i < r1; i++)
{
for (j = 0; j < c1; j++)
{
cout<< c [i] [j] << “\t“ ; // displaying the difference Matrix
}
cout<< “\n”;
}
break;
}
cout “ \n Do you want to continue? Press 1 for Yes and 0 for \n”;
cin>> x;
}
while ( x = = 1); // checking do-while loop condition
}
else

Institute of Lifelong Learning, University of Delhi 32


C++ Programming

{
cout<< “ Matrix cannot be added/subtracted\n”; //if-else condition
}
getch ( );
} // End of Program

9. (ii) Product of two Matrices

// Program to find product of two matrices

Institute of Lifelong Learning, University of Delhi 33


C++ Programming

# includeiostream.h
# includeconio.h
int main ( )
{
int r1, c1, r2, c2,i ,j, k ; // declaring variables
int a[10][10], b[10][10], c[10][10]; //initialization of size of 2 dimendional array for
matrix
clrscr ( );
cout<< “Multiplication of two matrices \n”;
cout<< “ Enter the number of rows and columns of Matrix A\n”;
cin>> r1 >> c1; // size of matrix A
cout<< “ Enter the number of rows and columns of Matrix B\n”;
cin>> r2>> c2; // size of matrix B
if(c1 = = r2) //condition for multiplication
{
cout “ Matrix A and B can be multiplied\n”;

cout “ Input the Matrix A row wise:\n”;


for (i = 0; i < r1; i++)
{
for (j = 0; I < c1; j++)
{
cout<< “ Matrix A [“<< i << ”][“<< j << “] = “;
cin>> a[ i ] [ j ]; // entering values for Matrix A
}
}
cout “ Matrix A is :\n”;
for (i = 0; i < r1; i++)
{
for (j = 0; j < c1; j++)
{
cout<< a [i] [j] << “\t“ ; // displaying Matrix A
}
cout<< “\n”;
}

cout “ Input the Matrix B row wise:\n”;


for (i = 0; i < r2; i++)
{
for (j = 0; j < c2; j++)
{
cout<< “ Matrix B [“<< i << ”][“<< j << “] = “;
cin>> b [ i ][ j ]; // entering values for Matrix B
}
cout<< endl;
}
cout “ Matrix B is :\n”;
for (i = 0; i < r1; i++)
{
for (j = 0; j < c1; j++)
{
cout<< b [i] [j] << “\t“ ; // displaying Matrix B
}

Institute of Lifelong Learning, University of Delhi 34


C++ Programming

cout<< “\n”;
}

// for loop for multiplying the two matrices A and B


for (i = 0; i < c1; i ++)
{
for ( j = 0; j < c2; j++)
{
for ( k = 0; k < c1; j++)
{
c [i] [j] += a [i] [k] + b[k] [j];
}
cout “ The product of the two matrices A and B is :\n”;
for (i = 0; i < r1; i++)
{
for (j = 0; j < c1; j++)
{
cout<< c [i] [j] << “\t“ ; // displaying the product Matrix
}
cout<< “\n”;
}

}
else
{
cout<< “ Matrix cannot be multiplied\n”; //if-else condition
}
getch ( );
} // End of Program

Institute of Lifelong Learning, University of Delhi 35


C++ Programming

10. Determination of 
(i) Summing a series /4 = 1 - 1/3 + 1/5 - 1/7 + 1/9....

// Program to find the value of Pi


# includeiostream.h
# includeconio.h
int main ( )
{
double sum = 0, pi = 0; // declaring variables
int i, j, sign, n;
cout << " Determining  by summing a series of finite number of terms\n " ;
cout << " Enter Number of terms (> 100 at least! ) ";
cin >> n;
i = 1; // initialising variables
j = 1;
sign = 1;
while (j <= n) //while loop for summation
{
sum = sum + (1 / double(i) * sign);
i += 2;
sign = sign * (-1);
j++;
}
pi = sum * 4;
cout << " Value of  = “ << pi << endl;
getch;
}

(ii) Calculation of  using Monte Carlo method

Monte Carlo Algorithm


Step 1: Draw a square of 1x1 and inscribe a circle in it
Step 2: generate pairs of random numbers x and y between
0 and 1
Step 3: Plot them in the square
Step 4: Find the number of such points in the circle.
Step 5: Number of points in the circle divided by the total
number of points is the ratio of the areas
Step 6: this area is pi/4

x
1 x

Institute of Lifelong Learning, University of Delhi 36


C++ Programming

// Program for calculation of Pi using Monte Carlo method


//The area of ¼ circle is pi/4 (radius =1)and the area of square is 1 (side =1)
//If N random numbers are scattered, their number is proportional to the areas of each shape
// pi/4 : number of random numbers inside ¼ circle (j): total (NUM)
//pi = 4 * j/NUM
//The following program tests for a number of iterations. For each point generated, the distance is
checked, if it is smaller than 1, then it is within the circle and counter j is incremented
#include <iostream>// header files
#include <time.h> // time
#include <stdlib.h> // srand
#define NUM 100000000
int main()
{
double x, y, pi; // declaring variables used
int i, j=0;
srand(time(NULL)); // changes seed value for random number generation
for ( i=1; i <= NUM; i++)
{
x= (double) rand()/RAND_MAX; //random number generation between 0 &1
y= (double) rand()/RAND_MAX;
if (x*x + y*y <=1) // increment counter when inside circle
j++;
}
Pi = (double) 4 * j / NUM;
cout << pi << endl ;
return 0;
}

Institute of Lifelong Learning, University of Delhi 37


C++ Programming

11.Solution of Non linear equation


(i) Bisection method

Institute of Lifelong Learning, University of Delhi 38


C++ Programming

// Program for solution of nonlinear equations Bisection method


#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
cout<<"The program evaluates the root of a equation x*x-2=0"<<endl;
float a, b, c, fa, fb, fc; // declaring variables
cout<<"Enter the limit of the interval for the equation x*x-2=0"<<endl;
cin>>a;
cin>>b;
cout<<"["<<a<<","<<b<<"]";
fa=a*a-2;
fb=b*b-2;
if(fa*fb<0) // check sign
{
while (fabs(a-b)>0.0001)
{
c=(a+b)/2; // bisect interval
fc=c*c-2;
if(fa*fc<0) // check convergence
{
b=c;
}
else // update interval
{
a=c;
}
}
cout<<"The root exist in the interval and it is"<<c<<endl;
} else
cout<<"The root doesn't exist in the given interval";
getch();
} //END OF PROGRAM

11. Solution of nonlinear equations

Institute of Lifelong Learning, University of Delhi 39


C++ Programming

(ii) Newton Raphson method

// Newton Raphson method for solving nonlinear equations

Institute of Lifelong Learning, University of Delhi 40


C++ Programming

#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
clrscr();
float y,x1,xn,fx,dfx;
int i=1;
cout<< "Program to calculate the root of equation x*x-12=0"<<endl;
cout<< "Enter the guess value for the root of equation x*x-12=0"<<endl;
cin>>x1;
while(fabs(xn-y)>0.00001)
{
fx=x1*x1-12;
dfx=2*x1;
xn=x1-(fx/dfx);
y=x1;
x1=xn;
cout<<"Iteration "<<i<<". "<<x1<<endl;
i++;
}

cout<<"The root of the eqn is "<<x1;


getch();
} // END

Institute of Lifelong Learning, University of Delhi 41


C++ Programming

Review Exercises

1. What is the output of the program


#include<iostream.h>
int main()
{
int n=1;
cout<<"The numbers are;"<<endl;
do
{
cout <<n<<"\t";
n++;
} while (n<=100);
}
a) Output numbers 0 to 99
b) Output numbers 1 to 99
c) Output numbers 0 to 100
d) Output numbers 1 to 100 

2. What is the output of the following program fragment


{
int a=20, b=25;
a=a++;
b= ++b;
cout<< a << “ “ << b << endl;
}
a. 20 25
b. 20 26
c. 21 26 
d. 21 15

3. What is the result of the following expression


x=y=z=0
a. x=0, y=null, z=null
b. x=0,y=0,z=0 
c. x=0,y=1,z=2
d. none of the above

4. What is the result after execution of the following statement?


x=10; y = ++x;

a. x=10,y=10
b. X=10,y=11
c. X=11,y=10
d. X=11,y=11 

5. Which of the following control statement creates an infinite loop?


a. for( : : ) 
b. while( : : )
c. when(: : )
d. if ( : : )
6. In a program Break statement used

Institute of Lifelong Learning, University of Delhi 42


C++ Programming

a. to control the switch statement


b. to force immediate termination of a loop
c. both a and b 
d. only a
7. Which of following will not return a value?
a. int
b. void 
c. empty
d. null
8. The & operator in C++is ?
a. address operator 
b.indirection operator
c. logical and operator
d. logical or operator
9. When two variables are compared which is the correct operator to use?
A. :=
B. =
C. equal
D. ==

10. Which of the following variables cannot be declared ?


a. structure
b. pointer
c. class
d. void 
11. The && operator is a ………………operator, it means ?
a. Logical OR
b. Bitwise OR
c. Logical AND 
d. Bitwise AND
12. The << operator is ?
a. stream extraction operator
b. stream insertion operator 
c. left shift operator
d. right shift operator

13. The conditional expression ( m<n ? m : n) evaluates to


a. n if m < n
b. m if m<n 
c. n if m>n
d. none of the above
e.
14. Functions can return the following ?
a. Arrays
b. Reference
c. Objects
d. all of above 
15. Every function in C++ are followed by
a. Parameters
b. Parenthesis 
c. Curly braces

Institute of Lifelong Learning, University of Delhi 43


C++ Programming

d. None of these
16. What is the only function all C++ programs must contain?
A. start()
B. system()
C. main() 
D. program()
17. Which of the following is a correct comment?
A. */ Comments */
B. ** Comment **
C. /* Comment */ 
D. { Comment }

18. Evaluate !(1 && !(0 || 1)).


A. True 
B. False
C. the expression cannot be evaluate

19. The file iostream includes


a. The declarations of the basic standard input-output library. 
b. The streams of includes and outputs of program effect.
c. Both of these
d. None of these
20. Which of the following is not a valid escape code?
a. \t
b. \v
c. \f
d. \w 

Institute of Lifelong Learning, University of Delhi 44


C++ Programming

Programming Exercises

1. Write a C++ program to calculate Fibonacci numbers xn, n=1,2, …,1000


using the series xn+1 = xn+ xn-1 with x0=1, x1=1, n=1,2,…
2. Write a C++ program to rearrange a list of random numbers x n into ascending
order
3. Write a C++ program that uses while loop to calculate the factorials of n positive
intergers 1,2,…,1000
4. Write a C++ program to calculate the volume and the area of a cylinder of radius r
and height h
5. Write a C++ program to calculate the sum of the series
1 1 1 1 1
𝑆𝑈𝑀 = 1 − + − + … + −
2 3 4 49 50
6. Write a C++ program to calculate the sum of the series
1 1 1 1 1
𝑆𝑈𝑀 = 1 − + − + … + −
2! 3! 4! 49! 50!
7. Write a C++ program to calculate the sum of the series
𝑆𝑈𝑀 = 1 − 32 + 52 − 72 + … + (−1)𝑛 2𝑛 + 1 , 𝑛 = 50

8. Write a C++ program to calculate the sum of a squares of odd numbers between
112 and 489
9. Write a C ++Program to test the increment and decrement operators with while
loop
10. Write a C++ program to calculate the integer square root of a number
11. Write a Boolean valued function with a single integer parameter It will return True
if the integer is a prime number between 1 and 1000 (note: 1is not usually counted
as a prime number). Hints:
(i) if a number is not prime, it has at least one prime factor less than or equal to its
square root, and (ii) (32 x 32) = 1024 and 1024 > 1000.
12. Write a C++ program to find factorial of integers using recursive function
13. Write a C++ program to find the power of a number using recursive function
14. Write a C++ program through which an unspecified number of elements can be
entered. Find sum and average of these numbers entered and also the deviation
from its mean of the numbers
15. Writ a C++ program to create a Pascal triangle in a square matrix
16. Write C++ program s to determine the root of the following equation to three
significant digits 𝑓 𝑥 = 𝑥 𝑠𝑖𝑛𝑥 + 𝑥 cos 𝑥 = 0 using (i) Bisection method, (ii) Newton
Raphson method and (iii) secant method. Compare the three methods in terms of
order of convergence
17. For the polynomial equation 𝑥 4 − 8 𝑥 3 + 14𝑥 2 9𝑥 − 25 = 0. Does a root exist ? if so,
write a C++program to find one root using Newton Raphson method
18. Write a C++program to find the value of sinx by summing the following series with
an absolute error less than .005 for x = .25

𝑥3 𝑥5
𝑠𝑖𝑛𝑥 = 𝑥 − + … ..
3! 5!

Institute of Lifelong Learning, University of Delhi 45


C++ Programming

Bibliography

Here is a short list of references to books

1. Programming with C++, John R Hubbard adapted by Atul Kahate,


Schaum’s Outlines, Tata McGraw Hill Publishing Company,2008
2. Object Oriented Programming with C++, E Balagurusamy, McGraw Hill
Education (India) Private Limited 2013
3. C++ An Active Learning Approach, Randal Albert & Todd Breedlove, Jones
and Bartlett Publishers, 2010
4. Computer Science A Structured Approach using C++, Behrouz A. Forouzan
& Richard F. Gilberg, Cengage Learning, 2012
5. Programming Principles and Practice using C++, Bjarne Stroustrup,
Addison Wesley, 2008
6. C++ Cookbook, D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis
& Jeff Cogswell, O’Reilly, Shroff Publishers & Distributors Pvt. Ltd, 200
7. User manuals for C++, turbo C++, Borland C++ and for gcc and g++
8. And websites http://www.gnu.org/software/make/manual/,
http://www.valgrind.org, tutorials on various websites on C++
9. Inputs from the students of B. Sc (Hons) Physics II year Semester III
batches of 2011, 2012, 2013

Institute of Lifelong Learning, University of Delhi 46

You might also like