Sie sind auf Seite 1von 39

College of Engineering C++ &Numerical Methods Lecturer

Civil Department Examples Muhammad I. Omer

Program #1-1:
Hello
// my program #1-1 in C++ Kurdistan
#include <iostream>
using namespace std;

int main ()
{
cout << "Hello Kurdistan";
return 0;
}

Example 2-1:

// My program #2-1 in C++ 4


// operating with variables
#include <iostream>
using namespace std;
int main ()
{
int a, b; // declaring variables:
int result;
a = 5;
b = 2;
cout << a=<<a<<\n;
a = a + 1;
cout << a=<<a<<\n;
result = a - b; // process:
cout << result; // print out the result:
return 0; // terminate the program:
}

Example 2-2:

// My program #2-2 in C++ 6


// initialization of variables
#include <iostream>
using namespace std;
int main ()
{ int a=5; // initial value = 5

1
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

int b(2); // initial value = 2


int result; // initial value undetermined
a = a + 3;
result = a - b;
cout << result;
return 0;}

Example 2-3:

// My program #2-3 in C++ This is a string


#include <iostream>
#include <string>
using namespace std;
int main ()
{
string my = "This is a string";
cout << my<<\n;
cout << my;
return 0;
}

Example 2-4:

// My program #2-4 in C++


// my first string
#include <iostream>
#include <string>
using namespace std;
int main ()
{ string my;
my = "This is the initial string content";
cout << my << endl;
my = "This is a different string content";
cout << my << endl;
return 0;}

After Compile and execution the out put will be

This is the initial string content


This is a different string content

2
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

Example 3-1:

// My program #3-1 in C++


// input & output example
#include <iostream>
using namespace std;
int main ()
{ int i;
cout << "Please enter an integer value: ";
cin >> i;
cout << "The value you entered is " << i;
cout << " and its double is " << i*2 << ".\n";
return 0;}

After Compile and execution the output will be

Please enter an integer value: 702


The value you entered is 702 and its double is 1404.

Example 3-2:

// My program #3-2 in C++


// cin with strings
#include <iostream>
using namespace std;
int main ()
{ char civil[50];
cout << "What's your name? ";
cin.getline (civil,50);
cout << "Hello " << civil << ".\n";
cout << "What is your favorite team? ";
cin.getline (civil,50);
cout << "I like " << civil << " too!\n";
return 0;
}

After Compile and execution the output will be

What's your name? Saman Bakir


Hello Saman Bakir.
What is your favorite team? The Kurdistan team
I like The Kurdistan team too!

3
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

Example 3-3:

// My program #3-3 in C++


// stringstreams
#include <iostream>
#include <sstream>
using namespace std;
int main ()
{ char eng[50];
float price=0;
int quantity=0;
cout << "Enter price: ";
cin.getline (eng,50);
stringstream(eng) >> price;
cout << "Enter quantity: ";
cin.getline (eng,50);
stringstream(eng) >> quantity;
cout << "Total price: " << price*quantity << endl;
return 0;
}

After Compile and execution the output will be


Enter price: 22.25
Enter quantity: 7
Total price: 155.75
Press any key to continue

Example 3-4:

// My program #3-4 in C++


