You are on page 1of 40

C/C++ Programming

What is Programming?
"A program is a precise sequence of steps to solve a particular problem.”

OR

The process of developing and implementing various sets of instructions to enable a


computer to do a certain task.

These instructions are considered computer programs and help the computer to operate
smoothly.

Programming Language:
As we know that language is a way of communication so with the help of computer
programming language we can communicate with the computer to solve our problem.

What is C/C++:
C/C++ is one of the most powerful, flexible, efficient, modular, general purpose high level
programming language.

It is a versatile language. You can use C/C++ for almost any programming task. It is effective
to develop high level application programs in various fields, such as engineering, business,
science, education, statistics, accounting, database management etc.

C/C++ has become a favorite programming language of professional computer


programmers for writing applications including word processing, spreadsheets, games and
graphics programs and for many such applications.

History of C/C++:
The C language was developed in late 60’s and early 70’s, in Bell Laboratories. In those days
BCPL(Basic Combined Programming Language) and B languages were developed there. The
BCPL language was developed in 1967 by Martin Richards as a language for writing
operating systems software and compilers. In 1970 Ken Thompson used B language to
create early versions of UNIX operating system.

C was developed by Dennis Ritchie in 1970 at Bell Laboratories while C++ was developed by
Bjarne Stroustrup in early 1980s at Bell Laboratories.

Prepared by:Usama Musharaf For DIT Students Page 1


It is a totally different language from the earlier C but it inherits its syntax from C language.
It supports the concept of object oriented approach that makes it different form C
language.

Its purpose was to make the programming process easier and pleasant for the individual
programmer.

Advantages of C/C++ Language:


C/C++ is an all purpose programming language. It is equally suitable for solving scientific
and engineering problems as well as for business applications.

From operating system to games anything can be developed in C/C++ language.

Difference B/w C & C++.


C is a procedural language C++ is an object oriented language
C uses the top down approach in C++ uses the bottom up approach in
program design program design
C require all the variables to be defined C++ allows the declaration of variables
at the starting of scope anywhere in the scope.
Multiple declaration of global variables Multiple declaration of global variables
are allowed are not allowed
Exception and inheritance is not Exception and inheritance is possible in
possible in C language C++
C doesn’t support operators and C++ supports operators & functions
functions overloading overloading.
Polymorphism cannot be achieved in C Polymorphism is the most important
language feature of C++

Two Basic Types of Computer Language;


Low-Level Languages.

High Level Languages.

Prepared by:Usama Musharaf For DIT Students Page 2


Low Level Language / Machine Language:

Low-level computer language is machine code. A computer cannot understand instructions


given to it in high-level languages. It can only understand and execute instructions given in
the form of machine language i.e. in binary form. This language consists of 0’s and 1’s, each
instruction or data in its language is written in the combination of 0’s and 1’s.

High Level Language:

High-level computer languages use formats that are similar to English. The purpose of
developing high-level languages was to enable people to write programs easily, in their own
native language environment (English).

High-level languages are basically symbolic languages that use English words and/or
mathematical symbols rather than codes. Each instruction in the high-level language is
translated into many machine language instructions that the computer can understand.

Assembly Language:

Assembly language was advance than machine language. This language some symbolic
codes were used instead of 0’s and 1’s. it was easy to use and understand as compare to
machine language.

These alphanumeric symbols are known as mnemonic codes and can combine in a
maximum of five-letter combinations e.g. ADD for addition, SUB for subtraction, START,
LABEL etc. Because of this feature, assembly language is also known as ‘Symbolic
Programming Language.

Translation Software:
It is application software that is used to convert source code into object code and vice
versa.

A program written in non-machine language and that is understandable by human is called


source code.
The code that a machine understands is called object code.

Types of Translation Software:


Assembler
Interpreter
Compiler

Prepared by:Usama Musharaf For DIT Students Page 3


Assembler:

It is translation software that is used to translate a program written in Assembly language


into object code and vice versa.

Source code Object code


Assembly
Assembler 0’s & 1’s
Language

Interpreter:

It is translation software that is used to convert a program written in high level language
into the machine language and vice versa. It takes our program as input and translates it
line by line into object code.

Source code Object code


High-Level
Interpreter 0’s & 1’s
Language

Compiler:

It is translation software that is used to convert a program written in high level language
into the machine language and vice versa. It takes our entire program as input and
translates the whole program into object code.

Source code Object code


High-Level
Compiler 0’s & 1’s
Language

Prepared by:Usama Musharaf For DIT Students Page 4


Basic Elements of C/C++:
Writing a computer program is like building a house. To construct a house, certain
fundamental construction materials are required and one must know how to use these
materials.

In the same way, C/C++ program is constructed from some material that is discussed below.

C/C++ Character set:


Numeric Character Set:

Numeric characters are 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9.

Alphabetic Character Set:

Alphabetic characters are upper and lower case letter of the English language (A, B, C
……….Z, a, b, c ………….z).

Special Character Set:

