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

Programming Fundamentals PDF

This document provides an overview of programming fundamentals in C++, including: 1) The structure of C++ programs consists of preprocessor directives, the main() function, and C++ statements. Preprocessor directives provide instructions to the compiler. 2) Header files contain library function definitions and are included via preprocessor directives. The main() function indicates the start of the program. C++ statements are written within main() and end with semicolons. 3) C++ has several basic data types - int for integers, float and double for floating point numbers, char for characters, and bool for Boolean values. Variables are declared with a data type and used to store and manipulate data.

Uploaded by

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

Programming Fundamentals PDF

This document provides an overview of programming fundamentals in C++, including: 1) The structure of C++ programs consists of preprocessor directives, the main() function, and C++ statements. Preprocessor directives provide instructions to the compiler. 2) Header files contain library function definitions and are included via preprocessor directives. The main() function indicates the start of the program. C++ statements are written within main() and end with semicolons. 3) C++ has several basic data types - int for integers, float and double for floating point numbers, char for characters, and bool for Boolean values. Variables are declared with a data type and used to store and manipulate data.

Uploaded by

Ahmad Ali
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Week#1 Programming Fundamentals

Structure Of C++ Programs


A C++ consists of three main parts. These are:
Preprocessor directives
The main function
C++ Statements
Preprocessor Directives
The instruction that are given to the compiler before the beginning of the actual
program are called preprocessor directives. These are also known as compiler directives. The preprocessor
directives consist of instructions for the compiler. The compiler adds special instructions or code from
these directives into the program at the time of compilation.
These preprocessors directives normally start with a number sign (#) and the keyword “include” or
“define”. For example, preprocessor directives are used to include header files in the program.
A program example is given below. The first statement of the program is a preprocessor directive.
This preprocessor directive has been written to include the iostream.h header file.

#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

A program statement consists of variable names, keywords, constants, punctuation


marks, operators, etc. In C++, these elements of a statement are called tokens.
In the following program segment:
main ( )
{
int a, b;
}
Main {, }, int a, b and punctuation marks ( ,) and (;) are tokens of the program.
Variables
A quantity whose value may change during execution of the program is called
variable. It is represented by a symbol or a name.
A variable represents a storage or memory location in the computer memory. Data is stored into
the memory location. The name of the memory location i.e. the variable name, remains fixed during
execution of the program but the data stored in that location may change from time to time.
A variable is also known as object in C++. In C++, a variable name consist of alphabets and digits.
Rules for Writing Variable Names
The following are the rules for writing a variable name in a program in C++.
1) Variable name consists of letter, digits or underscores.
2) First character must be an alphabets and underscores.
3) Starting letter cannot be a digits.
4) Blanks spaces are not allowed.
5) Special character are not allowed.
6) C++ keyword cannot be used as variable name.
7) A variable name can be declared for only one data type.
8) C++ is case sensitive language therefore capital letters are different from small letters.
9) Length of variable name can be upto 31 characters.
10) Name should be readable.
Variable Declaration
Statements which describes the data type and name of the variable is called variable
declaration.
Example
int age;
char grade;
Multiple Variable Declaration
Multiple variable can also be declared in a single statement.
Example
int S1, S2, S3 etc.
Variable Initialization
Assign a value to a variable for the very first time is called called initialization.
Example
int marks;
marks=80;
Multiple Variable Initialization
Multiple variable can also be initialized in statement.
Example
Int a, b, c;
a=50;
b=60;
c=70;
Week#2

Data Type In C++


The variable type specifies the type of data that can be stored in it. Variable is
declared by its type.
5 Basic Data Type
1. int → integer (2 bytes)
2. float → floating point (4 bytes)
3. double → double decision (4 bytes)
4. char → characters (1 byte)
5. bool → Boolean
The int Data Type
The int represents the integer data. It is used to declare integer type variables.
An integer is a whole number, i.e. a number without a fraction or a decimal point.
For example, 601, 250, -6 and 501 are integers.
The range of values that can be stored in int data type variables depends upon the computer
system being used. In MS DOS, an integer type variable takes two bytes in the memory and the range of
values stored is form -32768 to 32767.

Integer (int=2 bytes) 1 byte=8 bits


-nx+nx-1
-215+215-1
-32768+32768-1
32768+32767 range=2 bytes
Range for bits.

-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.

Assignment Operator (=)