// stringstreams
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main ()
{ string eng ("15 16");/*declares a string object with a
value of "15 16"*/
int my1, my2; //declare int object
stringstream(eng)>> my1>>my2;/*extract first integer to
my1 and second integer to
my2*/
cout << my1 <<endl<< my2;
return 0;

4
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

After compile and execution the output will be

15
16Press any key to continue

Example # 3-5

// My program #3-5 in C++//this program calculate


the user's pay.
#include <iostream>
using namespace std;
int main()
{ double hours, rate, pay;
cout <<" How many hours did you work? ";
cin >> hours;
cout <<" How much do you get paid per hours? ";
cin >> rate;
pay=hours * rate;
cout <<" you have earned $ "<<pay << endl;
return 0;}

After Compile and execution the out put will be


How many hours did you work? 8
How much do you get paid per hours?
5
you have earned $ 40
Press any key to continue

Example # 3-6

Write a program to convert gallon to liters

// My program #3-6 in C++//this program to convert gallon


to liters.
#include <iostream>
using namespace std;
int main()
{
int gallons, liters;
cout << "Enter number of gallons: ";

5
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

cin >> gallons; // this inputs from the user


liters = gallons * 4; // convert to liters
cout << "Liters: " << liters;
return 0;
}

Example # 4-1

write a program to find the value for below function.

x 2 , if x 0
y
x 2, if x 0

//program 4-1 on using if else enter value of x = 3


#include <iostream> value of y= 5
using namespace std;
int main()
{
int x;
cout <<"enter value of x = ";
cin>> x;
if (x<0)
cout <<"y="<<x*x<<endl;
else
cout <<"value of y= "<<x+2<<endl;
system ("pause") ;// to stop the system
return 0;
}

Example # 4-2
make a program to countdown using a while-loop:
// example 4-2 custom countdown using while-loop
#include <iostream>
using namespace std;
int main ()
{
int n;
cout << "Enter the starting number : ";
cin >> n;
while (n>0)
{
cout << n << ", ";
--n;
}

6
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

cout << "FIRE!\n";


return 0;
}

After Compile and execution the out put will be


Enter the starting number : 8
8, 7, 6, 5, 4, 3, 2, 1, FIRE!

Example # 4-3

Write a program to allow entering numbers till ending by zero

// example 4-3
#include <iostream>
using namespace std;
int main ()
{
unsigned long n;
do{
cout << "Enter number (0 to end): ";
cin >> n;
cout << "You entered: " << n << "\n";
}while (n != 0);
return 0;}

After Compile and execution the output will be

Enter number (0 to end): 12345


You entered: 12345
Enter number (0 to end): 160277
You entered: 160277
Enter number (0 to end): 0
You entered: 0

Example # 4-4
Make a program to countdown using a for loop:
// example 4-4 countdown using a for loop
#include <iostream>
using namespace std;
int main ()
{
for (int n=10; n>0; n--)
{
cout << n << ", ";

7
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

}
cout << "FIRE!\n";
return 0;
}

Example # 4-5

Write a program to find the value for below function.

y sin( x ) e | x| x x1.5

// Example 4-5 function result 1


#include <cmath> 9.23053press
#include <iostream>
using namespace std;
int main ()
{
int x;float y;
cin >> x;
y= sin(x)+ exp(fabs(x)+x)+pow (x,1.5);
cout <<y;
return 0;
}
Example 4-6:
Write a program to find the value for below function and make it repeated.

x4 , if x 0
y
x x 7, if x 0
2

//Example 4-6 to evaluate function value enter value of x = 5


#include <iostream> value of y= 23
#include <string> do you want to continue
#include<cmath> (y/n)
using namespace std;
int main()
{
int x;
string i="y",p="y";
while (i==p)
{system("cls"); // to clean the screen
cout <<"enter value of x = ";
cin>> x;
if (x<0)
cout <<"y="<<pow(x,4)<<endl;
else
cout <<"value of y= "<<x*x+x-7<<endl;

cout <<"do you want to continue (y/n)" ;


cin >>p;

8
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

}
system ("pause") ;// to stop the system
return 0;
}

Example 4-7:
Re-write the above program using char instead of string for repeating
//Example 4-7 to evaluate function value enter value of x = -5
#include <iostream> value of y= 625
#include<cmath> do you want to continue (y/n)
using namespace std;
int main()
{ int x; char n='y',y='y';
while (n==y)
{system("cls"); // to clean the screen
cout <<"enetr value of x = "; cin>> x;
{if (x<0)
cout <<"y="<<pow(x,4)<<endl;
else
cout <<"value of y= "<<x*x+x-7<<endl; }
cout <<"do you want to continue (y/n)" ;
cin >>y; }

system ("pause") ;// to stop the system


return 0;}

Example 5-1:

// My program #5-1 in C++ b is 0


#include <iostream>
using namespace std; b is 1
int main()
{ This is executed.
bool b;
Press any key
b = false;
to continue
cout << b is << b << \n;
b = true;
cout << b is << b << \n;
if(b) cout << This is executed.\n;
b = false;
if(b) cout << This is not executed.\n;
return 0;
}

Example 5-2:
// My program #5-2 in C++ 31.4159

9
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

// defined constants: calculate


circumference
#include <iostream>
using namespace std;
#define PI 3.14159
#define NEWLINE \n
int main ()
{ double r=5.0; // radius
double circle;
circle = 2 * PI * r;
cout << circle;
cout << NEWLINE;
return 0;}

Example 5-3:
// My program #5-3 in C++ The Area is
//calculate area of circle using const 26.4208
#include <iostream>
using namespace std; Press any key
const float PI = 3.1415926; to continue
int main()
{
float r = 2.9;
cout << "The Area is " << PI*r*r
<<"\n";
return 0;
}

Example 6-1:

5
// My Example 6-1
// compound assignment operators
#include <iostream>
using namespace std;
int main ()
{ int a, b=3;
a = b; // a=3
a+=2; // equivalent to a=a+2
cout << a;
return 0;}

Example 6-2:

10
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

//my program 6-2 7


// conditional operator
#include <iostream>
using namespace std;
int main ()
{ int a,b,c;
a=2;
b=7;
c = (a>b) ? a : b;
cout << c;
return 0;}

Example 6-3:

1+2-3*4/5%6
1 + 2 - (3*4) / 5 % 6
1 + 2 - 12 / 5 % 6
1 + 2 - (12 / 5) % 6
1+2-2%6
1 + 2 - (2 % 6)
1+2-2
(1 + 2) - 2
32
1

Example 6-4:

//this program to find the result and grade for the students
#include <iostream>
#include <string>
using namespace std;
int main()
{ string name; float x;
cout<<"enter the student name : " ;
getline (cin,name);
cout << "enter his degree" <<endl ;
cin>>x;
cout <<"************************************************"<<endl ;
if (x>=50) {cout<<"congratulation "<<name<<endl; }
if ( x>=90)cout<< "pass with grade Excellent" ;
else if (x<90 && x>80)cout<< "pass with grade V.Good" ;
else if (x<80 && x>70)cout<< "pass with grade Good" ;
else if (x<70 && x>60)cout<< "pass with grade Medium" ;

11
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

else if (x<60 && x>=50)cout<< "pass with grade Accept" ;


else cout<< "Fail" ;
cout <<endl<<"****************************************"<<endl ;
return 0;
}

Example 7-1:

// My example #7-1 10, 9, 8, 7, 6, 5, 4, 3,


// break loop example countdown aborted!
#include <iostream>
using namespace std;
int main()
{
int n;
for (n=10; n>0;n--)
{ cout << n<<,;
if (n==3)
{ cout <<countdown aborted!;
break;
}
}
return 0;
}

Example 7-2:

// My example #7-2 10, 9, 8, 7, 6, 4, 3, 2, 1,


// example continue loop fire!
example for skip number 5
#include <iostream>
using namespace std;
int main()
{
int n;
for (n=10; n>0;n--)
{
if (n==5)

12
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

continue;
cout << n<<,;
}
cout << fire!\n;
return 0;}

Example 7-3:

// My example #7-3 10, 9, 8, 7, 6, 5, 4, 3, 2,


// goto loop example 1, fire!
#include <iostream>
using namespace std;
int main()
{ int n=10;
loop:
cout<<n<<,;
n--;
if (n>0) goto loop;
cout<< fire!\n;
return 0;}

Example 7-4:

// My example #7-4
// switch example
#include <iostream>
using namespace std;
int main()
{
int num;
cout << "enter a number from 1 to 3 ";
cin>>num;
switch (num)
{
case 1:
cout <<"111.\n";
break ;
case 2 :
cout << "222.\n";
break ;
case 3 :
cout <<"333.\n";
break ;
default :
cout << " you must enter either 1, 2, or 3.\n";
13
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

}
return 0;}

Example 8-1:

// arrays example 8-1 12206


#include <iostream>
using namespace std;
int billy [] = {16, 2, 77, 40,12071};
int n, result=0;
int main ()
{
for ( n=0 ; n<5 ; n++ )
{ result += billy[n];
}
cout << result;
return 0;
}

Example 8-2:

Example: multidimensional array for assigning values to the array


// my program 8-2
#include<iostream>
using namespace std;
#define w 5
#define h 3
int main ()
{
int b [h][w];
int i,j;
for (i=0;i<h;i++)
{
for (j=0;j<w;j++)
{
b[i][j]=(i+1)*(j+1);
cout<< b[i][j]<<"\t";
}
cout<<"\n";
}
return 0;
}

14
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

Example 8-3 Write a program to read an array then print one element of array
#include <iostream> Output : 3
using namespace std;
int main() 0 1 2
{ 0 1 2 3
short matrix[][3] = {{1,2,3},{2,3,1}};
cout<<matrix[1][1]<<endl; 1 2 3 1
return 0;
}

Example 8-4: Write a program to find summation and average of array.

# include <iostream> 76
using namespace std ; 381
int main () Press any key to continue
{
int array1[5]={ 100,85,65,77,54};
int s=0;
for(int a=0;a<5;a++)
s=s+array1[a];
float avg=s/5;
cout<<avg<<endl<<s<<endl;
return 0;
}

Example 8-5: Write a program input an array then print the array in accending.
#include <iostream> please enter x [0]: 5
using namespace std ; please enter x [1]: 6
int main () please enter x [2]: 2
{ please enter x [3]: 3
int x[5]; please enter x [4]: 1
int temp, i,j; 1 2 3 5 6
for( i=0; i<5 ; i++) Press any key to continue
{
cout<<"please enter x ["<<i<<"]: ";
cin>>x[i];
}
for(i=0; i<5 ; i++)
for(j=i+1; j<5; j++)
if (x[i]>x[j])
{
temp=x[i];
x[i]=x[j];
x[j]=temp;

15
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

}
for(i=0; i<5 ; i++)
cout<<x[i]<<\t;
cout<<endl;
return 0;
}

Example 8-6: Write a program to input an array then print in opposite direction
#include <iostream> please enter x [0]: 5
using namespace std ; please enter x [1]: 6
int main () please enter x [2]: 7
{ please enter x [3]: 9
int x[10]; please enter x [4]: 10
int i; 10 9 7 6
for( i=0; i<10; i++) 5
{ Press any key to continue
cout<<"please enter x ["<<i<<"]: ";
cin>>x[i];
}
for(i=9; i>=0 ; i--)
cout<<x[i]<<"\t";
return 0;
}

Example 8-7: Write a program to input two array then merged into one array
#include <iostream> please enter a [0]: 6
using namespace std ; please enter b [0]: 5
int main () please enter a [1]: 6
{ please enter b [1]: 5
int a[5],b[5],c[10],i; please enter a [2]: 6
for( i=0; i<5 ; i++) please enter b [2]: 5
{ please enter a [3]: 6
cout<<"please enter a ["<<i<<"]: "; please enter b [3]: 5
cin>>a[i]; please enter a [4]: 6
cout<<"please enter b ["<<i<<"]: "; please enter b [4]: 5
cin>>b[i]; 6 6 6 6
} 6 5 5 5
for( i=0; i<10 ; i++) 5 5
{ Press any key to continue
if (i<5)
c[i]=a[i];
else
c[i]=b[i-5];
}
for( i=0; i<10 ; i++)
cout<<c[i]<<"\t ";
return 0;
}
Example 8-8: Write a program to input an array then find the maximum number
between the elements.
#include <iostream> please enter a[0]:4
using namespace std ; please enter a[1]:6

16
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

int main () please enter a[2]:5


{ please enter a[3]:7
int a[5]; please enter a[4]:3
int max, i; 7 Press any key to
for( i=0; i<5 ; i++) continue
{
cout<<"please enter a["<<i<<"]:";
cin>>a[i];
}
max=a[0];
for( i=0; i<5 ; i++)
if (a[i]>max)
max=a[i];
cout<<max<<" ";
return 0;
}

Example 8-9: Write a program to input an array then make the summation between
odd numbers and even numbers separately
#include <iostream> input n:6
using namespace std ; b[0]=8
int main () b[1]=7
{ b[2]=2
int b[20]; b[3]=3
int n,i,s1,s2; b[4]=1
cout<<"input n:"; b[5]=9
cin>>n;
for(i=0;i<n;i++) sum even element:10
{ sum odd element:20
cout<<"b["<<i<<"]="; Press any key to continue
cin>>b[i];
}
s1=s2=0;
for(i=0; i< n; i++)
{
if(b[i]%2==0)
s1+=b[i];
else
s2+=b[i];
}
cout<<"\nsum even element:"<<s1;
cout<<"\nsum odd element:"<<s2<<"\n";
return 0;
}
Example 8-10: Write a program to input a [5][5] array and print array then change
the location of diagonal and transpose diogonal
#include <iostream> 1 2 3 4
using namespace std ; 5
int main () 6 7 8 9
{ 10
int a,b,i,j; 11 12 13 14
a=4; 15

17
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

int x[5][5]={1,2,3,4,5,6,7,8,9, 16 17 18 19
10,11,12,13,14,15,16,17,18,19,20, 20
21,22,23,24,25}; 21 22 23 24
for(i=0;i<5;i++) 25
{
for(j=0;j<5;j++) 5 2 3 4
{ 1
cout<<x[i][j]<<"\t"; 6 9 8 7
} 10
cout<<"\n"; 11 12 13 14
} 15
cout<<"\n"; 16 19 18 17
for(i=0;i<5;i++) 20
{ 25 22 23 24
for(j=0;j<5;j++) 21
{ Press any key to continue
if(i==j)
{
b=x[i][j];
x[i][j]=x[i][a];
x[i][a]=b;
}
}
a-=1;
}
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
{
cout<<x[i][j]<<"\t";
}
cout<<"\n";
}
return 0;
}