The special character is period (.). comma, Semicolon(;), Single & double quotes (‘&”). Plus
& Minus sign (+& -). Asterisk (*), Slash (/), Equal Sign (=), Parentheses (), Percent (%), Less
and Greater Sign (< >), Hash or number sign (#), Ampersand (&), Question Mark (?),
Opening and closing braces ({ }), and other special character including the blank character
which is equivalent to a space on the keyboard.

Whitespace Character Set:

Any character or series of characters that produce horizontal or vertical space is called
whitespace character. Whitespace characters include spacebar, tab (\t), Enter, newline (\n).
C/C++ RESERVED WORD:

Words that have pre-defined meanings in C Language are called reserve words. They
cannot be re-defined by the user inside his program. They must be spelled correctly and
entered in lowercase. Example of reserve words are int, long, float, char, if, else, do, while,
switch, for etc.

USER DEFINED WORDS (Identifiers)

Words that are defined or provided by the user inside his program are called user defined
words or identifiers.
During programming programmer needs to store some data to perform some operation on
it so some name must be associated with that data to access it when it is needed.

Prepared by:Usama Musharaf For DIT Students Page 5


NAMING RULES USER DEFINED WORDS (identifiers):
Identifier name must be comprised of digits (0 – 9), alphabets (A – Z or a – z) and only
special character underscore ( _ ).

User defined words must be unique in the program.

Both upper and lowercase letters are allowed in identifier names, but case sensitivity
should be taken care of their. For example TaX, tax. taX, TAX are four different identifiers.

The first character of identifier name must be an alphabet or underscore. After alphabet or
underscore you can use numbers and additional alphabets, underscore as well.

If identifier name consist of one character, then it must be an alphabet.

No space is allowed in an identifier name.

Reserve words cannot be used as an identifier names.

It is recommended to have meaningful identifier names inside a program.

Identifier names may be of any length.

WHAT ARE VARIABLES?


A value, which may vary during program execution, is called a variable. Each variable has a
specific storage location in memory where its value is stored, or in simple words we can say
that a variable is name used to represent a piece of information that a programmer needs
to access. You may think of a variable as a name of a box in memory. The box can hold any
value that can fit in the variable. For example

Z = 5; Z = 5

The above example, Z is a variable, which hold a value 5. It is important to note that the
value of a variable may change from time to time during the execution of program, but the
name remains the same.

If we say

Z = Z + 5;

So the value of Z becomes 10.

Prepared by:Usama Musharaf For DIT Students Page 6


NAMING VARIABLES:

Each variable has a name, a type and a value that you assign to it. A variable name must be
unique in a program.

All identifier’s rules must be observed in naming variable.

Variable name should be meaningful that imparts some meaning. Meaningful variable’s
names tell you what those variables are for and make it easier to understand the flow of
your program.

DATA TYPES:

Data type actually tells the compiler about the type of the data that you are going to store
into memory location.

Based on the data type of a variable, the operating system allocates memory and decides
what can be stored in the reserved memory.

The following table shows a list of variable types and range that each variable might hold.

Declaration Name Type Size Range


char Character 1 byte -128 to 127
unsigned char Unsigned character 1 byte 0 to 255
int Integer 2 bytes -32768 to 32767
unsinged int Unsigned integer 2 bytes 0 to 65.535
signed int Signed integer (same as int) 2 bytes -32768 to 32767
short int Short integer 2 bytes -32768 to 32767
unsigned short int Unsigned short integer 2 bytes 0 to 65,535
signed short int Signed short integer 2 bytes -32768 to 32767
long int Long integer 4 bytes -2,147,483,648 to 2,147,483,647

singed long int Signed long integer 4 bytes -2,147,483,648 to 2,147,483,647

unsigned long int Unsigned long integer 4 bytes 0 to 4294967295


float Floating point 4 bytes -1.7E+38 to 3.4E+38
double Double floating point 8 bytes -1.7E+308 to 1.7E+308
long double Long double floating point 10 bytes -1.7E+4932 to 1.7E4932

It is important to note that the size and ranges are not fixed; as it varies from machine to
machine.

Prepared by:Usama Musharaf For DIT Students Page 7


CONSTANTS:
Constant is an identifier whose value remains fixed during the program execution.
E.g. PI = 3.14, INTEREST_RATE = 8.5 etc.
There are two main types of constants in C/C++.

1. NUMERIC CONSTANT
Numeric values that remain fix during the program execution, are called Numeric constant.
These values consist of digits (0 to 9), plus (+) or minus (-) sign and decimal point (.).
Numeric constants are further divided into three sub types.

a) Integer constants: This type of constants consist of only digits (0 to 9) and sign (+ or -
). These constants represent whole values. Example; 15, 576, +420, -750 etc.

b) Floating Point Constants: Floating point constants consist of digits (0 – 9), sing (+ or -)
and decimal point(.). These constants represent fractional values. Examples; 5.7,
25.5, +235.45, -67.3, 0.123 etc.

c) Exponential Real Constants: If floating point constants are represented in the form of
exponential notations, then called as Exponential real constants. These type of
constants are used to represent very large or small numbers. Example; 5.234E+6,
8.0E+9, 9.5E-10 etc.

2. NON-NUMERIC CONSTANTS:
Constants that are not numeric are called No-numeric constants. This type of constants
is divided into two types.

a) Character Constants: A single character constant is called character constant. This type
of constant is enclosed in a single quote. Example; ‘n’, ‘#’, ‘5’, ‘=’, ‘y’ etc.

b) String Constant: A sequence of characters enclosed in double quote is known as String


Constant. Example; “Welcome”, “23456”, “Phone#1234567” etc.

