Programming Fundamentals PDF
Programming Fundamentals PDF
#include <iostream.h>
main ()
{
cout<<”This is my first program”;
}
Header File
Header file is a C++ source file that contains definition of library function/objects.
Header files are added into the program at the compilation of the program. A header file is added if the
function/object defined in it is to be used in the program.
The preprocessor directive “include” is used to add a header file into the program. The name of the
file is written in angle brackets (<>) after “#include” directive. It can also be written in double quotes.
C++ has a large number of header files in which library functions are defined. The header file must
be included in the program before calling its function in the program. A single header file may contain a
large number of built-in library functions.
For example, the header file iostream.h has definitions of different built-in input and output objects
and functions. It is included in the above program because its object “cout” is used in the program.
The syntax to include a header file is:
#include <name of the header file>
The main() Function
The “main()” function indicates the beginning of a C++ program. The “main()” must
be included in every C++ program. When a C++ program is executed, the control goes directly to the main()
function.
The statements within this function are the main body of the C++ program. If main() function is not
included, the program is not compiled and an error message is generated.
The syntax of the main() function is:
main()
{
Program statements…
}
C++ Statements
The statements of the program are written under the main() function between curly
braces {}. These statements are the body of the program. Each statement in C++ ends with a semicolon (;).
C++ is a case sensitive language. The C++ statements are normally written in lowercase letters but
in some exceptional cases, these can also be written in uppercase.
Keywords
The words that are used by the language for special purposes are keywords. These
are also called reserved words.
For example, in a C++ program, the word main is used to indicate the starting of program, include is
used to add header files, int to declare an integer type variable. All these words are keywords of C++.
The keywords cannot be used as variable names in a program.
Tokens
-nx+nx-1
-27+27-1
-128+128-1
-128+127 range=8 bits
The storage capacity for integer type variable can be changed by applying the qualifiers. There are
three qualifiers that can be applied to int type variables. These are:
1) short int 2) long int 3) unsigned int
The short int
The storage capacity of a short int type variable is two bytes. It can store integer
values from -32768 to 32767.
The long int
The storage capacity of a long int type variable is four bytes. It can store integer
values from -2147483648 to 2147483647.
The unsigned int
The unsigned int can store only positive whole-numbers. Its storage capacity is two
bytes. It can store integer from 0 to 65,535.
The float Data Type
The float represents real or floating type data.
The real type data is represented in decimal or exponential notation. Float type data be signed or
unsigned. For example, 23.26, 16.21, 0.56, -9.87 are example of floating type data.
The storage capacity for float type variable is 4 bytes and it can store real values from 3.4×10-38 to
3.4×10+38.
The long float Data Type
The storage capacity of a long float type variable is twice the storage capacity of
float type variable. Its storage capacity is 8 bytes.
The double Data Type
The double is real or floating type data. Its storage capacity is twice the capacity of
float data type. It is used to store large real values.
The storage capacity for a double type variable is 8 bytes and it can store real values from 1.7×10-308
to 1.7×10+308.
The long double Data Type
The long double type variables are used to store very large real data values. The
storage capacity for long double variables is ten bytes.
A long double variable can store real values from 3.4×10-4932 to 1.1×10+4932.
The char Data Type
The char stands for character. It is used to declare character type variables.
In character type variables, alphabetic character, numeric digits and special characters can be
stored.
The storage capacity for a single character is 8-bit or one byte. A char type variable can hold from 1
byte to 65535 bytes.
Arithmetic operations can also be performed on char type variables.
The bool Data Type
The word bool stand for Boolean. It is used to declare logical type variables.
In a logical type variable, only two values true or false can be stored. The true is equivalent to 1 and
false to 0.
Constants
A quantity that cannot change its value during execution of the program is called
constant.
There are four type of constants in C++.
1. Integer constants
2. floating point constants
3. character constants
4. string constants
Integer Constants
A numerical value without a decimal part is called integer constant.
The plus (+) and minus (-) signs can also be used with an integer constant.
Integer constants are used in expressions for calculations. To print an integer constant, it is given in
the output statement without quotation marks. For example, to print integer constants 520 and 662, the
output statement is written as:
cout<<520;
cout<<662;
Floating-point Constants
Numeric values that have an integer as well as a decimal part are called floating-
point values. These values can also be written in exponential notation.
In exponential notation, a floating-point constant is written as 123.5E2. The symbol E represents
the exponent. A floating-point constant may be a positive or a negative value. The exponent may also be a
+ve or a – ve value.
Character Constants
A single character enclosed in single quotation marks is called character constant.
For example ‘a’, ‘/’, and ‘+’ represent character constants.
String Constants
A sequence of characters consisting of alphabets, digits and/or special characters
enclosed in double quotation marks is called string constant.
For example, “[email protected]” and “Pakistan” are examples of string constant.
Program#01
#include<iostream.h>
#include<conio.h>
main()
{
clrscr();
cout<<”Hello World”;
getch();
return 0;
}
Input Statement
The statement that are used to get data and then to assign it to variable as known as
input statement.
cin stands for console input.
It is pronounced as “see in”
It is used as input statement to get input from the keyword during execution of program.
Cin syntax: cin>>var1, …;
↓
Extraction operator, or get from operator.
Output Statement
The statement that are used to receive data from the computer memory then to
send it to the output devices are called output statements.
cout stands for console output.
It is pronounced as “see out”
It is used as an output statement to output on the computer screen.
Cout syntax: cout<<string/variable;
↓
Insertion operator, or put to operator.
Operator in C++
Operator are special type of functions that takes one or more arguments and produces a new value. For
example: addition (+), subtraction (-), multiplication (×) etc., are all operators. Operators are used to
perform various operations on variables and constants.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<“Please enter a number :”;
cin>>num;
num++;
cout<<“value after increment = ”<<num;
getch();
}
Program#02
Prefix Increment Operator
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int x, i;
i=10;
x=++i;
cout<<“X = ”<<x<<endl;
cout<<“I = ”<<i;
getch();
}
Program Output:
X=11, I=11
Program#03
Post fix Increment Operator
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int x, i;
i=10;
x=i++;
cout<<“X = ”<<x<<endl;
cout<<“I = ”<<i;
getch();
}
Program Output:
X=10, I=11
Program#04
Decrement Operator
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<“Please enter a number :”;
cin>>num;
num--;
cout<<“Value after decrement :”<<num;
getch();
}
Program#05
Prefix Decrement Operator
#include<iostream.h>
#include<conio.h>
Void main()
{
clrscr();
int x, i;
i=10;
x=--i;
cout<<“X = ”<<x<<endl;
cout<<“I = ”<<i;
getch();
}
Program Output:
X=9, I=9
Program#06
Post fix Decrement Operator
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int x, i;
i=10
x=i--;
cout<<“X = ”<<x<<endl;
cout<<“I = ”<<i;
getch();
}
Program Output:
X=10, i=9
Program#07
Both Increment and Decrement Operators
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int a, b, c, x;
a=2;
b=4;
c=5;
x=a--+b++-++c;
cout<<“X = ”<<x;
getch();
}
Program Output:
X=0
getch()
getch() is a nonstandard function and it reads a single character from keyboard. But it does not use any
buffer, so the entered character is immediately returned without waiting for the enter key.
Syntax:
// Example for getch() in C++
#include<iostream.h>
#include<conio.h>
void main()
{
char ch;
ch=getch();
cout<<ch;
}
getche();
Like getch(), this is also a non-standard function present in conio.h. It also reads a single character from the
keyboard and display an output screen without enter for input key.
Syntax:
// Example for getche() in C++
#include<iostream.h>
#include<conio.h>
void main()
{
char ch;
ch=getche();
cout<<ch;
}
Program09 Write a program which checks whether two numbers are equal or not using two if statements.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num1, num2;
cout<<“enter first number :”;
cin>>num1;
cout<<“enter second number :”;
cin>>num2;
if(num1==num2)
cout<<“both numbers are equal”;
if(num1!=num2)
cout<<“both numbers are not equal”;
getch();
}
Program#10 Write a program which checks whether a number is even or odd using two if statements.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<“Enter a number :”;
cin>>num;
if (num%2==0)
cout<<“even number”;
if(num%2==1)
cout<<“odd number”;
getch();
}
Program#11 Write a program using three if statements which checks whether num1 is maximum or num2
is maximum or both values are equal.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num1, num2;
cout<<“enter first number :”;
cin>>num1;
cout<<“enter second number :”;
cin>>num2;
if(num1>num2)
cout<<“num1 is maximum”;
if(num2>num1)
cout<<“num2 is maximum”;
if(num1==num2)
cout<<“both values are equal”;
getch();
}
Program#12 Write a program which checks whether a number is even or odd using if else statement.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<“enter a number :”;
cin>>num;
if(num%2==0)
cout<<“even number”;
else
cout<<“odd number”;
getch();
}
Program#13 Write a program which checks whether a number is divisible by 5 or not using if else
statement.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<“enter a number :”;
cin>>num;
if(num%5==0)
cout<<“divisible by 5”;
else
cout<<“not divisible by 5”;
getch();
}
Program#14 Write a program using nested if statement which checks whether three numbers are equal or
not.
#include<iostream.h>
#include<conio.h>
void main();
{
clrscr();
int num1, num2, num3;
cout<<“enter first number :”;
cin>>num1;
cout<<“enter second number :”;
cin>>num2;
cout<<“enter third number :”;
cin>>num3;
if(num1==num2)
{
if(num1==num3)
cout<<“All values are equal”;
else
cout<<“All values are not equal”;
}
else
cout<<“All values are not equal”;
getch();
}
Program#15 Write a program using nested if else statement which checks whether num1 is maximum,
num2 is maximum or both numbers are equal.
#include<iostream.h>
#include<conio.h>
void main();
{
clrscr();
int num1, num2;
cout<<“enter first number :”;
cin>>num1;
cout<<“enter second number :”;
cin>>num2;
if(num1>num2)
cout<<“num1 is maximum”;
else if(num2>num1)
cout<<“num2 is maximum”;
else
cout<<“both numbers are equal”;
getch();
}
Program#16 Write a program using nested if else statement which takes marks of the student as input and
then calculates and display grade of a student.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int marks;
cout<<“enter marks :”;
cin>>marks;
if(marks>=90 && marks<=100)
cout<<“A+ Grade”;
else if(marks>=80 && marks<=89)
cout<<“A Grade”;
else if(marks>=70 && marks<=79)
cout<<“B+ Grade”;
else if(marks>=65 && marks<=69)
cout<<“B Grade”;
else if(marks>=56 && marks<=64)
cout<<“C+ Grade”;
else if(marks>=50 && marks<=55)
cout<<“C Grade”;
else if(marks>=0 && marks<=49)
cout<<“F Grade”;
else
cout<<“Invalid Marks”;
getch();
}
Program#17 Write a program using nested if else statement which takes an operator(+,-,*,/,%) as input
from user and then calculates and display the result of required arithmetic operation.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num1, num2;
char op;
cout<<“enter num1 :”;
cin>>num1;
cout<<“enter num2 :”;
cin>>num2;
cout<<“enter operator +,-,*,/,% :”;
cin>>op;
if(op==‘+’)
cout<<“sum = ”<<(num1+num2);
else if(op==‘-’)
cout<<“subtraction = ”<<(num1-num2);
else if(op==‘*’)
cout<<“multiplication = ”<<(num1*num2);
else if(op==‘/’)
cout<<“division = ”<<(num1/num2);
else if(op==‘%’)
cout<<“remainder = ”<<(num1%num2);
else
cout<<“Invalid Operator”;
getch();
}
Program#18 Write a program to calculate the electricity bill. The rates of electricity bill per unit are as
follow:
1. If the units consumed are equal or less than 300, then the cost is Rs. 3/- per unit.
2. If units consumed are more than 300, then the cost is Rs. 3.5/- per units and a surcharge of 5% of
bill is added.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
float cu, pr, units, bill;
cout<<"Enter Your Current reading : ";
cin>>cu;
cout<<"Enter Your Previous reading : ";
cin>>pr;
units=cu-pr;
if(units<=300)
{
bill=units*3;
cout<<“Electricity bill ="<<bill<<endl;
}
if(units>300)
{
bill=units*3.5+units*5/100;
cout <<“Electricity bill ="<< bill<<endl;
}
getch();
}
The “switch” Statement The “switch statement” is used as a substitute of “nested if-else” statements. It is
used when multiple choices are given and one choice is to be selected.
The “nested if-else” structure becomes complicated in multiple choices. The “switch statement” is used in
such situations. Only one condition is given in the “switch statement” and multiple choices are given inside
the main body as cases.
The “switch statement” evaluates an expression and returns a value. One of the choices or cases in the
“switch statement” is executed depending upon the value returned by the expression. The returned value
is compared with the constant values given in the cases. If the returned value matches the case value, the
statement under that case are executed.
The syntax of switch is:
switch (expression)
{
case const-1:
statements;
case const-2:
statements;
case const-n:
statements;
default:
statements;
}
The const-1, const-2, etc. are numeric constants or character constants.
Program#19 Write a program using switch statement which takes an operator (+,-,*,/,%) as input form
user and then calculates and display the result of required arithmetic operation.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num1, num2;
char op;
cout<<“enter num1 :”;
cin>>num1;
cout<<“enter num2 :”;
cin>>num2;
cout<<“enter operator +,-,*,/,% :”;
cin>>op;
switch(op)
{
case ‘+’:
cout<<“sum = ”<<(num1+num2);
break;
case ‘-’:
cout<<“subtraction = ”<<(num1-num2);
break;
case ‘*’:
cout<<“multiplication = ”<<(num1*num2);
break;
case ‘/’:
cout<<“division = ”<<(num1/num2);
break;
case ‘%’:
cout<<“remainder = ”<<(num1%num2);
break;
default:
cout<<“Invalid Operator”;
}
getch();
}
Program#20 Write a program using switch statement which takes a number from user as input and then
calculates and display whether a number is even or odd.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<“enter any number :”;
cin>>num;
switch(num%2)
{
case 0:
cout<<“even number”;
case 1:
cout<<“odd number”;
}
getch();
}
The Conditional Operator The conditional operator is used as an alternative of a simple if-else statement.
The conditional operator consists of “?” (question mark) and a “:” (colon). Its syntax is:
(condition)?{exp1}:{exp2}
Where
Condition represents the test condition. If this condition is true then the value of “exp1” is
returned after evaluation. Otherwise the value “exp2” is returned.
exp1 & exp2 represents the two expressions. It may be arithmetic expressions or constant
values. Input/output statements can be used.
For example, if a=10 and b=5 and res is an integer type variable then an assignment statement is written
as:
res=(a>b)?a:b
The above statement is equivalent to:
if(a>b)
res=a;
else
res=b;
Program#21 Write a program using conditional operator which checks whether a number is even or odd.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
cout<<“ enter a number :”;
cin>>num;
cout<<((num%2==0)?“Even number”:“Odd number”);
getch();
}
Program#22 Write a program to enter two values as input and then finds the maximum value among them
using conditional operator.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num1, num2, max;
cout<<“enter num1 :”;
cin>>num1;
cout<<“enter num2 :”;
cin>>num2;
max=(num1>num2)?num1:num2;
cout<<“Maximum value is ”<<max;
getch();
}
Manipulators
These are formatting instruction inserted into a stream. The manipulators are operators used in C++ for
formatting output. The data is manipulated by the programmer’s choice of display. Some of the more
commonly used manipulators are provided here below.
endl manipulator
It is used to insert new line, endl is the line feed operator in C++. We can use \n (is an escape sequence)
instead of endl for the same purpose.
Setw manipulator
This manipulators sets the minimum field width on output. The syntax is setw(x). E.g.,
Example
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
Float basic, ta, da, gs;
Basic=10000; ta=800; da=5000;
gs=basic+ta+da;
cout<<setw(10)<<“Basic”<<setw(10)<<basic<<endl
<<setw(10)<<“TA”<<setw(10)<<ta<<endl
<<setw(10)<<“DA”<<setw(10)<<da<<endl
<<setw(10)<<“GS”<<setw(10)<<gs<<endl;
return 0;
}
Program Output
Basic 10000
TA 800
DA 5000
GS 15800
Press any key to continue…
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a scope, all
automatic objects that were created in that scope are destroyed.
C++ Supports the following control statements.
Break Statement
The break statement has the following two usages in C++:
• When the break statement is encountered inside a loop, the loop is immediately terminated and
program control resumes at the next statement following the loop.
• It can be used to terminate a case in the switch statement (covered in the next chapter).
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the
execution of the increment loop and start executing the line of code after the block.
Syntax
The syntax of a break statement in C++ is:
break;
Example
#include<iostream>
using namespace std;
int main() {
//Local variable declaration:
int a=10;
//do loop execution
do {
cout<<“value of a : ”<<a<<endl;
a=a+1;
if(a>15) {
//terminate the loop
break;
}
}while(a<20);
return 0;
}
When the above program is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
Continue Statement
The continue statement works somewhat like the break statement. Instead of forcing termination,
however, continue forces the next iteration of the loop to take place, skipping any in between.
For the for loop, continue causes the conditional test and increment portions of the loop to execute. For
the while and do…while loops, program control passes to the conditional tests.
Syntax
continue;
Example
#include<iostream>
using namespace std;
int main() {
//Local variable declaration:
int a =10;
//do loop execution
do {
if(a==15) {
//skip the iteration.
a=a+1;
continue;
}
cout<<“value of a: ”<<a<<endl;
a=a+1;
}while(a<20);
return 0;
}
When the above program is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
goto statement
A goto statement provides an unconditional jump from the goto to a labeled statement in the same
function.
Note: Use of goto statement is highly discouraged because it makes difficult to trace the control flow of a
program, making the program hard to understand and hard to modify. Any program that uses a goto can
be rewritten so that it doesn’t need the goto.
Syntax
The syntax of a goto statement in C++ is:
goto label;
label: statement
Where label is an identifier that identifies a labeled statement. A labeled statement is any statement that is
preceded by an identifier followed by a colon(:).
One good use for the goto is to exit from a deeply nested routine. For example, consider the following
code fragment:
for(…) {
for(…) {
while(…) {
if(…) goto stop;
.
.
.
}
}
}
stop:
cout<<“Error in program.\n”;
Eliminating the goto would force a number of additional tests to be performed. A simple break statement
would not work here, because it would only cause the program to exit from the innermost loop.
Program#23 Write any program which uses goto and if statement.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num=1;
abc:
cout<<num<<endl;
num++;
if(num<=10)
goto abc;
getch();
}
LOOPS
A statement or set of statements that is executed repeatedly is called loop. The statement(s) in a loop are
executed for a specified number of times or until some given condition remains true.
In C++, there are three kinds of loop statements. These are:
• The “for” loop
• The “while” loop
• The “do-while” loop
The “for” Loop
The “for loop” statement is used to execute a set of statements repeatedly for a fixed number of times. It is
also known as counter loop.
The structure of this loop is different from both the “while” and the “do-while” loops. It has the following
parts:
i. Initialization
ii. Condition
iii. Increment or decrement
iv. Body of the loop
The general syntax of the “for” loop is:
for (initialization; condition; increment/decrement)
Program#24 Write a program using for loop which displays integer number from 1 to 10.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
for(int i=1; i<=10; i++)
cout<<i<<endl;
getch();
}
Program#25 Write a program using for loop which displays integer numbers from 1 to 10 in descending
order.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
for(int i=10; i>=1; i--)
cout<<i<<endl;
getch();
}
Program#26 Write a program using for loop which displays integer numbers from 1 to 10 in both ascending
and descending order.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
for(int i=1, j=10; i<=10; i++, j--)
cout<<i<<“\t\t”<<j<<endl;
getch();
}
Program#27 Write a program using for loop which displays the sum of even numbers from 1 to 20.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int sum=0;
for(int i=2; i<=20; i=i+2)
{
sum=sum + i;
}
cout<<“Sum of even numbers from 1 to 20 is “<<sum;
getch();
}
Program#28 Write a program using for loop which displays the sum of odd numbers from 1 to 20.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int sum=0;
for(int i=1; i<=20; i=i+2)
{
sum=sum + i;
}
cout<<“Sum of odd numbers from 1 to 20 is “<<sum;
getch();
}
While Loop
It is a conditional loop statement, it is used to execute a statement or a set statements as long as the given
condition remains true.
Syntax:
While loop for one statement.
while(condition)
statement;
Syntax:
While loop for more than one statement.
While(condition)
{
Statement-1;
Statement-m;
}
Program#29
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i=1;
while(i<=10)
{
cout<<i<<endl;
i++;
}
getch();
}
The “do-while” Loop
The “do-while” loop is also a conditional loop statement. It is like a while loop but in this loop the condition
is tested after executing the statement of the loop.
The syntax of the “do-while” is:
do
{
Statements;
}
while(condition);
Program#30
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int i=1;
do
{
cout<<i<<endl;
i++;
}
while(i<=10);
getch();
}
***Best-of-Luck***