Example 9-1:
// function example 9-1
#include <iostream>
using namespace std;
int addition (int a, int b) //define function name is
addition
{ int r;
r=a+b;
return (r);}
int main ()

18
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

{ int z;
z = addition (5,3);
cout << "The result is " << z;
return 0;}

The result is 8

Example 9-2:
// function example 9-2 for f(x,y)=x+y2 2
#include <iostream> 2
using namespace std; The result
int f (int x, int y)//define function name is f is 6
{ int r;
r=x+y*y;
return (r);}
int main ()
{ int z,x,y;
cin >>x>>y;
z = f (x,y);
cout << "The result is " << z;
return 0;}

Example 9-3:
// void function example to show I'm a function!
//message on the screen example 9-3
#include <iostream>
using namespace std;
void printmessage ()
{cout << "I'm a function!";}
int main ()
{ printmessage ();
return 0;}
Example 9-4:
//Example 9-4 for print function only Before call
#include <iostream> in function
using namespace std;
void f()
{ cout << "in function\n\n\n";}
int main() After call
{ cout << "Before call\n";
f();
cout << "After call\n";
return 0;}

19
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

Example 9-5:
// example-9-5 default values in functions 6
#include <iostream> 5
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;}

Example 9-6:

// example 9-6 on overloaded function 10