Prepared by:Usama Musharaf For DIT Students Page 8


DIFFERENT BETWEEN VARIABLES & CONSTANTS:

A Variable is the name of identifier whose value changes during the program execution
while constant is an identifier whose value remains fixed during the program execution.
A constant is must initialized when it is declared while variable is not required to be
initialized during its declaration.
Variable syntax is
data-type variable-name = value;
E.g int number = 50;

Constant syntax is
const data-type constant-name = value;
E.g const float pi = 3.14159;

Operators that C/C++ supports:


Arithmetic Operators:
Operators that are used to perform arithmetical calculations like addition, subtraction,
multiplication, division etc., are called arithmetic operators. C/C++ supports the following
types of arithmetic operators. +, -, *, /, %.

Example:

Operators Purpose Example Result

+ Performs addition X=2, Y=7 9


X+Y

- Performs X=11, Y=5 6


subtraction X-Y

Performs X=12, Y=6 72


* multiplication X*Y

X=12, y=6 x/y


/ Performs division 2

Gives remainder X=13, Y=5


% after division X%Y 3

Prepared by:Usama Musharaf For DIT Students Page 9


Relational Operators that C/C++ supports:
Relational Operators:

Operators that are used to compare two variables or values, are called relational operators.
They form relational expressions whose result can be either true or false. C/C++ support the
following types of relational operators. >, <, >=, <=, ==, !=

Operator Purpose Example Result


> Compares to check whether the left X=2, Y=3 False
value is greater X>Y
< Compare to check whether the left X=2, Y=3 True
value is smaller X<Y
>= Compare two values to check X=2, Y=3 False
whether the left value is greater or X>=Y
equal to the right one
<= Compares two values to check X=2, Y=3 True
whether the left value is smaller or X< =Y
equal to the right one.
== Compares two values for equalities. X=2, y=3 True
X==Y
!= Compares for the non-equality of X=2, Y=3 False
two given values X!=Y

Logical operator that support C/C++:

Logical Operator:

Operators that are used to combine two or more relational expressions are called logical
operators. The result of these operators will either be true or false. C/C++ supports the
following types of logical operators.

Operator Purpose Example Result


&& (AND If all the operands have true values, X=2, Y=5
operator) then its outcome will be true, if (X>2 && False
otherwise false Y==5)
l l (OR If one of this operands has true value X=2, y=5
operator) then it provides the true result, if (X>2 I I True
otherwise false y==5)
! (NOT This operator applies to the single X=2,
operator) operand. If the operand value is true, !(X>2) True
the result will be false and vice versa

Prepared by:Usama Musharaf For DIT Students Page 10


Unary Operators:

Unary Operator is an operator that operates on single operand to produce a new value.
C/C++ supports two unary operators i.e.

Increment operator (++) and Decrement operator (- -).

The increment operator causes its operand to be increased by 1, while decrement operator
causes its operand to be decreased by 1. Both the operators may be used with the single
variable as a prefix or postfix.

Operator Example Result

++ i=1 i ++ 2

-- i=2 i- - 1

Assignment & Compound Assignment Operators:


Assignment operator (=) is used to assign a value to an identifier, while operators that are
formed by the combination of arithmetic operators and assignment operator are called
compound assignment operators they are used to assign the value of a constant, variable or
expression to an identifier.
C/C++ supports the following types of compound assignment operators.
+ =, - =, * =, / =, % =

Operator Purpose Example Result


+= Increment the value of the variable by the i=2 i+=3 5
given value or i= i+3
-= Decrement the value of the variable by the i=10 i-=5 5
given value or i= i-5
*= Multiply the value of the variable by the given i=5 i*=5 25
value or i = i*5
/= Divides the value of the variable by the given i=25 i/=5 5
value i=i/5
%= Divides the value of the variable by the given i=25 i%=6 1
value and assign the resulting remainder to or i= i% 6
the same variable

Prepared by:Usama Musharaf For DIT Students Page 11


Expression:
If we combine constants and variables with the help of C/C++ valid operators, then called as
expression. An expression in a C/C++ statement is required to evaluate to produce some
result.

Example of Expressions is;

c=a +b; z=y=10; r=p/q; ++j; m<=n;

Difference between Statement and Expression:


An expression is the combination of operands and operators that are require evaluating to
produce some result,

while

Statement is an instruction for a computer to cause some action. All expressions may be
valid C/C++ statements, while all statements are not expression. For example got top; or
continue; if , else, switch, is a statement but not an expression.

Basic Structure of C/ C++ Program:


#include<header-file>
void main ( )
{
statement 1;
statement 2; body of c/c++ program
..
..
statement n;
}

# Include

It is called Pre-processor directive. It tells the compiler to inset header files into our source
code before the process of compilation.

Prepared by:Usama Musharaf For DIT Students Page 12


#include<header-file> Header File

It is a C or C++ library file which contains a group of related functions.

main ( ) Function
main ( ) is a C or C++ language function. It is the compulsory part of the C or C++ program. It
is the first executable function.

Body of program:
{
Here we can write our code
}

Structure of C program: Structure of C++ program:


#include<stdio.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main ( ) void main ( )
{ {
statement 1; statement 1;
statement 2; statement 2;
.. ..
.. ..
statement n; statement n;

} }

How can we insert any header file in a C/C++ Program?