Operates‘=’ is used for assignment, it takes the right-hand side (called R-value) and
copy it into the left-hand side (called L-value).
Assignment operator is the only operator which can be overloaded but cannot be inherited.
Logical Operators
The logical operators are AND (&&) and OR (||). They are used to combine two
different expressions together.
If two statement are connected using AND operator, the validity of both statements will be considered, but
if they are connected using OR operator, then either one of them must be valid. These operators are
mostly used in loops (especially while loop) and in decision making.
Arithmetic Operators
These are operators used to perform basic arithmetical operations. Addition (+),
subtraction (-), diversion (/), multiplication (*) and modulus/remainder (%) are basic arithmetic operators.
Modulus/remainder operator cannot be used with floating-point numbers.
C++ and C also use a shorthand notation to perform an operation and assignment at same type. Example,
int x=10;
x +=4 //will add 4 to 10, and hence assign 14 to x.
x –=5 //will subtract 5 from 10 and assign 5 to x.
Relational Operators
These operators establish a relationship between operands. The relational operators
are: less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=), equivalent (==)
and not equivalent (!=).
You must notice that assignment operator is (=) and there is a relational operator, for equivalent (==).
These two are different from each other, the assignment operator assigns the value to any variable,
whereas equivalent operator is used to compare values, like in if-else conditions.
Example,
int x=10; //assignment operator
x=5; //again assignment operator
if(x==5) //here we have used equivalent relational operator, for comparison
{
cout<<“Successfully compared”;
}
Comma Operator
This is used to separate variable names and to separate expressions. In case of
expressions, the value of last expression is produced and used.
Example,
Int a, b, c; //variable declaration using comma operator
a=b++, c++; //a=c++ will be done.
Shift Operators
Shift operators are used to shift bits of any variable.
For example,
 Left shift operator <<
 Right shift operator >>
 Unsigned left shift operator <<<
 Unsigned right shift operator >>>
Unary Operators
These are the operator which work on only one operand. There are many unary
operators, but increment “++” and decrement “– –” operators are most used.
Other Unary Operators:
Address of &, dereference *, new and delete, bitwise not ~, logical not !, unary minus – and unary plus +.
Ternary Operators
The ternary if-else ? : is an operator which has three operands.
Int a=10;
a>5? Cout<<“true” : cout<<“false”
Bitwise Operators
There are used to change individual bits into a number. They work with only integral
data types like char, int and long and not with floating point values.
 Bitwise AND operators &
 Bitwise OR operator |
 And bitwise XOR ^
 And, bitwise NOT operator ~
They can be used as shorthand notation too, &=, |=, ^=, ~= etc.
After Mid
Escape Sequences
1) \a → stands for alert alarm.
2) \b → stands for backspace.
3) \t → stands for tab.
4) \n → stands for newline.
5) \f → stands for form feed.
6) \r → stands for carriage return.
7) \\ → these are double backslash characters. One is used for control and second is used
to print backslash “\” character.
Increment (++)
Increasing the value of integer variable by one is called increment operator.
Prefixing Increment
Add before the value of integer variable by one is called prefixing increment operator.
e.g. ++variable name; as, ++a, ++b … ++z.

Post Fixing Increment


Add after the value of integer variable by one is called post fixing increment operator.
e.g. Variable name++; as, a++, b++ … z++.
Decrement (--)
Decreasing the value of integer variable by one is called decrement operator.
Prefixing Decrement
Subtract before the value of integer variable by one is called prefixing decrement operator.
e.g. --variable name; as, --a, --b … --z.
Post Fixing Decrement
Subtract after the value of integer variable by one is called post fixing decrement operator.
e.g. Variable name--; as, a--, b-- … z--.
Rule: Expression>Prefixing>Assign>Post fixing.
Program#01
Increment Operator

#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;
}

The “If” Statement


The “if statement” is used to execute (or ignore) a set of statements after testing a condition.
The “if statement” evaluates a condition. If the given is true, the statement (or a set of statements)
following the “if statement” is executed. If the given condition is false, the statement (or a set of
statements) following the “if statement” condition is ignored and the control transfer to the next
statement.
The syntax of the “if statement” is:
if (condition)
Statement-1;
Statement-2;
Condition: specifies a condition or a relational expression.
The “if-else” Statement
This is another form of the “if statement”. It is used for making two way decisions. In this statement, one
condition and two blocks of the statement are given. Either one of the two blocks of statement is executed
after evaluating a condition.
The “if-else” statement tests the given relational condition. If the condition is true then the first block of
statements is executed. If the condition is false, the block of statement is ignored and the second block
following the else is executed.
The syntax of “if-else” statement is:
Syntax-1
if (condition)
statement-1;
else
statement-2;

The “nested if” Statement


When an “if statement” is used within another “if statement”, it is called the “nested if statement”. The
“nested if statement” is used for multi-way decision making.

The “nested if-else” Structure


When an “if-else” structure is placed in another “if-else” structure, it is called “nested if-else” structure. It
is used for multiple-selection.
Its general syntax is:
Program#08 Write a program which checks whether two numbers are equal using single if statement.
#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”;
getch();
}

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***

You might also like