#include <iostream> 2.5
using namespace std;
int operate (int a, int b)
{return (a*b);}
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;}

Example 9-7:

// program 9-7 factorial calculator Please type a number: 9


#include <iostream> 9! = 362880
using namespace std;
long factorial (long a)
{ if (a > 1)
return (a * factorial (a-1));
else
return (1);}
int main ()
{long number;
20
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

cout << "Please type a number: ";


cin >> number;
cout << number << "! = " << factorial
(number);
return 0;}

Example #9-8: write a program using function for getting the number if it is odd or
even.

// example 9-8 declaring functions prototypes Type a number (0 to exit): 9


#include <iostream> Number is odd.
Type a number (0 to exit): 6
using namespace std; Number is even.
Type a number (0 to exit): 1030
void odd (int a);// declaration of Number is even.
Type a number (0 to exit): 0
functions Number is even.
void even (int a);

int main ()
{
int i;
do {
cout << "Type a number (0 to exit):
";
cin >> i;
odd (i);
} while (i!=0);
return 0;}
void odd (int a)
{
if ((a%2)!=0) cout << "Number is
odd.\n";
else even (a);}
void even (int a)
{
if ((a%2)==0) cout << "Number is
even.\n";
else odd (a);}

Example 9-9:
// example9-9-arrays as parameters 5 10 15
#include <iostream> 2 4 6 8 10
using namespace std;

void printarray (int arg[], int length) {


for (int n=0; n<length; n++)
cout << arg[n] << " ";
cout << "\n"; }

21
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

int main ()
{
int firstarray[] = {5, 10, 15};
int secondarray[] = {2, 4, 6, 8, 10};
printarray (firstarray,3);
printarray (secondarray,5);
return 0;
}

Problem-1: write a program for subtract two numbers


// program-2-function example
#include <iostream>
using namespace std;
int subtraction (int a, int b)//function name is subtraction
{ int r;
r=a-b;
return (r);}
int main ()
{ int x=5, y=3, z;
z = subtraction (7,2);
cout << "The first result is " << z << '\n';
cout << "The second result is " << subtraction (7,2) <<
'\n';
cout << "The third result is " << subtraction (x,y) <<
'\n';
z= 4 + subtraction (x,y);
cout << "The fourth result is " << z << '\n';
return 0;}
The first result is 5
The second result is 5
The third result is 2
The fourth result is 6

Problem-2 : write a program for print a multidimensional array

// program-4-Initializing multidimensional arrays.


#include <iostream>
using namespace std;;

void printArray( const int [][ 3 ] ); // prototype


int main()
{
int array1[ 2 ][ 3 ] = { { 1, 2, 3 }, { 4, 5, 6 } };
int array2[ 2 ][ 3 ] = { 1, 2, 3, 4, 5 };
int array3[ 2 ][ 3 ] = { { 1, 2 }, { 4 } };
cout << "Values in array1 by row are:" << endl;
printArray( array1 );
cout << "\nValues in array2 by row are:" << endl;
printArray( array2 );
cout << "\nValues in array3 by row are:" << endl;
22
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

printArray( array3 );
return 0; } // indicates successful termination
// function for output array with two rows and three columns
void printArray( const int a[][ 3 ] )
{ for ( int i = 0; i < 2; i++ ) // loop through array's rows
{for ( int j = 0; j < 3; j++ ) //loop through columns of current row
cout << a[ i ][ j ] << ' ';
cout << endl; // start new line of output
} // end outer for
} // end func
Values in array1 by row are:
1 2 3
4 5 6