A header-file can be inserted in any source code of C/C++ through a pre-processor directive
(#include). The general syntax for inserting a header file is #includes<header-file>.
For example, for using input and output stream objects in C++ source code, the following
directive is used. #include<iostream.h>.
Comments:
It is the brief description about a statement or a group of statements or about the whole
program. During compilation, the compiler ignores this portion.

Prepared by:Usama Musharaf For DIT Students Page 13


Importance of Comments:
Comments are used to explain the logic inside a program. It also tells us about the purpose
of whole program. It provides documentation to the program. It is very helpful in the case
when the program is to be updated or upgraded.
Types of Comments in C/C++:
There are two types of comments used in C/C++ language.
Single-Line Comment
Multi-Line Comment
Comments enclosed within the symbol /* and */ are considered multiline comments, while
comments followed by // are single line comments.

What do you know about the C/C++ Libraries?


A library in C/C++ is an additional part of language use to provide functions that are not
core part of the language.
It composes of different functions and declarations that are required to be included in our
program whenever they are needed.
There are dozens of C/C++ libraries included in “LIB” directory.
Operating systems like Microsoft Windows use a “.lib” extension for libraries, for example
maths.lib, grahics.lib etc. the header files for libraries are stored in a special directory
named include.

Define Multiple Assignment Operators (=):


If multiple assignment operators are chained together to form a single statement, then
called as multiple assignment operator.
Its general syntax is identifier-1 = identifier-2 = identifier-3 ……..;
In multiple assignments, the assignments are carried from right to left. X=Y=Z=10,
sum=count=i=0;

Prepared by:Usama Musharaf For DIT Students Page 14


OUTPUT STATEMENTS IN C / C++:

Printf() Function:

It is a standard output function in C-language. Its function is to display the messages,


constants and the values of variables or expression on screen.
Its general syntax is

printf(“format string”, var1/const1/expr1,var2/const2/expr2,….);

Where format string is a message enclosed in double quotes. It may contain escape
sequence characters or/and format specifier. The format specifiers for integer data are %d,
for float data is %f and for character data is %c etc.

Declaration Name Format Specifier


char %c
string %s
int %d
unsinged int %u
long int %ld
Unsigned long int %lu
float %f
double %lf
long double %Lf

cout<< Function:

cout stands for console output. It is a standard output stream use to display output on the
standard device like monitor. It is used with the combination of stream insertion operator
(<<). This stream object is capable to display messages, values, and value of variables or
expression on screen.

Its general syntax is

cout<<string/variable/constant/expression;

Where string must be enclosed in double quotes.

Example: cout<<”Hello! Good Morning”;

Prepared by:Usama Musharaf For DIT Students Page 15


putch() and putchar() function:

Putch() is an output function use to write a single character to the console.

Its general syntax is

putch (character/character_ variable);

Where character must be enclosed in single quote.

The header file <conio.h> is required to be included in the program for the putch() function.

Example:
char ch;
ch=getche();
putch(ch);

The putchar() is also an output function use to write a single character to the screen.

Its general syntax is

putchar(character/character_ variable)

The header file<stdio.h> is required for putchar() function.

clrscr() function is C/C++?


This function is used to clear the current text window and locate the cursor at the upper
left-hand corner of the screen. Its general syntax is clrscr();

INPUT STATEMENTS:

scanf () function:

It is a standard input function in C-language.

Its function is to read values for variables from keyboard during program execution.
General syntax is
scanf(“control string”,var1,&var2,….);

Example:
scanf(“%d”,&n);

Ampersand(&) sign is used to indicate the address of memory location.

Prepared by:Usama Musharaf For DIT Students Page 16


Difference between getch(), getche(), and getchar():
getch():

The getch() function is used to read a single character from keyboard during program
execution without echoing it on screen. There is no need to press the whitespace character
e.g. enter key etc.

getche():

The getche() function is used to input a single character form keyboard during program
execution and also echoes the character on screen. There is also no need to press the
whitespace character e.g. enter key etc.

getchar():

The getchar() function is also used to read a single character from keyboard at run time and
echoes it on screen but after that you need to press enter key.

gets():

This function is used to read an entire string until you press enter key.

Syntax : gets(variable);

cin>> Functiont:
cin stands for console input. It is a standard input stream use to receive input from the
standard input device like keyboard.

It is used with the combination of stream extraction operator (>>).

This stream object is capable to read values for various kinds of variables from keyboard
during program execution.

General syntax is
cin>>var-1>>var-2>>…..>>var-n;

Prepared by:Usama Musharaf For DIT Students Page 17


#include<stdio.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main( ) void main( )
{ {
clrscr( ); clrscr( );
printf(“Hello World \n”); cout<<”Hello World”<<endl;
printf(“This is My First Program”); cout<<”This is my irst Program”<<endl;
getch ( ); getch ( );
} }

Write a Program in C to add any two Write a Program in C++ to add any two integer
integer numbers and display the results. numbers and display the results.

#include<stdio.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main( ) void main( )
{ {
int num1,num2,sum; int num1,num2,sum;
clrscr( ); clrscr( );
num1=250; num1=250;
num2=135; num2=135;
sum=x+y; sum=x+y;
printf(“Result=%d”,sum); cout<<”Result = ”<<sum<<endl;
getch ( ); getch ( );
} }

Write a Program in C that inputs two Write a Program in C++ that inputs two
numbers at run time, and finds the sum & numbers at run time, and finds the sum &
difference. difference.

#include<stdio.h> #include<iostream.h>
#include<conio.h> #include<conio.h>

void main() void main()


{ {
clrscr(); clrscr();
int num1,num2,sum,diff; int num1,num2,sum,diff;
printf("Enter your first number = \n"); cout<<"Enter your first number ="<<endl;
scanf("%d",&num1); cin>>num1;
printf("Enter your second number= \n"); cout<<"Enter your second number ="<<endl;
scanf("%d",&num2); cin>>num2;
sum=num1+num2; sum=num1+num2;
diff = num1-num2; diff = num1-num2;
printf("%d",sum); cout<<sum;
printf("%d",diff); cout<<diff;
getch(); getch();
} }

Prepared by:Usama Musharaf For DIT Students Page 18


Student Report Card
#include<iostream.h>
#include<conio.h>

void main()
{
clrscr();
char Name[20];
int Roll_No,Eng,Urdu,Maths,Computer,Obtain_Marks,Total_Marks=400;
float Percentage;
cout<<"ENTER YOUR NAME : "<<endl;
cin>>Name;
cout<<"ENTER YOUR ROLL NO : "<<endl;
cin>>Roll_No;
cout<<"ENTER YOUR ENG MARKS : "<<endl;
cin>>Eng;
cout<<"ENTER YOUR URDU MARKS : "<<endl;
cin>>Urdu;
cout<<"ENTER YOUR MATHS MARKS : "<<endl;
cin>>Maths;
cout<<"ENTER YOUR COMP MARKS : "<<endl;
cin>>Computer;
Obtain_Marks=Eng+Urdu+Maths+Computer;
Percentage=(float)Obtain_Marks*100/Total_Marks;
clrscr();
cout<<"Your Name is "<<Name<<endl;
cout<<"Your Roll No is "<<Roll_No<<endl;
cout<<"YOUR OBTAIN MARKS ARE: "<<Obtain_Marks<<endl;
cout<<"YOUR PERCENTAGE IS: "<<Percentage<<endl;
getch();
}

Prepared by:Usama Musharaf For DIT Students Page 19


DECESION CONTROL STATEMENTS:

if statement:
if statement is used to execute a statement or group of statement on the basis of some
condition. If the given condition is true, then the statement in its body is executed,
otherwise not.
General syntax of if
if (condition)
{
Statement(s);
}

if-else statement:
if else statement is used to execute a statement or group of statement on the basis of some
condition. If the given condition is true, then the statement in its body of if is executed, and
if the condition is false then the body of else will execute.
This statement lets us to pick out one choice of statement between two on the basis of a
same condition.

General Syntax is;


if(condition)
{
Statement(s);
}
else
{
Statement(s);
}

If the given condition is true, then the statements after if clause will execute and
statements after else will skip. But if the condition false, then statements after else will
execute only.

Prepared by:Usama Musharaf For DIT Students Page 20


Write a program to input a number and check
#include<iostream.h> whether the number is EVEN or ODD.
#include<conio.h>
#include<iostream.h>
void main()
#include<conio.h>
{ void main()
clrscr(); {
int marks; int number, reminder;
cout<<"Enter your Marks="; clrscr();
cin>>marks; cout<<”Enter your number”;
if(marks>=50); cin>>number;
reminder=number%2;
{
if(reminder= =0)
cout<<"Pass"; {
} cout<<”Number is Even”;
else }
{ else
cout<<"Fail"; {
} count<<”Number is Odd”;
}
getch();
getch();
} }

Write a program to check whether the two numbers Write a program to find the Largest number between
are equal or not? two numbers?

#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
clrscr(); clrscr();
int number1,number2; int number1,number2;
cout<<"Enter First Number="; cout<<"Enter First Number=";
cin>>number1; cin>>number1;
cout<<"Enter Second Number="; cout<<"Enter Second Number=";
cin>>number2; cin>>number2;
if(number1==number2); if(number1>number2);
{ {
cout<<"Numbers are Equal"; cout<<"Largest Number is "<<number1;
} }
else else
{ {
cout<<"Numbers are not Equal"; cout<<"Largest Number is"<<number2;
} }
getch(); getch();
} }

