Chapter One: Basics of C++: Structure of A Program #Include
Chapter One: Basics of C++: Structure of A Program #Include
Structure of a program
#include <iostream.h>
Lines beginning with a hash sign (#) are directives for the preprocessor. In this
case the directive #include <iostream.h> tells the preprocessor to include the iostream
standard file. This specific file (iostream.h) includes the declarations of the basic
standard input-output library in C++.
main ( )
The main ( ) corresponds to the beginning of the definition of the main
function. The word main is followed in the code by a pair of parentheses (()). That is
because it is a function declaration: after these parentheses we can find the body of
the main function enclosed in braces {}. What is contained within these braces is what
the function does when it is executed.
Ending semicolon
In C++, the separation between statements is specified with an ending
semicolon (;) at the end of each one, so the separation in different code lines does not
matter at all for this purpose.
Comments
Comments are parts of the source code disregarded by the compiler. They
simply do nothing. Their purpose is only to allow the programmer to insert notes or
descriptions embedded within the source code. So, if the program include comments
without the comment characters combinations //, /* */, the compiler will take them
as if they were C++ expressions, most likely causing one or several error messages.
There are two ways to insert comments in C++:
// line comment
/* block comment */
1
Basic Input / Output:
The standard C++ library includes the header file iostream.h, where the
standard input and output stream objects are declared.
Example-1
#include <iostream.h>
main ( )
{
cout << "Hello World";
}
Example-2
#include <iostream.h>
main ( )
2
{
int a;
cin>>a=10;
cout << a;
}
The values of the columns Size and Range depend on the system the program
is compiled for. The values shown above are those found on most 32-bit systems. But
3
for other systems, the general specification is that int has the natural size suggested by
the system architecture (one "word") and the four integer types char, short, int and
long must each one be at least as large as the one preceding it, with char being always
1 byte in size. The same applies to the floating point types float, double and long
double, where each one must provide at least as much precision as the preceding one.
Declaration of variables:
In order to use a variable in C++, we must first declare it specifying which data
type we want it to be. The syntax to declare a new variable is to write the specifier of
the desired data type (like int, bool, float...) followed by a valid variable identifier. For
example:
int a;
float b;
If you are going to declare more than one variable of the same type, you can
declare all of them in a single statement by separating their identifiers with commas.
For example:
int a, b, c;
Declaration of Characters:
The character variables can be declared as follows:
char name of character = ‘value’
Note:
When inventing the identifiers , they cannot match any keyword of the C++
language nor your compiler's specific ones, which are reserved keywords. The
standard reserved keywords are:
4
asm, auto, bool, break, case, catch, char, class, const, const_cast, continue,
default, delete, do, double, dynamic_cast, else, enum, explicit, export, extern, false,
float, for, friend, goto, if, inline, int, long, mutable, namespace, new, operator, private,
protected, public, register, reinterpret_cast, return, short, signed, sizeof, static,
static_cast, struct, switch, template, this, throw, true, try, typedef, typeid, typename,
union, unsigned, using, virtual, void, volatile, wchar_t, while.
Additionally, alternative representations for some operators cannot be used as
identifiers since they are reservedwords under some circumstances:
and, and_eq, bitand, bitor, compl, not, not_eq, or, or_eq, xor, xor_eq
Operators
Once we know of the existence of variables and constants, we can begin to
operate with them. For that purpose, C++ integrates operators.
Assignment (=)
The assignment operator assigns a value to a variable.
B = 2;
This statement assigns the integer value 2 to the variable B. The part at the left
of the assignment operator (=) is known as the L-value (Left value) and the right one
as the R-value (Right value). The L-value has to be a variable whereas the R-value
can be either a constant, a variable, the result of an operation or any combination of
these. The most important rule when assigning is the right-to-left rule: The
assignment operation always takes place from right to left, and never the other way:
For example:
#include <iostream.h>
main ( )
{
int a, b;
a = 10;
b = 4;
a = b;
b = 7;
cout << a;
cout << b;
5
}
o/P
a=4
b=7
Arithmetic operators :
The five arithmetical operations supported by the C++ language are:
Compound assignment:
When we want to modify the value of a variable by performing an operation on
the value currently stored in that variable we can use compound assignment operators:
Type of operator Meaning of operator
+= New value = Old value + increase
-= New value = Old value - subtraction
*= New value = Old value * multiplication
/= New value = Old value / division
%= New value = Old value % modulo
Example:
#include <iostream.h>
main ( )
{
int a=5, b=6;
a+=2; // equivalent to new a=old a+2
b/=2; // equivalent to new b=old b/2
cout << a;
cout << b;
}
6
Increase and decrease (++, --)
Shortening even more some expressions, the increase operator (++) and the
decrease operator (--) increase or reduce by one the value stored in a variable. They
are equivalent to +=1 and to -=1, respectively.
Example:
#include <iostream.h>
main ()
{
int a=5;
a++; // equivalent to a=a+1
cout << a;
}
o/P
a=6
7
Q1-Write a program that prints “Hello World I’m C++ program”:
#include <iostream.h>
main ()
{
cout << "Hello World ";
cout << "I'm a C++ program";
}
Q2- Write a program that prints the block letter “E” in a 7 × 6 grid of
stars like this:
*****
*
*****
*
*****
#include<iostream.h>
main( )
{
cout << "*****" << endl;
cout << "*" << endl;
cout << "*****" << endl;
cout << "*" << endl;
cout << "*****" << endl;
}
8
Line 4 missing y
Line 5 missing ; and input operator should be >>
Line 6 output operator should be <<
Line 7 should be }
9
H.W 1- What is the output (O/P) of the following program:
#include<iostream.h>
main( )
{
int n , m , z;
n=9;
m=6;
z=++n-m++;
cout << n << m<<z<< endl;
z=--n+m++;
cout << n << m<<z<< endl;
z=n++*m++;
cout << n << m<<z<< endl;
}
H.W 2- Write a program to find the total resistance and total current of
the following circuit:
R2=5Ohm
R1=3Ohm
V=10 volt
10
Chapter Two: Selection
Type of Meaning of
operator operator
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or
equal to
<= Less than or equal
to
Conditional structure ( if ):
The (if ) keyword is used to execute a statement or block only if a condition is
fulfilled, and its form is:
if (condition) statement
For example:
#include<iostream.h>
main ( )
{int a,b;
cin>>a;
if ( a>=0)
{
b=a+2;
cout << b;
}
cout << "a is negative number";
}
If-else statement:
The if-else is used to execute a statement or block by using keyword (if) if a
condition is fulfilled, and execute another statement or block if the condition is not
fulfilled by using the keyword else, and its form is:
else If construct:
Its form is:
if (condition1) statement (1)
else if (condition2) statement (2)
.
.
.
else statement (0)
Switch:
13
Its form is:
Swith (variable)
{
Case 1: Statemet 1; breake;
Case 2: Statemet 2; breake;
Case 3: Statemet 3; breake;
.
.
Case n: Statemet n; breake;
defaulte: Statemet 0;
}
Conditional Opterator:
Its form is:
(Condition?Statement-1:statement-2)
Example:
#include <iostream.h>
main ()
{
int a,b,c;
a=2;
b=7;
c = (a>b ? a : b);
cout << c; O/P 7
}
Q4-Write a program to convert a test score into its equivalent letter grade
(use else if CONSTRUCT):
#include<iostream.h>
main( )
{
int score;
15
cout << "Enter your test score: ";
cin >> score;
if (score > 100)
cout << "Error: that score is out of range.";
else if (score >= 90)
cout << "Your grade is an A." << endl;
else if (score >= 80)
cout << "Your grade is a B." << endl;
else if (score >= 70)
cout << "Your grade is a C." << endl;
else if (score >= 60)
cout << "Your grade is a D." << endl;
else if (score >= 0)
cout << "Your grade is an F." << endl;
else
cout << "Error: that score is out of range.";
}
Q5-Write a program that reads the user’s age and then prints “You are a
child.” if the age < 18, “You are an adult.” if 18 ≤ age < 65, and “You are a senior
citizen.” if age ≥ 65.
#include<iostream.h>
main( )
{ int age;
cout << "Enter your age: ";
cin >> age;
if (age < 18)
cout << "You are a child."<<endl;
else if (age < 65)
cout << "You are an adult."<<endl;
else
cout << "you are a senior citizen."<<endl;
}
17
Q8-Write a program to convert a test score into its equivalent letter grade
(Use a switch statement):
#include<iostream.h>
main( )
{
int score;
cout << "Enter your test score: ";
cin >> score;
if (score > 100 || score < 0) cout << "Error: that score is out of range."<<endl;
else
switch (score/10)
{ case 10:
case 9: cout << "Your grade is an A."<<endl; break;
case 8: cout << "Your grade is a B." <<endl; break;
case 7: cout << "Your grade is a C." <<endl; break;
case 6: cout << "Your grade is a D." <<endl; break;
default: cout << "Your grade is an F." <<endl; break;
}}
H.W
1- Write a program that prints the maximum of four integers entered:
2- Write a program that prints the positive if the number is more than or equal
zero and negative if number is less than zero:
3- Write a program to print the result of student as follows: (Use else if
CONSTRUCT):
NON if X>100.
Pass if X≥50.
Fail if X<50.
4- Write a program that prints the median of three integers entered:
19
Chapter Three: Iteration
1- For Loop:
Its form is:
For(first value; condition of continue; increment or decrement)
Loop statements
#include<iostream.h>
main( )
{
int n;
cout << "Enter a positive integer: ";
cin >> n;
int sum=0;
for (int i=1; i <= n; i++)
sum += i*i;
cout << "The sum of the first " << n << " squares is " << sum << endl;
}
20
Example-3: Write a program that counts from 1 to 10 (use for loop):
#include<iostream.h>
main( )
{
for (int i=1; i <= 10; i++)
cout << i << endl;
}
Example-5: Write a program that prints the sum of all integers between 1
to 100 that are divisible by 7 (use while loop):
#include<iostream.h>
main( )
{
int i,sum=0;
for (i=1;i<=100;i++)
{
if (i%7==0)
sum+=i;
}
cout<<sum<<endl;
}
2- while loop:
Its form is:
Initial value;
While(continue condition)
{
Loop Statements;
Increment or decrement value;}
Example-8: Write a program that prints the square root of each number
input by the user, (use while loop):
#include<iostream.h>
main( )
{ double x;
cout << "Enter a positive number: ";
22
cin >> x;
while (x > 0)
{ cout << sqrt(x) << endl;
cout << "Enter another positive number (or 0 to quit) ";
cin >> x;}}
3- do…while loop:
Its form is:
Initial value;
Do
{
Loop statements;
Increment or decrement value;
}
While(continue condition)
Example-10: Write a program to find the sum of five positive numbers (use
do-while loop):
#include<iostream.h>
main( )
{
int i, n, sum=0;
23
i=0;
do
{
cin>>n;
if(n<0) continue;
sum+=n;
i++;
}
while (i<5);
cout<<sum<<endl;
}
H.W
1- Write a program that computes and print the sum 1 + 1/2 + 1/3 + ... + 1/n
for an input integer n. (use for loop).
2- Convert the following for loop into a while loop:
24
Chapter Four: Functions
1- Standard Function:
No. Function Description Header File
1 sin(x) sine of x (in radians) #include<math.h>
2 cos(x) cosine of x (in radians) #include<math.h>
3 tan(x) tangent of x (in radians) #include<math.h>
4 asin(x) inverse sine of x (in radians) #include<math.h>
5 acos(x) inverse cosine of x (in radians) #include<math.h>
6 atan(x) inverse tangent of x (in radians) #include<math.h>
7 log(x) natural logarithm of x (base e) #include<math.h>
8 log10(x) natural logarithm of x (base 10) #include<math.h>
9 exp(x) exponential of x (base e) #include<math.h>
10 fabs(x) absolute value of x #include<math.h>
11 pow(x,p) x to the power p #include<math.h>
12 sqrt(x) square root of x #include<math.h>
13 rand( ) generates random numbers #include<stdlib.h>
14 srand(seed) generates seed #include<stdlib.h>
15 time (NULL) generate seed from the system clock #include<time.h>
16 setw(x) generate s (x) space between outputs #include<iomanip.h>
#include<iostream.h>
#include<math.h>
#include<iomanip.h>
main()
{
for (float x=0; x < 2; x += 0.2)
cout << x << setw(10) << sin(2*x) <<stew(10)<< 2*sin(x)*cos(x) << endl;
}
2- User Functions:
Example-2: Write a program to print the square of input integer (x).
25
(use function called Square).
#include<iostream.h>
int square(int);
main ( )
{
int n=1;
while(n!=0)
{cin>>n;
cout<< square(n);
}
}
int square(int x)
{
return x*x;
}
Example-3: Write a program to print the max of input two integers (use
function called max).
#include<iostream.h>
int max(int,int);
main ( )
{
int n,m;
cin>>n>>m;
cout<< max(n,m);
}
int max(int x,int y)
{
if (x>y)
return x;
else
return y;
}
26
Example-4: Write a program to print the factorial of input integers x (use
function called factorial).
#include<iostream.h>
int factorial (int)
main ( )
{
int x;
cin>>x;
cout<< factorial(x);
}
int factorial (int y)
{int i, fact=1;
if (y<0)
return 0;
else
for(i=y;i>=1;i--)
fact*=i;
return fact;
}
Example-5: Write a program to print the square root of input integer (x)
(use function called SR).
#include<iostream.h>
#include<math.h>
float SR(int)
main ( )
{
int n=1;
while(n!=0)
{cin>>n;
cout<< SR(n);
}
}
float SR(int x)
{
27
return sqrt(x);
}
#include<iostream.h>
void printdate (int, int, int)
main ( )
{int x, y,z;
do
{
cin>>x>>y>>z;
printdate(x,y,z);
}
while (x>0);
}
H.W:
1- Write a program to print the average of four integers (use function called
average)?
2- Write a program to find value of z according to the following equations:
z=x+y when r=1
z=x-y when r=2
z=2x+4y when r=3
(use function called calculations)?
29
Chapter Five: Arrays
#include<iostream.h>
main ( )
{
int B [7]={1,2,3,4,5,6,7};
}
2- Through running program:
#include<iostream.h>
main ( )
{
int B [7],
for(int i=0;i<=6;i++)
cin>>B[i];}
30
1- one dimension arrays:
Example-3: Write a program to input array B (and print the sum of first three
elements?
[ ]
#include<iostream.h>
main ( )
{int sum=0;
int B [7]={1,2,3,4,5,6,7};
for(int i=0;i<=6;i++)
if(i<=2)
Sum+=B[i];
cout<<sum;
}
#include<iostream.h>
main ( )
{
int C [2][3]={1,2,3,4,5,6};
}
2- Through running program:
#include<iostream.h>
main ( )
{
#include<iostream.h>
main ( )
{
int C [2][3],
for(int i=0;i<=1;i++)
for(int j=0;j<=2;j++)
31
{cin>>C[i][j];}}
Example-2: Write a program to input array A and (1-print second row, 2- print
A[1][2])? [ ]
#include<iostream.h>
main ( )
{
int A [3][3]={1,2,3,4,5,6,7,8,9};
for(int j=0;j<=2;j++)
cout<<A[1][j]<<endl;
cout<<A[1][2];
}
Example-3: Write a program to input array A&B and print sum of them?
#include<iostream.h> [ ]
main ( )
{ [ ]
int A [3][3]={1,2,3,4,5,6,7,8,9};
int B [3][3]={1,3,5,7,9,11,13,15,17};
intC[3][3];
for(int i=0;i<=2;i++)
for(int j=0;j<=2;j++)
{C[i][j]=A[i][j]+B[i][j];
cout<<C[i][j];
}
cout<<endl;
}
32
Example-4: Write a program to input array A and print transpose of it?
[ ]
#include<iostream.h>
main ( )
{
int A [3][3]={1,2,3,4,5,6,7,8,9};
int T[3][3];
for(int i=0;i<=2;i++)
for(int j=0;j<=2;j++)
{T[i][j]=A[j][i];
cout<<T[i][j];
}
cout<<endl;
}
Example-5: Write a program to input array A&B and print the multiplication of
first row of A and first column of B?
#include<iostream.h> [ ]
main ( )
{ [ ]
int A [3][3]={1,2,3,4,5,6,7,8,9};
int B [3][3]={1,3,5,7,9,11,13,15,17};
int mult=0;
for(int i=0;i<=2;i++)
mult+= A[0][i]*B[i][0];
cout<<mult;
}
33
Example-6: Write a program to input array A and print the major diagonal?
[ ]
#include<iostream.h>
main ( )
{
int A [3][3]={1,2,3,4,5,6,7,8,9};
for(int i=0;i<=2;i++)
{for(int j=0;j<=2;j++)
{if(i= = j)
cout<<A[i][j];
}
cout<<endl;
}
H.W:
1- Write a program to input array A and print the secondary diagonal?
[ ]
2-Write a program to input array b and print the third row and second column?
[ ]
3-Write a program to input array A and print the square root of its elements?
[ ]
34