Values in array2 by row are:


1 2 3
4 5 0

Values in array3 by row are:


1 2 0
4 0 0
Press any key to continue

Example 10-1:
// Example#10-1 basic file operations [file example.txt]
#include <iostream> Writing this to a file
#include <fstream>
using namespace std;
int main ()
{ ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
return 0;}

Example 10-2:
// Example#10-2- writing on a text file [file example.txt]
#include <iostream> This is a line.
#include <fstream> This is another
using namespace std; line.
int main () {
ofstream myfile ("example.txt");
if(myfile.is_open())
{ myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
}
else cout << "Unable to open file";
return 0;}

23
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

Example 10-3:
// Example#10-3 reading a text file This is a line.
#include <iostream> This is another line.
#include <fstream>
#include <string>
using namespace std;
int main () {
string civil;
ifstream myfile ("example.doc");
if (myfile.is_open())
{ while (! myfile.eof() )
{ getline (myfile,civil);
cout << civil << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;}
Example 11-1:
//calculate area under the curve x/ enter the value of x1 & x2 : 0 1
(1+x2) //base on strip width. enter the vlaue of dx : 0.0001
#include <iostream> value of integration = 0.346547
#include <string> no of iterations = 10000
#include <cmath> Press any key to continue
using namespace std;
int main()
{float x1,x2;double dx,area(0),y ;int
n=0;
cout<<"enter the value of x1 & x2 : " ;
cin >> x1>>x2;
cout<<"enter the vlaue of dx : " ;
cin >> dx;
while(x1<x2)
{ y=x1/(1+pow(x1,2));

area = area + (y * dx);


n=n+1 ;
x1=x1+dx;
}
cout <<"value of integration =
"<<area<<endl ;
cout<<"no of iterations = "<<n<<endl;
return 0;}

See the result in text book c++ and numerical analysis byJames M.Ortaga

Example 11-2:
// Example11-2 find the value of area under curve y=x/(1+x2)

24
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

based on the convergence parameter

#include <iostream>
#include <cmath>
using namespace std;
float rectangle (float a, float b,int n); //function
float f(float x); //function for finding y
int main()
{
int n0, n;
float a,b,eps, rc, rn;
cout <<"a,b,n0,eps=?\n";
cin>> a>>b>>n0>>eps;
cout <<"a ="<<a<<"b = "<<b<<endl;
cout <<"n0= " << n0 << "eps = "<<eps <<endl;
rc=rectangle(a,b,n0);
n=2*n0;
rn=rectangle (a,b,n);
while (fabs(rn-rc)>eps)
{n=n+n;
rc=rn;
rn=rectangle (a,b,n);
cout <<"integral= "<<rn<<"for n=" <<n<<endl;
}
return 0;}
float f (float x)
{return (x/(1.0+x*x));
}
float rectangle(float a, float b, int n)
{
float h, x, area(0);
h=(b-a)/(n+1);
x=a;
for (int i=1; i<=n;i++)
{
area =area +f(x);
x=x+h;
}
return (area * h);
}

a,b,n0,eps=?
0 1 2 0.0001
a =0b = 1
n0= 2 eps = 0.0001
integral= 0.262593 for n=8
integral= 0.302221 for n=16
integral= 0.323777 for n=32

25
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

integral= 0.335016 for n=64


integral= 0.340755 for n=128
integral= 0.343654 for n=256
integral= 0.345111 for n=512
integral= 0.345842 for n=1024
integral= 0.346208 for n=2048
integral= 0.34639 for n=4096
integral= 0.34649 for n=8192
Press any key to continue

H.W.1) Write a program to find the value of integration for


2

(x 4 x 2 6) dx
4
The integration accuracy to be 0.001
2

Hint the value of integration using calculus =232/15

H.W.2) Write a program to find the value of integration for


2

Sin
2
x dx The integration accuracy to be 0.001
0

Hint the value of integration using calculus =

H.W.3) Modify the above programs to be the value of integration accuracy = 1E-6
=.000001

H.W.
5
Sin 2 xdx
1. Write a program to find the approximate value of integration1 x using trapezoidal rule.

2. Find the approximate value for the area surrounded by the two curves f1(x) & f2(x), by the way
f1(x)=sin(x) and f2(x)=cos(x).
3. In 1976 the below equation been derived for gas compression coefficient Z:

1 y y2 y3
Z if Z value equals to 0.892 what will be the value of y in the equation?
(1 y ) 3

Example 12-1 Solve the equation sin x x + 0.5 = 0 manually and write a C++
program by using bisection method. If you know the accepted error is 0.00001.
According to the drawing the root is lies between 1.49 &1.5

Solution: Let f (x) = sin x x + 0.5 , remember that in the last section we have seen
that f has a root between 1.49 and 1.5 we can tabulate our result round to 4 decimal
places as follows.
Interval An bn x*=(an+bn)/2 f(x*) Absolute Error

26
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

[a0,b0] 1.49 1.50 1.495 0.002129 0.005


[a1,b1] 1.495 1.50 1.4975 -0.000185 0.0025
[a2,b2] 1.495 1.4975 1.49625 0.000973 0.00125
[a3,b3] 1.49625 1.4975 1.496875 0.000394 0.000625
[a4,b4] 1.496875 1.4975 1.497187 0.000105 0.000313
[a5,b5] 1.497187 1.4975 1.497348 -0.00000045 0.000161
[a6,b6] 1.497187 1.497348 1.497267 0.000003 0.000081
[a7,b7] 1.497267 1.497348 1.497307 -0.00000006 0.00004
Hence since | 1.497307 1.4 97267| 0.00004 > 0.00001 the approximated root is 1.4973