Prepared by:Usama Musharaf For DIT Students Page 21


Write a program to input three numbers from keyboard & find the largest number
amongst them?

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num1,num2,num3,max;
cout<<"Enter your first number=";
cin>>num1;
cout<<"Enter your second number=";
cin>>num2;
cout<<"Enter your Third Number=";
cin>>num3;
if(num1>num2)
{
max=num1;
}
else
{
max=num2;
}
if(num3>max)
{
max=num3;
}
cout<<"Maximum number is="<<max;
getch();
}

Conditional Operator (? :) in C/C++:


Conditional Operator is the shortest form of an if-else statement. In this statement, the
condition is first evaluated, if it is true then the value of first expression is evaluated,
otherwise the value of 2nd expression is evaluated.
Example;
cout<<( (marks>50) ? “PASS”:”FAIL”);

Write a program to input a number and check


whether the number is EVEN or ODD using
#include<iostream.h>
Conditional Operator?
#include<conio.h>
void main() #include<iostream.h>
{ #include<conio.h>
void main()
clrscr(); {
int marks; int number, reminder;
cout<<"Enter your Marks="; clrscr();
cin>>marks; cout<<”Enter your number”;
cin>>number;
cout<<( (marks>50) ? “PASS”:”FAIL”); reminder=number%2;
getch(); cout<<( (reminder==0) ? “EVEN”:”ODD”);
} getch();
}

Prepared by:Usama Musharaf For DIT Students Page 22


Different between Conditional Operator and if else Statement:
Conditional operator is a simple control statement that allows us to select one of the two
expressions for evaluation on the basis of condition, while if-else statement lets us to
execute one group of statements out of two on the basis of a given condition.

Else if statements:

If & else statements are used when we have to make decisions between two choices but
when we have multiple choices then we use else if statement.

Syntax:

if (condition)

else if (condition)
By using else if statement we can have multiple choices.
{

else if (condition) We can make decisions on the basis of multiple


conditions.
{

else if (condition)

else

Prepared by:Usama Musharaf For DIT Students Page 23


#include<iostream.h> #include <iostream.h>
#include<conio.h> #include <conio.h>
void main ()
void main()
{ {
clrscr(); clrscr();
int num1,num2; char choice;
cout<<"Enter your first number="; int f_num,s_num,sum,minus,mult;
cin>>num1;
cout<<"Enter the first num" <<endl;
cout<<"enter your second number=";
cin>>num2; cin>>f_num;
if(num1>num2) cout<<"Enter the second num" <<endl;
{ cin>> s_num;
cout<<"first number is greater";
cout<<"ENTER YOUR CHOICE (+,-,*) " <<endl;
}
else if(num2>num1) choice=getche();
{ if(choice=='+')
cout<<"second number is greater"; {
} sum=f_num+s_num;
else{
cout<<sum<<endl;
cout<<"numbers are equal";
} }
getch(); else if(choice=='-')
} {
minus = f_num - s_num;
cout<<minus<<endl;
}
else if(choice=='*')
{
mult = f_num*s_num;
cout<<mult<<endl;
}
else{
cout<<"invalid choice"<<endl;
}
getch();
}

Prepared by:Usama Musharaf For DIT Students Page 24


Nested if Statement:

When an if-statement is embedded (included) inside the body of another if, then it is called
as nested-if statements.
Syntax:
If (condition)
{
If (condition)
{
statement.

}
else
{

}
}
else
{
statement.

#include<iostream.h>
#include<conio.h>
void main()
{
Int marks;
clrscr();
cout<<”enter your marks”;
cin>>marks;
If (marks>=30)
{
If (marks>=50)
{
cout<<”Good;
}
else
{
cout<<”Average;
}
}
else
{
cout<<”Poor”;
}
getch();
}

Prepared by:Usama Musharaf For DIT Students Page 25


Switch Statement/Multiple Decision Making Statement:

The switch statement is a special form of multiple-alternative decision making i.e when
multiple choice possibilities are based on a single value.

Syntax:

switch(expression)
{
case value-1: statement;
break;

case value-2: statement;


break;

case value-3: statement;


break;
:
:
case value-n: statement;
break;

default: statement;
}

Role of Break Statement in Switch Statement:

Break in switch statement is used to exit the switch and transfer the control to the next
statement outside the switch body.

Different between else if and switch statement:

Else if statement allows us to execute group of statements based on multiple condition,


while switch statement allows us to execute group of statements based on a single value.

Prepared by:Usama Musharaf For DIT Students Page 26


#include <iostream> #include<iostream.h>
#include<conio.h> #include<conio.h>
void main () { void main()
char grade; {
clrscr();
clrscr();
int num1,num2,sum,sub,mul,prod,choice;
cout<<”Enter Your Grade”; cout<<"Enter your first number";
cin>>grade; cin>>num1;
switch(grade) { cout<<"Enter your Second number";
case 'A' : cin>>num2;
cout << "Outstanding!" << endl; cout<<"Enter your choice\n";
break; cout<<"Press 1 for Addition\n";
cout<<"Press 2 for Subtraction\n";
case 'B' :
cout<<"Press 3 for Multiplication\n";
cout << "Excellent" << endl; cin>>choice;
break; switch (choice)
case 'C' : {
cout << "Good" << endl; case 1: sum=num1+num2;
break; cout<<sum;
case 'D' : break;
case 2: sub=num1-num2;
cout << "Fair" << endl;
cout<<sub;
break; break;
case 'E' : case 3: mul=num1*num2;
cout << "Poor" << endl; cout<<mul;
break; break;
default : defualt: cout<<"Please Select valid choice";
}
cout << "Invalid grade" << endl;
getch();
} }
cout << "Your grade is " << grade << endl;

getch();
}

Prepared by:Usama Musharaf For DIT Students Page 27


LOOPS

One of the main features of programming is looping because in many situations some operations
are performed over and over again.

A statement or group of statements that is required to be executed repeatedly is called loop.

A loop is used for the purpose of repetitive task when we have to execute same type of
statement again & again we use loops.

Two types of Loop:

Counter or Determined Loop

Controlled or Undetermined Loop

Counter or Determined Loop is used in that case when the precise number of repetition is
known in advance.

Controlled or Undetermined Loop is used in a situation when number of repetition is not


known in advance.

For Loop:
For loop is used to execute a statement or group of statement for the specified number of times.
This is called a determined loop, because this loop is preferred to use when we know in advance
that how many times the loop will execute.

Syntax is; for (initialization; condition; incrementation / decrementation)


{
Statements; // body of loop
}

In initialization, the control variable is given the initial value and this variable will control the
loop.
In condition, the control variable is compared with some limit value to check whether the loop is
continued or not? If it is true, then loop is continued, otherwise not.

Prepared by:Usama Musharaf For DIT Students Page 28


Write a program to display a word “PAKISTAN” Write a program to print first ten numbers on
ten times on screen? screen?

#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>

void main() void main()


{ {
clrscr(); clrscr();
int i; int i;
for (i=1;i<=10;i++) for (i=1;i<=10;i++)
{ {
cout<<"Pakistan"<<endl; cout<<i<<endl;
} }
getch(); getch();
} }
Write a program to print first ten numbers on Write a program to print EVEN numbers upto 20
screen in descending order? on screen?

#include<iostream.h>
#include<conio.h> #include<iostream.h>
#include<conio.h>
void main()
{ void main()
clrscr(); {
int i; clrscr();
for (i=10;i>=1;i--) int i;
{ for (i=0;i<=20;i=i+2)
cout<<i<<endl; {
} cout<<i<<endl;
getch(); }
} getch();
}
Write a program to display even numbers in Write a program to print ODD numbers from 1 to
descending order from 100 to 0. upto 25 on screen?

#include<iostream.h>
#include<iostream.h>
#include<conio.h> #include<conio.h>

void main() void main()


{ {
int i; clrscr();
int i;
clrscr();
for (i=1;i<=25;i=i+2)
for(i=100;i>=0;i=1-2) {
{ cout<<i<<endl;
cout<<i<<”/t”; }
} getch();
getch() }
}

Prepared by:Usama Musharaf For DIT Students Page 29


While Loop:

While loop is used to execute a single or multiple statements repeatedly until a specified
condition is true. This is called a pre-condition loop because in this loop, the condition is
first evaluated and then it is decided whether the body of loop is executed or not. While
loop is used when the number of repetition is not known in advance.

while (condition)
{
statements;
}

The given condition is first evaluated, if it is true then the body of loop will execute,
otherwise not.

#include<iostream.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
ch = 'y';
while(ch=='y')
{
cout<<"PAKISTAN"<<endl;
cout<<"Are you want to continue [y/n]"<<endl;
cin>>ch;
}
getch();
}

The program written above will continuously print the word PAKISTAN until user presses y.

In this situation it is not known in advance that how many times the user will press ‘y’ key to
continue the process.

Prepared by:Usama Musharaf For DIT Students Page 30


Do While Loop:

Do while loop is used to execute a statement of group of statements repeatedly until a given
condition is true.

This is called post condition loop because in this loop, the body of loop will first execute and then
the condition is evaluated at the end.

If the condition is true, the execution of loop will continue, otherwise not, but even after condition
being false the loop will execute once.

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.
Syntax:
do
{
statements;
}
while (condtion);

#include <iostream.h>
#include<conio.h>

void main () {
int a = 10;
do {
cout << "value of a: " << a << endl;
a = a + 1;
}while( a < 10 );

getch();
}

Prepared by:Usama Musharaf For DIT Students Page 31


Write a program to input a number from keyboard and create table for that number?

#include<iostream.h>
#include<conio.h>
void main()
{
int number, i, tab;
cout<<"Enter Number for Table "<<endl;
cin>>number;
for(i=1;i<=10;i++)
{
tab = number*i;
cout<<number<<"*"<<i<<"="<<tab<<endl;
}
getch();
}
………………………………………………………………………………………………………………………………………….
Using while Loop
#include<iostream.h>
#include<conio.h>
void main()
{
int number, i, tab;
cout<<"Enter Number for Table "<<endl;
cin>>number;
i=1;
while(i<=10)
{
tab = number*i;
cout<<number<<"*"<<i<<"="<<tab<<endl;
i++;
}
getch();
}

Prepared by:Usama Musharaf For DIT Students Page 32


Function:
A function is used to do some specific task. A function is basically a group of statements
that together perform a task.

Every C++ program has at least one function, which is main().

You can divide up your code into separate functions and can assign different task to
functions.

It makes our program easier by writing the same code again and again.

The function is defined once in the program it but can be used several times by just calling
that function when desired.

Declaration of function:
We must have to declare a function before defining function body. The declaration of a
function is called function prototype.

Function prototype is a statement which must ends with a semicolon.

Function prototype consists of

return type function name ( );

return type function name (type parameter, type parameter ……..);

Defining Function:
In function body we define the task that a function is going to perform.

We can define the function body anywhere outside the main ( ).

Syntax:

return type function name (type parameter, type parameter ……..)

body of function;

Prepared by:Usama Musharaf For DIT Students Page 33


#include<iostream.h>

#include<conio.h>

void display();

void main()

clrscr();

display();

cout<<"Welcome to the programming world"<<endl;

cout<<"This is a program to clear the concept of function"<<endl;

cout<<"Programming is interesting"<<endl;

display();

getch();

void display()

cout<<"**************"<<endl;

OUTPUT:

**************

Welcome to the programming world

This is a program to clear the concept of function

Programming is interesting

**************

Prepared by:Usama Musharaf For DIT Students Page 34


#include<iostream.h>

#include<conio.h>

void add(int x, int y);

void subtract(int x, int y);

void main()

int n1,n2;
clrscr();
cout<<"enter first number"<<endl;
cin>>n1;
cout<<"enter second number"<<endl;
cin>>n2;
add(n1,n2);
subtract(n1,n2);
getch();
}
void add(int x,int y)
{
int s;
s=x+y;
cout<<s<<endl;
}
void subtract(int x,int y)
{
int s;
s=x-y;
cout<<s<<endl;
}

Prepared by:Usama Musharaf For DIT Students Page 35


System Defined/Built-in Functions:
Built-in functions play a very vital role in computer programming. These functions are used
to perform some pre-determined task.
The body of pre-determined functions are already defined, programmer just need to call the
desired function.
Some of the built-in functions are as follow.

Trigonometric Functions:

Functions Purpose

sin(x) Compute sine of x where x must be in radian

cos(x) Compute cosine of x where x must be in radian

tan(x) Compute tangent of x where x must be in radian

asin(x) Compute arc sine of x where x must be in radian

acos(x) Compute arc cosine of x where x must be in radian

atan(x) Compute arc tangent of x where x must be in radian

sinh(x) Compute hyperbolic sine of x where x must be in radian

cos(h) Compute hyperbolic cos of x where x must be in radian

tan(h) Compute hyperbolic tan of x where x must be in radian

#include<iostream.h>
#include<conio.h>
#include<math.h>
void main()
{
double x= 50.0;
clrscr();
x= x*(3.14159/180);
Prepared by:Usama Musharaf For DIT Students Page 36
cout<<"Sin 50 = "<<sin(x)<<endl;
cout<<"Cos 50 = "<<cos(x)<<endl;
cout<<"Tan 50 = "<<tan(x)<<endl;
cout<<"Sin inverse 50 = "<<asin(x)<<endl;
cout<<"Cos inverse 50 = "<<acos(x)<<endl;
cout<<"Tan inverse 50 = "<<atan(x)<<endl;
cout<<"Sin hyperbola 50 = "<<sinh(x)<<endl;
cout<<"Cos hyperbola 50 = "<<sinh(x)<<endl;
cout<<"Tan hyperbola 50 = "<<sinh(x)<<endl;
getch();
}

Arithmetic Functions:
abs(x) Computes the absolute value of an integer.
labs(x) Computes the absolute value of a long integer.
fabs(x) Computes the absolute value of a floating-point value.
fabsl(x) Computes the absolute value of long double value.

sqrt(x) Computes the square root of the given value.


pow(x,y) Computes the power of given values. E.g pow(3,4) = 81.
log(x) calculates the natural logarithm of x, whereas log10(x) calculates the common
logarithm of x .
log(1)  0
log10(10)  1
exp(x) function is referred to as exponential function. It performs the opposite of log.
exp(0)  1

Prepared by:Usama Musharaf For DIT Students Page 37


ceil & floor Function:
ceil function is used to round up and floor function is used to round down.
ceil(9.5) 10
floor (9.5)  9

Sqrt() Pow()
#include<iostream.h> #include<iostream.h>
#include<conio.h> #include<conio.h>
#include<math.h> #include<math.h>
void main() void main()
{ {
double number; int number,power;
clrscr(); clrscr();
number=4; number=4;
cout<<sqrt(number); power=2;
getch(); cout<<pow(number,power);

} getch();

fmod() Function:
Modulus operator only computes the reminder of integer numbers, whereas the fmod()
function computes the reminder of real numbers as well.
#include<iostream.h> Output:
#include<conio.h> Reminder = 2.623
#include<math.h>
void main()
{
double x = 10.123;
double y = 7.5;
cout<<”Reminder = ”<<fmod(x,y);
getch();
}

Prepared by:Usama Musharaf For DIT Students Page 38


String Functions:
String Functions are used to perform operations with string data. Header file <string.h>
must be include for using string functions.

strlen() Function calculates the length of the string.


char Name[30]= “Muhammad Khan”;
cout<<”The Total Length is = ”<<strlen(Name);

Sample Output:
The Total Length is = 13

Strlwr() converts the uppercase letters to lower case and strupr() converts the
lowercase letters to upper case.
cout<<strlwr(“MUHAMMAD KHAN”)<<endl;
cout<<strupr(“ ahsan khan”);

Sample Output:
muhammad khan
AHSAN KHAN

strrev() function reverse all the character of a string.


cout<<strrev(“AMEER”);  REEMA

strcpy() Function copies one string to another.


strcpy(Target String, Source String)
Example:
char Name1[10]= “SALMAN”;
char Name2[10]= “ALI”;
strcpy(NAME1 , NAME2)
cout<<NAME1<<endl;
cout<<NAME2;

Sample Output:
ALI
ALI

Prepared by:Usama Musharaf For DIT Students Page 39


strcat() Function concatenates one string into another.

Example:
char str1[10]= “ABC”;
char str2[10]= “DEF”;
strcat(str1 , str2)
cout<<str1<<endl;
cout<<str2;

Sample Output:
ABCDEF
DEF

Prepared by:Usama Musharaf For DIT Students Page 40

You might also like