+Source code first test f(a)<0 or f(b)<0 f(b)<0


/ Example-12-1 to find the value of function sin (x) - x +0.5 using
bisect method
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
float f (float x)
{ return sin (x) - x +0.5 ; }//function
int main(){
int kmax;
float a,b,eps;
cout <<"input a,b,eps,kmax\n";
cin>> a>>b>>eps>>kmax; //kmax =max number of iterations
cout <<"the result are\n";
cout <<"k a b x f(x)\n";
int k=1;
float x=0.5*(a+b); //next bisection
while((k<=kmax)&&((b-a)>eps))
{
cout<<k<<setprecision(5)<<setw(12)<<x<<setw(15)<<f(x)<<setprecision(5)
<<setw(12)<<a<<setw(12)<<b<<endl;//print k,x,y,a,b
if (f(x)>0) a=x; //because f(b)<0
else b=x;
x=0.5*(a+b);
k++;}
if(k>kmax)cout <<"no convergence";
return 0; }
input a,b,eps,kmax
1.49 1.50 0.00004 10
the result are
k x f(x) a b
1 1.495 0.0021288 1.49 1.5
2 1.4975 -0.00018492 1.495 1.5
3 1.4962 0.00097279 1.495 1.4975
4 1.4969 0.00039413 1.4962 1.4975
5 1.4972 0.00010471 1.4969 1.4975
6 1.4973 -4.0094e-005 1.4972 1.4975
7 1.4973 3.2255e-005 1.4972 1.4973
27
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

8 1.4973 -3.9739e-006 1.4973 1.4973


Press any key to continue
H.W.Example 8.1 P-89 & exercises 8.1,8.2,8. page 96 in text book
Example# 12-2: Find a real root of the equation x3 x 1 = 0 manually by using
Newton - Raphson method,and the accepted error is 0.00001 .

f (2)=3*22-1=11

f (x )
x x 0 2 5 1.54545 error 2 1.54545 0.45455 0.00001
1 0 '
f (x ) 11
0
f (1.54545) 1.545453 1.54545 1 3.69117 1.54545 1 1.14572
f ' ( x ) 3 x 2 1 3(1.54545) 2 1 6.16525
1.14576
x 2 1.54545 1.35961 error 1.54545 1.35961 0.18584 0.00001
6.16487
f (1.35961) 1.359613 1.35961 1 0.15368
f ' ( x ) 3 x 2 1 3(1.35961) 2 1 4.54562
0.15368
x 3 1.35961 1.32580 error 1.35961 1.32580 0.03381 0.00001
4.54562
f (1.32580) 1.325803 1.32580 1 0.004619
f ' ( x ) 3 x 2 1 3(1.3258) 2 1 4.27323
0.004619
x 4 1.32580 1.3247191 error 1.32580 1.3247191 0.001081 0.00001
4.27323

3.3934 *10 5
x 5 1.3247191 1.32471 error 1.32741 1.32741 0.0000 0.00001
4.26449
Hence the required root is 1.32471

Example# 12-3: find the root of function cos(x)=x


// Example 12-2- to find the value of Give initial guess
function cos(x)=x //using Newton raphson 1

28
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

method Therootis0.739085
#include<iostream> Press any key to continue
#include<cmath>
using namespace std;
int main()
{double x;
cout<<"Give initial guess"<< endl;
cin>>x;
double err,tol=1e-12,x1;
int it,maxit=100;
it=0;
err=tol+1;
while(err>tol&&it<maxit)
{x1=x-(x-cos(x))/(1+sin(x));
err=fabs(x1-x);
x=x1;
it++;}
if(err<=tol)
cout<<"The root is"<<x<<endl;
else
cout<<"Error, no convergence\n";
return 0; }

Example 12-4/ find the root of function 2x2+1-ex =0 and write the output in a file.
//Example 12-3 tofind the value of enter the value of eps,
function 2x2+1-ex =0//using Newton kmax : .0000000001
raphson method 100
#include<iostream> Give initial guess
#include<cmath> 1
#include<fstream> Press any key to continue
using namespace std;
int main()
{float eps;int kmax;
cout << "enter the value of eps, kmax :
"; cin>>eps>>kmax;
cout<<"Give initial guess"<< endl;
double x;
cin>>x;
double err, x1;
int it;
it=0;
err=eps+1;
while(err>eps&&it<kmax)
{x1=x-(2*x*x+1-exp(x))/( 4*x-exp(x));
err=fabs(x1-x);
x=x1;
it++;}
ofstream file("root.txt");
if(err<=eps)
file<<"The root is"<<x<<endl;
else

29
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

cout<<"Error, no convergence\n";
file.close();
return 0; }
The output in the file will be: The root is0.74085

Example 13.2: Find the approximate solution to a differential equation with


Euler method for a function dy/dx=x+y, if you know y(0)=1, h=0.2 and for n=5.
// Example13-2- to find the approximate solution to a
differential equation with Euler method for a function

#include<iostream>
#include<iomanip>
using namespace std;
float f(float x ,float y) //function
{return x+y;}
int main ()
{float a,h,x[100],y[100];
int i,n;
cout << " enter value of x[0],n,h,y[0](n must be <100)\n";
cin >>x[0] >>n>>h>>y[0];
for (i= 0;i<n ;i++)
{ //this is euler loop
y[i+1] =y[i] + h*f(x[i],y[i]);
x[i+1] =x[i] + h;
}
cout<<setw(14)<<"x"<<setw(14)<<"y"<<setw(14)<<"\n";
for(i=0;i<=n;i++)
cout<<setprecision(5)<<setw(14)<<x[i]<<setw(14)<<y[i]<<setw(14)
<<endl;
return 0;}

value of a,n,h,y[0](n must be <100)


0 5 0.2 1
x y
0 1
0.2 1.2
0.4 1.48
0.6 1.856
0.8 2.3472
1 2.9766
Press any key to continue

Example 13-3

30
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

Compute the approximate value of at x=0.2 from the solution y(x) of the differential
equation
y x y 2 given the initial condition y(0)=1. Use Runge-Kutta method with h=0.2
K1 h. f ( xn , yn ) h.( x y 2 ) 0.2 (0 12 ) 0.2
h K 0 .2 0.2
K 2 h. f (( xn ), ( yn 1 )) 0.2 f ((0 ), (1 ) 0.2 (0.1 1.12 ) 0.262
2 2 2 2
h K 0 .2 0.262
K 3 h. f (( xn ), ( yn 2 )) 0.2 f ((0 ), (1 )) 0.2 (0.1 1.1312 ) 0.276
2 2 2 2
K 4 h. f (( xn h)), ( yn K 3 )) 0.2 f ((0 0.2), (1 0.276)) 0.2 f (0.2,1.276)
0.2 (0.2 1.276 2 ) 0.366
1 1
y1 y0 ( K1 2 K 2 2 K 3 K 4 ) 1 (0.2 2 0.262 2 0.272 0.366) 1.274
6 6

Example 13-4:
Apply Runge-Kutta equation to find dy/dx=x+y, y(0)=1 for dx interval=0.02 ut to
x=0.1
Solution : Solve the above equation using C++ source code
n=(0.1-0)/0.02=5
// Example13-4-Program to solve the first order
Differential using Runge-Kutta rule for y'=x+y
#include<iostream>
#include<iomanip>
using namespace std;
float f(float x ,float y) //function
{return x+y;}
int main ()
{float h,x[100],y[100],k1,k2,k3,k4;
int i,n;
cout << "value of x[0],n,h,y[0] are (n must be <100)\n";
cin >>x[0]>>n>>h>>y[0];
for (i= 0;i<n ;i++)
{
k1=h* f(x[i],y[i]);
k2=h*f(x[i]+h/2,y[i]+k1/2);
k3=h*f(x[i]+h/2,y[i]+k2/2);
k4=h*f(x[i]+h,y[i]+k3);
y[i+1] =y[i] +(k1+2*k2+2*k3+k4)/6; // value of y
x[i+1] =x[i] + h;
}
cout<<setw(14)<<"x"<<setw(14)<<"y"<<"\n";
for(i=0;i<=n;i++)
cout<<setprecision(5)<<setw(14)<<x[i]<<setw(14)<<y[i]<<endl;
return 0;}

value of x[0],n,h,y[0] are (n must be <100)


0 5 0.02 1
31
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

x y
0 1
0.02 1.0204
0.04 1.0416
0.06 1.0637
0.08 1.0866
0.1 1.1103
Press any key to continue

Solution by Gauss Jordan Elimination


Consider representing the set of linear equations given in equation

32
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

The solution to the equations is x1=13, x2=-11,x3=7

33
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

Write a source code for gauss elimination method to find the solution for above
simultaneous equations.
/
*******************************************************************
*Using Gauss-Jordan elimination to find the inverse matrix
*******************************************************************
*/
#include <iostream>
#define row 3 //enter number of rows
#define col row+1
using namespace std;
void print( float a[row][col] ); // print on the screen
int main()
{float a[row][col]={1,2,3,12, // array value
3,2,1,24,
2,1,3,36,};
float temp;
int i,j,k;
cout<<endl<<"Matrix Value"<<endl; // print the matrix.
print(a);
for (k=0;k<row;k++)
{
for (i=0; i<row;i++)
{ temp=a[i][k];
for (j=0; j<col;j++)
{ a[i][j]=a[i][j]/temp;}} // dividing matrix.

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


{ if(i==k)
for (j=0; j<col;j++)
a[i][j]=a[i][j];
else
for (j=0; j<col;j++)
a[i][j]=a[i][j]-a[k][j]; // setting matrix to zero.
}
}
for (i=0;i<row;i++)
{ temp=a[i][i];
for(j=0;j<col;j++)
a[i][j]=a[i][j]/temp;
}
cout<<endl<<"Matrix Inverse Unit"<<endl;
print(a); // Print unit matrix
return 0;}

void print ( float a[row][col] ) // print array function


{ cout<<"-----------------------------------\n";
for ( int m=0; m<row; m++)
{ for (int n=0; n<col-1 ; n++)
{ cout<<"X"<<n+1<<"= "<<a[m][n]<<" ";}
cout<<"Y="<<a[m][col-1]<<endl; }}

34
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

Matrix Value
-----------------------------------
X1= 1 X2= 2 X3= 3 Y=12
X1= 3 X2= 2 X3= 1 Y=24
X1= 2 X2= 1 X3= 3 Y=36
Matrix Inverse Unit
-----------------------------------
X1= 1 X2= 0 X3= 0 Y=13
X1= 0 X2= 1 X3= 0 Y=-11
X1= 0 X2= 0 X3= 1 Y=7
Press any key to continue

H.W.
1) Solve the below simultaneous equations using gauss-jordain method
5x1-x2+x3=10
2x1+4x2=12
X1+x2+5x3=-1

Ans[x1=2.5555,x2=1.7222,x3=-1.0555]

1) Solve the below simultaneous equations using gauss-jordain method


3.01x+6.03y+1.99z=1
4.16y+1.27x-1.23z=1
0.987x-4.81y+9.34z=1

Ans[x1=1592.6 , x2= -631.911, x3= - 493.618]

3)find the solution for below truss (find the forces)


1000 500
F4

F1 F5
F7 F9
F3
45o F6 30o 45o
F8
F2
500
Solution
0.7071F1-F4-0.866F5=0
0.7071F1+F3+0.5F5=-1000
F2-F6=0
-F3=0
-F7+0.7071F9=500
F4-0.7071F9=0
0.866F5+F6-F8=0
-.5F5-F7=-500
F8+0.7071F9

Example: write a program to calculate first dy/dx& second d2y/d2x derivatives for f(x)=xex and find
its value at x=1, use dx=0.01

35
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

//program 1-to find first&second drivitives for function f(X)=xex


#include <iostream>
#include <cmath>
float f(float );
using namespace std;
int main()
{float x,h;
cin>>x >>h ;
float f1=(f(x+h)-f(x-h))/(2*h) ;
float f2=(f(x+h)-2*f(x)+f(x-h))/pow(h,2) ;
cout<<"dx= "<<h<<" f'= "<<f1<<" f\"= "<<f2<<endl;
return 0;}
float f(float x)
{return x*exp(x);}
1
.01
dx= 0.01 f'= 5.43674 f"= 8.15432
Press any key to continue

Example: write a program to calculate y,y,y, y for f(x)=x4 , and compare it with exact values
when x=1, use h=.1
//program -2-to find first&second drivitives for function f(X)=x04
#include <iostream>
#include <cmath>
//float f(float );
float f(float x)
{return pow(x,4);}

using namespace std;


int main()
{float x,h;
cout<< "enter value of x ,dx\n";
cin>>x >>h ;
float f1=(f(x+h)-f(x-h))/(2*h) ;
float f2=(f(x+h)-2*f(x)+f(x-h))/pow(h,2) ;
float f3=(f(x+2*h)-2*f(x+h)+2*f(x-h)-f(x-2*h))/(2*pow(h,3)) ;
float f4=(f(x+2*h)-4*f(x+h)+6*f(x)-4*f(x-h)+f(x-2*h))/pow(h,4) ;

cout<<"dx= "<<h<<endl;
cout<<"appr-f' = "<<f1<<" exact f' = "<<4 *pow(x,3)<<endl;
cout<<"appr-f'' = "<<f2<<" exact f'' = "<<12*pow(x,2)<<endl;
cout<<"appr-f''' = "<<f3<<" exact f''' = "<<24*x <<endl;
cout<<"appr-f''''= "<<f4<<" exact f''''= "<<24 <<endl;

//cout<<"appr-f'= "<<f1<<"exact f\"= "<<f2<<endl;

return 0;}

enter value of x ,dx


1
.1
dx= 0.1
appr-f' = 4.04 exact f' = 4
appr-f'' = 12.02 exact f'' = 12

36
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

appr-f''' = 23.9999 exact f''' = 24


appr-f''''= 24.0011 exact f''''= 24
Press any key to continue

H.W. Resolve prob2 when x=2

Example # 16-1
Write the Source code for linear interpolation
//linear interpolation Example #16-1
#include <iostream>
using namespace std;
int main() { double x,x0,x1,y,y0,y1;
cout<<"Enter Value of x, x0, x1, y0, y1\n";
cin>>x>>x0>>x1>>y0>>y1;
y=y0+(x-x0)/(x1-x0)*(y1-y0);
cout<<"the approximate value of f("<<x<<")= "<<y;
return 0;}
Enter Value of x, x0, x1, y0, y1
1.15
1.1
1.2
1.9648
2.5722
the approximate value of f(1.15)= 2.2685

Example(16-3):
Result of an experiment is tabulated:
X 1 3 4 x6 y8 x2
9 xy
11 14
y 1 2 4 14 15 17 18 9
Plot the data 3 2 9 6 and find the formula that
corresponds to 4 4 16 16 best fit to those data.
6 4 36 24
Solution: 8 5 64 40
9 7 81 63
1 8 12 88
1 9 1 12
1 19 6
4 6
Sum 5 4 52 36 37
6 0 4 4
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

y=a+bx
y=6/11+7/11x
y=6/11+0.63636x

38
College of Engineering C++ &Numerical Methods Lecturer
Civil Department Examples Muhammad I. Omer

Write the Source code for Least square curve fitting


//least square curve fitting program

#include <iostream>
using namespace std;
int main() {
int n;
double x,y,sumx=0,sumy=0,sumxx=0,sumxy=0,a,b;
cout<<"What is the number of points";
cin>>n;
cout<<"Enter"<<n<<"pairs ,one pair line:\n";
for (int i=1;i<=n;i++){
cout<<'\t'<<i<<":";
cin>>x>>y;
sumx +=x;
sumy +=y;
sumxx +=x*x;
sumxy +=x*y ;}
a=(sumy*sumxx-sumx*sumxy)/(8*sumxx-sumx*sumx);
b=(n*sumxy-sumx*sumy)/(n*sumxx-sumx*sumx);
cout <<"The equation of the regression line is:\n"
<<"\ty ="<<b<<"x + "<<a<<endl;
return 0;}

What is the number of points8


Enter8pairs ,one pair line:
1:1 1
2:3 2
3:4 4
4:6 4
5:8 5
6:9 7
7:11 8
8:14 9
The equation of the regression line is:
y =0.636364x + 0.545455
Press any key to continue

39

Das könnte Ihnen auch gefallen