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

Introduction to C++

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

Introduction to C++

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

Introduction to C++: Applications, Example Programs, Tokens, Data Types,

Operators, Expressions, Control Structures, Arrays, Strings, Pointers, Searching


and Sorting Arrays.

1.​ What is C++?


▪​ C++ is an Object Oriented Programming language (OOP) and
is an extension to C language. It is middle level language, as
it comprises of both high level and low level language features
C++ was developed by Bjarne Stroustrup starting in 1979 at
bell Labs in Murray Hill, New jersey.
▪​ C + + supports the features of object-oriented programming
▪​ Following are the OOP features supported by C
1.​ Encapsulation
2.​ Data hiding
3.​ Classes and Objects
4.​ Inheritance
5.​ Polymorphism

​ Applications of C++

​ Applications - C + + is widely used in software infrastructure


including desktop applications, servers like E-commerce , web
search or SQL servers , and performance-critical applications
like telephone switches
​ Following are few applications of C + +:

1.​ Games -C + + overrides the complexities of 3D games ,


optimizes resource management and facilitates. For instance ,
the science fiction game Doom 3 is cited as an example of a
game that used C + + well and the Unreal Engine
, a suite of game development tools , is written in C + +.
2.​ Graphic User Interface ( GUI ) based applications: Many
highly used applications such as Image Ready, Adobe Premier,
Photoshop and illustrator, are scripted in C + +
3.​ Web Browsers: With the introduction of specialized
languages such as PHP and Java, the adoption of C + + is
limited for scripting of websites and web applications For
instance , a part of Google's back-end is coded in C + + , and
the rendering engine of a few open source projects , such as
web
browser Mozilla Firefox and email client Mozilla Thunderbird , are also
scripted in the programming language .
4.​ Advance computations and graphics: C++ provides for building
application requiring real-time physical simulations, high performance
image processing and mobile sensors applications. Maya 3D software.
5.​ Database software: C + + has been used for scripting MySQL, one of the
most popular database management software . The software forms the
backbone of a variety of database-based enterprise Software: Google,
Wikipedia, Yahoo and You Tube etc.
6.​ ​Operating systems: it is an a interface between user and hardware and
also software which performs all basic tasks.
7.​ Enterprise software: C++ is used in banking and trading enterprise
applications such as those deployed by Bloomberg. It is also used in
development of advanced software, such as flight simulators and radar
processing.
8.​ Medical and Engineering Applications: many advanced medical
equipments, such as MRI machines, use C + + language for scripting their
software. It is also part of engineering applications, such as high-end CAD
/ CAM.
9.​ Compliers: A host of compilers including Apple C++, Bloodshed Dev C++ ,
Clang C + + and MINGW

​ Example Programs of C++

​ A compiler is a computer program which converts high-level language into


machine low-level language.
​ ​In other words we can say that it converts the source code written in a

programming language into another computer language which computer


understands.

​ Creating C + + program:

​ To compile and execute it depends on three things the


1.​ Operating system
2.​ The text editor
3.​ Compiler

​ We will describe in details – Windows environment, UNIX Environment

1. Developing a C + + Program In Windows Environment :


​ There are many integrated development environment (IDE) available for
windows operating system.
​ such as CodeBlocks, DevC++, Turbo C++, Borland C++ etc , which can be
used to work easily with C programming language.

(a)​Using Turbo C + + IDE

Steps to create and execute a C++ program in Turbo C++ ;

1.​ Open turbo C + + IDE , click on file and the click on new
2.​ Now write your c program in this empty file
3.​ Save the file with .cpp extension(program.cpp)
4.​ Click on compile or press alt+f9 to compile code
5.​ Click on run or press ctrl+f9
6.​ The program is executed

(b)​Using CodeBlocks IDE

1.​ After installing code blocks go to file menu--- select new and then empty file
2.​ Now write your c++ program and save with .cpp extension
3.​ After saving build and run option in build menu
4.​ The program is compiled and executed. Outpit will be displayed.

(C)​Developing program in unix environment

1.​ Use vi editor to create a text file save file with .cpp (first.cpp) that contains
c++ program
2.​ write the program
3.​ after that for compile cc program name(first.cpp)
4.​ /a.out for output

​ Basic program should have:

1.​ Preprocessor directive- These are processed by the compiler before the
program code . # include instructs the compiler to use the standard C + +
library and library name is specified through angled bracket . And " using
directive " helps programming easier , Without " using directive , instead of
cout and endl , std : cout and std : endl should be written as the iostream
library is within std namespace.

#include<iostream>
Using namespace std;
#include<conio.h>

2.​ Comment -These would not be compiled and executed.


3.​ Main function - this is important entry point in C++. C++ should have main
function
int main( )
{
}
4.​ Statement - These are actions that the programs execute when it runs Each
statement should be terminated with semicolon.

cout < < " Hello World ! " < < endl;
return 0;

In main function , return 0 : statement means the program would return a


zero integer value.

​ C++ Basic Input/Output

​ C++ I/O operation is using the stream concept. Stream is the sequence of
bytes or flow of data. It makes the performance fast.
​ If bytes flow from main memory to device like printer, display screen, or a
network connection, etc, this is called as output operation.
​ If bytes flow from device like printer, display screen, or a network connection,
etc to main memory, this is called as input operation.

​ Standard output stream (cout)

​ The cout is a predefined object of ostream class. It is connected with the


standard output device, which is usually a display screen.
​ The cout is used in conjunction with stream insertion operator (<<) to display
the output on a console

​ Standard input stream (cin)

​ The cin is a predefined object of istream class. It is connected with the


standard input device, which is usually a keyboard.
​ ​The cin is used in conjunction with stream extraction operator (>>) to read
the input from a console.
2.​What are the Tokens?

▪​ A token is the smallest individual unit in C + + language. In fact, every unit


that make in C++ is a Token C++ has six types of Tokens as given below.
1.​ Keywords
2.​ Identifiers
3.​ Constant
4.​ Special Symbols
5.​ Operators

1.​ Keywords -Keywords are those words that have special meaning for compiler. Key
words cannot be used a variable name or identifier. Below are the lists of C + +
keywords

auto break Case char const continu Defaul do


e t

doubl else Enum exter float for Goto if


e n

int long Registe retur short signed Sizeof stati


r n c

struct switc Typede union unsigne void Volatil whil


h f d e e

2.​ Identifiers - are fundamental building blocks of a program and are used for the
names given to different parts of program viz . variables , functions array
structure.

Rules of naming Identifiers

1)​ Identifiers can have alphabets , digits and underscore sign characters .
2)​ They must not be a keyword or boolean literal or null literal
3)​ They must not begin with a digit .
4)​ They can be of any length .
5)​ C + + is case sensitive ie , upper-case letters and lower-case letters are
treated differently
3.​ Constants or Literals - Constants or Literals are data items that never change
their value during the execution of the program . The following types of literals
are available in C + +
1)​ Integer-Constants
2)​ Character-constants
3)​ Floating-constants

1)​ Integer Constant - Integer constants are whole number without any fractional
part C + + allows three types of Integer constants.
a.​ Decimal integer constants : It consists of sequence of digits and should
not begin with 0 ( zero ) . For example 124 . , + 108 .
b.​ Octal integer constants : It consists of sequence of digits starting with
0 ( zero ) . For example
c.​ ) Hexadecimal integer constant : It consists of sequence of digits
preceded by ox or OX .
2)​ Character constants - A character constant in C + + must contain one or more
characters and must be enclosed quotation marks. ‘A’

3)​ Floating constants - They are also called real constants. They are numbers
having fractional parts . They may be written in fractional form or exponent
form. A real constant in fractional unsigned digits including a decimal point
between digits.
For example 3.0,-17.0.-0.627 etc

4)​ Strings - A sequence of character enclosed within double quotes is called a


string literal String literal is by automatically added with a special character "0
which denotes the end of the string. Therefore the size of the string is
increased by one character. For example "COMPUTER will re represented as
COMPUTER\0 " in the memory and its size is 9 characters .

4.​ Special symbols

Special
Trivial Name Function
Character
The opening and closing brackets of an array symbolize single
[] Square brackets
and multidimensional subscripts.
() Simple brackets The opening and closing brackets represent function
declaration and calls, used in print statements.
The opening and closing curly brackets to denote the start and
{} Curly braces end of a particular fragment of code which may be functions,
loops or conditional statements
We use commas to separate more than one statements, like in
, Comma
the declaration of different variable names
Hash / Pound / The hash symbol represents a preprocessor directive used for
#
Preprocessor denoting the use of a header file
We use the asterisk symbol in various respects such as to
* Asterisk
declare pointers, used as an operand for multiplication
~ Tilde We use the tilde symbol as a destructor to free memory
. Period / dot The use the dot operator to access a member of a structure

6.​Operators

▪​ An operator is simply a symbol that is used to perform operations.


▪​ There can be many types of operations like arithmetic, logical, bitwise etc.
▪​ There are following types of operators to perform different types of operations
in C language.

o​ Arithmetic Operators
o​ Relational Operators
o​ Logical Operators
o​ Bitwise Operators
o​ Assignment Operator
o​ Unary operator
o​ Ternary or Conditional Operator
o​ Increment and decrement operator
o​ The Arithmetic Operators in C++ include:

1. + (Addition) – This operator is used to add two operands.


2. – (Subtraction) – Subtract two operands.
3. * (Multiplication) – Multiply two operands.
4. / (Division) – Divide two operands and gives the quotient as the
answer.
5. % (Modulus – Find the remains of two integers and gives the
operation) remainder after division

PROGRAM:
1.​ #include <iostream>
2.​ using namespace std;
3.​ #include<conio
.h> 4.
5.​ int
main() 6. {
7.​ int a = 10, b = 7,result ;
8.​ result =x+y;
9.​ cout<<"The Addition of "<< result<<endl;
10. result =x-y;
11. cout<<"The Subtraction of "<< result<<endl;
12. result =x*y;
13.​cout<<"The Multiplication of "<< result<<endl;
14.​ result =x/y;
15.​cout<<"The Division of “<< result<<endl;
16. result =x%y;
17.​cout<<"The Modulus operation between "<< result<<endl;
18.​getch();
19.​return 0;
20.}

o​ relational operator : It is used to compare two numbers by checking whether they


are true or false If the relational statement is satisfied (it is true), then the
program will return the value 1, otherwise, if the relational statement is not
satisfied (it is false), the program will return the value 0.

1. == (Equal to)– This operator is used to check if both operands are equal.
2. != (Not equal Can check if both operands are not equal.
to)–
3. > (Greater than)– Can check if the first operand is greater than the second.
4. < (Less than)- Can check if the first operand is lesser than the second.
5. >= (Greater than
6. equal to)– Check if the first operand is greater than or equal to the
second.
7. <= (Less than Check if the first operand is lesser than or equal to the
equal to) second

PROGRAM:
#include<iostream>
Using namespace
std;
#include<conio.h>
int main()
{
int x,y;
cout<<”enter value for x: “;
cin>>x;

cout<<”enter value for y: “;


cin>>y;
if(x>y)//0 is false, non-zero is true
{
Cout<<”x is greater than y.”;
}
if(x<y)//0 is false, non-zero is true
{
Cout<<”y is greater than x.”;​ output:
}​ enter value for x: 50
if(x==y)//0 is false, non-zero is true​ enter value for y: 25
{
Cout<<”x and y are both equal.”;
}
Getch();
Return 0;
}

o​ Logical operator: are used when we have more than one condition in a single if
statement.

Operator Operation Description


&& (a && b) AND: Used to check if both the operands are true
|| (a || b) OR: Used to check if at least one of the operand is true
! !a NOT: Used to check if the operand is false

o​ Bitwise operator – performs bit by bit

operation. Truth table:

Operator Operand Operation Description


AND operator copies bit to result if it exists in both
& a, b (a&b)
operands
OR operator copies bit to result if it exists either in
| a, b (a|b)
operand
XOR operator copies bit if it is set in one operand but
^ a, b (a^b)
not both operands+
One’s complement operator: Converts the operand
~ a (~a)
into its complementary form
<< a a<< Left shift
>> a a>> Right shift

PROGRAM:
1.​ #include <iostream>
2.​ using namespace std;
3.​ #include<conio.h>
4.​ int
main() 5. {
6. int a = 26, b = 14;
7.​ int c=0;
8.​ c=a&b;
9.​ cout<<" Bitwise AND operation" << a << " & " << b << " : " << (a&b)
<<endl;
10.​ c=
a|b; 11.
12.​cout<<" Bitwise OR operation" << a << " | " << b << " : " << (a|b) <<endl;
13.​ c=a
^b; 14.
15. cout<<" Bitwise XOR operation" << a << " ^ " << b << " : " << (a^b)
<<endl;
16. c=~a;
17.
18. cout<<" Bitwise ONE'S COMPLEMENT ~"<< a << " operation :"<< (~a)
<<endl;
19. c=a<<b;
20. c=a>>b;
21.
22. return 0;

o​ Assignment operator

Assignment operator is used to copy value from right to left variables.

Float x = 5, y = 2;

The above statement assigns value of 5 and 2 to variable X and Y respectively

PROGRAM
Program to show usage of assignment operator :
#include<iosteam>
Using namespace std;
#include<conio.h>
Int main()
{
Int x=5, y=2;
Cout<<:Initial values, x=”<< x <<, y=”<<endl;
X=y ;​ ​ //assign the value of y to x
Cout<<”After x=y, x=”<< x <<”, y=”<< y <<endl
X=5;​ //reassign initial value 5
X+=y;
Cout<<”After x+=y, x=”<< x <<endl;
X = 5; //reassign initial value 5
x-=y;
cout<<After x-=y, x=”<< x <<endl
x = 5; //reassign initial value 5
x*=y;
cout<<After x*=y, x=”<< x<<endl;
x=5;​ //reassign initial value 5
x/=y;
cout<<After x/=y, x=”<< x <<endl;
x = 5; //reassign initial value 5
x % =y;
cout<<after x %=y, x=”<< x <<endl;
output :
initial values, x = 5, y = 2
after x = y, x = 2, y=7
After x+=y, x = 7
After x-=y, x = 3
After x*=y, x = 10
After x/=y, x = 2
After x%=y, x = 1

6.​Conditional Operator:

▪​ The conditional operator is also know as ternary operator. It is called ternary


operator because it takes three argument.
▪​ First is condition, second and third is value.
▪​ The conditional operator checks the condition, if the condition is true, it will
return second value, if condition is false, it will return third value.

Syntax : val = condition ? val1 : val2;

PROGRAM

Program to show Conditional operator :


#include<iostream>
Using namespace std;
#include<conio.h>
Int main()
{
Int x, y, larger;
Cout<< “enter two numbers:”;
Cin>> x >>y;
Larger = (x>y) ? x : y
Cout<<”largest number is :”<<larger;
Getch()
Return 0;
}
Output :
Enter two numbers: 10 30
Largest number is : 30

7.​Unary Operator:

▪​ Unary operator are those operator that work with single operands such a
increment or decrement operator.
▪​ The increment operator ++ add 1 to its operands, and the decrement
operator –subtracts 1 from its operands.

X = x +1;
Is the same as
X++;
Similarly,
X = x-1;
Is the same as
x--;
▪​ Both the increment and decrement operator can either precede (prefix) or
follow (postfix) the operands. For example.

x =x+1
can be written as
++x;​ //prefix form
Or as
X++;​ //postfix form
Similarly
X = x-1;
Can be written as
--x;​ //prefix form;
Or
X++; //postfix form

▪​ In prefix form the increment or decrement will be done before rest of the
expression is evaluated, and postfix form, the increment or decrement will be
done after the complete expression is evaluated.

PROGRAM

Program to show Unary operator :


#include<iostream>
Using namespae std;
#include<conio.h>
Int main()
{
Int a = 10;
Int c = 0;
Cout<<”initial value of c =”<< c<< “,a=”<< a<< endl;
C=a++;​ //value of a=10 is assigned to c then incremented
Cout<<”post increment(a++) : value of c=<< c <<”, a=”<< a <<endl;
Cout<< endl<<”initial value of c =”<< c <<, a =”<< a <<endl;
C = ++a;
Cout<<”pre increment (++a) : value of c =”<< c <<”, a=”<< a<<endl;
Getch()
Return 0;
}

Output :
Initial value of c=0, a = 10;
Post increment (a++) : value of c=10, a=11
Initial value of c=10, a=11;
Pre increment (a++) : value of c=12, a=12

​ Expression

​ An expression is a combination of variables, constants and operators that


represent a computation.

1.​ Constant expressions: The expression that consist of only constant value are
called constant expression. Some example of constant expression are 20, ‘a’ and
2/5+30.

2.​ Integral expressions: The expression that produce an integer value as output
after performing all types of conversions are called integral expression . for example
, x,6*x-y and 10 +int(5.0) are integer expression. Here, x and y variable of type
integer.

3.​ Float expression: The expression that produce floating-point value as output
after performing all types of conversion are called float expression. For example,
9.25, x-y and 9+float (7) are float expression. Here, x and y are variable of type
float.

4.​ Relational or Boolean expression: The expression that produce a bool type
value, that is either true or false are called relational or Boolean expression. For
example , x+y, <, m+n== a-b and a>=a+c are relational expression.

5.​ Logical expression: The expression that produce a bool type value after
combining two or more relational expression are called logical expression. For
example , x==5, &&m==5 and y>x || are logical expression.

6.​ Bitwise expression: The expression which manipulate data at bit level are
called bitwise expression, for example, a >>4 and b<<2 are bitwise expression.
✔​ Data Types:
▪​ Data types are used to define a variable. Data types represent the types of
information present in a variable.
▪​ Data types are the keywords, which used for assigning a type to a variable.

1.​Value types:

a.​ Integer type: integer data type are like whole number, they also include
negative number but does not support decimal numbers.
b.​ Float-point type: float data type allow user to store decimal values in a
variable.
c.​ Character type: character data type is used to store only one letter, digit,
and symbol at a time.

2.​Reference types:

a.​ Array: array is a collection of similar data type. A single variable can hold
only one value at a time, if we want a variable to store more than one value
of same type we use array.
b.​ pointers: a normal variable is used to store value. A pointer variable is used
to store address calculation on operands.

Controls Structures:

●​ A C++ program is set of statement which are normally executed sequentially


in order in which they appear.
●​ C++ language possesses such decision making capabilities know as control
structure.
●​ Control structure enable us to specify the flow of program control, the order
in which the instruction in a program must be executed. They make it
possible to make decision, to perform takes repeatedly or to jump from one
section of code to another.

1.​Branching Statement:
These statement are popularly know as decision making statement

●​ If
●​ If else
●​ Nested if else
●​ If else if
●​ Switch
●​ Conditional statement
2.​Looping Statement:
A portion of program that is executed repeatedly is called a loop.

●​ While
●​ Do while
●​ For

3.​Jumping Statement:
Jumping statement are special control statement are used to transfer the
program’s control from one location to another.
The C++ programming language contain the following jumping statement:

●​ Go to statement
●​ Return statement
●​ Break statement
●​ Continue statement

​ Branching statement –

if : The if control statement is a conditional statement which checks the


conditional given as an argument to the statement and if evaluated to true
continues the execution of the statement that are existing within the statement.

Syntax: if(<condition>)
{
Statement 1;
Statement 2;

Statement n;
}

Program to show If statement:


#include<iostream>
Using namespace std;
#include<conio.h>
Int main()
{
Float avg;
Cout<<”Enter average marks:”;
Cin>>avg;
If(avg >=60) /* if condition is true, then statement after if is executed*/
{
Cout<<”you have hot first class”;
}
Getch()
Return 0;
}
Output :
Enter average marks : 65
You have got first class

if else statement: This control statement works exactly same as the if statement. We
provide the alternative statement to be executed if the given condition is evaluated
to false that is the else part.

Syntax: if(<condidition>)
{
Statement 1;

Statement n;
}
Else
{
Statement 1;

Statement n;
}

Program to show if –else statement:

#include<iostream>
Using namespace std;
#include<conio.h>
Int main()
{
Int age;
Cout<< “Enter age”;
Cin>>age;
If(age>=18)
{
Cout<<”you are eligible to vote”;
}
Else
{
Cout<<”you are Not eligible to vote”;
}
Getch()
Return 0;
}
Output:
Enter age : 20
You are eligible to vote

Nested if statement: An if statement having another if structure as part of statement


is called nested if structure.

if(<condition>)
{
Statement to be done;
if(<condition>)
{
Statement to be done;
}
}

Program to show nested if statement:

#include<iostream>
Using namespace
strd;
#include<conio.h>
Int main()
{
Int a, b, c;
Cout<<”Enter value for a, b, and c;
Cin>>a>>b>>c;
/* check the Boolean condition */
If(a == b)
{
/* if condition is true then check the following */
If(b == c)
{
/* if condition is true then print the following */
Cout<<”Value of a, b and c are equal\n”;
}
}
Getch()
Return 0;
}
Output :
Enter value for a, b, and c : 10 10 10
Value of a, b, and c are equal.

Nested if-else statement:​ An if structure can have one more if (if….else) structure
as a part of statement and even an else part of an if….else structure can also have
again an if…..else structure. This sort of building the if….else structure is called
Nested if….else structure.

Syntax:
If(<condition>)
{
Statement to be
done;
If(<condition>)
{
Statement to be done;
}
Else
{
Statement to be done;
}
}
Else
{
S
t
{ a
t
e
m
e
n
t
t
o
b
e
d
o
n
e
;
I
f
(
<
c
o
n
d
i
t
i
o
n
>
)
Statement to be
done;
Else
{
statement to be done;
}
}

Program to show Nested if-else statement :


#include<iostream>
Using namespace std;
#include<conio.h>
Main()
{
float A, B, C;
Cout<<”enter three values:;
Cin>> A >> B >> C;
If(A>B)
{
If(A>C)
Cout<<”largest value is : <<A;
Else
Cout<<”largest values is :”<<C;
}
Else
{
If(C>B)
Cout<<”largest values is : “<<C;
Else
Cout<<”largest value is : “<<B;
}
Getch()
Return 0;
}

Output:
Enter three values : 123 456 218
Largest value is : 456
If…else statement: If…else is structure is the other way of representing an if..else ..
if structure i.e, instead of using ‘if’ statement again in the else part of the else
structure we can use a single statement as ‘else’..if. this statement works exactly the
same as ‘if….else….if structure.

Syntax:
If(<condition>)
{
Statement to be done;
}
Else if(condition)
{
Statement to be done;
}

Switch statement:
The switch statement selects a particular statement from a group of
statement.
The selective depends upon the current value of the expression where the
expression result in an integer value, character value or any other data type. The
general form of the switch statement is

Switch(expression) statement
Case expression :
Statement 1
Statement 2
…………. ……..

Statement n

Or, when multiple case labels are required,


Case expression 1
Case expression 2:
…… …… …… ……
Case expression m:
Statement 1
Statement 2
Statement 3
Where expression 1 and expression 2,….., expression m represent constant , integer-
valued expression.

Program to show switch statement:


#include<iostream>
Using namespace std ;
#include<conio.h>
Main()
{
Char choice;
Cout<<”enter a charater (R/W/B);”;
Cin>>choice;
Choice = toupper(choice);
Switch (choice)
{
Case ‘R’ :
Cout<<”choice is white”;
Break;
Case ‘B’;
Cout<<”choice is blue”;
Break;
Default :
Cout<<”enter valid character;
}
Getch()
Return 0;
}

Output:
Enter character (R/W/B) : W
Choice white

Conditional statement: The conditional operator ? and : are sometime called


TERNARY OPERATOR since they take three argument at a time. An expression
that makes use of the conditional operator is called conditional expression.

Syntax:

Expression 1 ? expression 2 : expression 3


When evaluating, exp 1 is evaluated first, if exp 1 is true, then exp 2 is evaluated
and this becomes the value of the conditional expression. However, if expression 1 is
false, then ex[ 3 is evaluated and becomes the value of the conditional expression.

X = 16 are int variable


Y = (x>5 ? 3:4)

Program to show Conditional statement:


#include<iostream>
Using namespace std:
#include<conio.h>
Main()
{
Int x, y, larger ;
Cout<<”enter two number
:”; Cin>> x >>y;
Larger = (x>y) ? x : y;
Cout<<”largest number is : “<<larger;
Getch()
Return 0;
}
Output :
Enter two number : 10 30
Largest number is : 30

​ Iterative statement –

1.​ While: Iteration is the process where a set of instruction or statement is executed
repeatedly for a specified number of time or until a condition is met. If we want
to perform an action repeatedly to the different values of a variable, the while
loop is ideally used.

Syntax : while (condition)


{
Statement;
}
Program to show the usage of while loop :
#include<iostream>
Using namespace std;
#include<conio.h>
Int main()
{
Int num, result ;
Int count = 1;
Cout<<”Enter the number:”;
Cin>>num;
While (cout< = 10)
{
Result = num* count;
Cout<<num<<” * “ <<cout<< “ = “ <<result << endl;
Count = count+1
}
Getch ()
Return 0;
}

Output:
Enter the number: 5
5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 =20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50
2.​ Do-while statement:

The structure of do-while loop is similar to while loop. The difference is that in
case of do while loop the expression is evaluated after the body the loop is executed.
In case while loop the expression if evaluated before executing body of loop.

The general form of do while statement


Do
{
Statement;
}
While (expression);

In do while loop, first the statement is executed and then the expression tested. If
the expression evaluated to false, the loop terminates and the execution controls
transfer to the next statement.

Program to show usage of do-while loop :


#include<iostream>
Using namespace std;
#include<conio.h>
Int main()
{
Int sum, I, n;
Cout<<”Enter the value of n:”;
Cin>>n;
Sum = 0;
I = 1;
Do
{
Sum = sum + 1
I++;
}
While (I<=n);
Cout<<”Sum of first “<< n <<”number is “<<sum;
Getch()
Return 0;
}
Output:
Enter the number of n : 5
Sum of first 5 number is 15

In case of do-while loop, the statement is executed at least once, where as in case of
while loop, the statement may not executed at all if the expression result false for
the first time itself.

3.​ For – Statement:

The for loop is most common in major programming language. However, the for loop
in C language is very flexible and very powerful. The for loop is used to repeat the
execution of a statement for fixed number of times.
The general form of the for loop is

For(initialization; test – condition; increment)

{
Body of the loop
}

Execution process of the for loop statement is as follows:

​ Initialization of the controls variable is done first, using assignment statement


such as I = 1 and count = 0. The variable I and count are know as loop
control variable.
​ The value of the control variable is tested using the test-condition. The test-
condition is a relational expression, such as I < 10 that determine when
loop is terminated and the execution continues with the statement that
immediately follow the loop.
​ The body of the loop is executed the controls is transferred back to the for
statement after evaluating the last statement in the loop. Now, the control
variable is increment using an assignment the last statement such as I = i+1
and the new value of the control variable is again tested to see whether it
satisfies the loop condition.
▪​ If the condition is satisfied, the body of the loop is again executed. This
process continues till the value to the control variable fails to satisfy the test
condition.

Consider the following segment of a program:

For (x = 1; x < = 10; x = x + 1)


{
Cout<< x;
}

This for loop is executed 10 times and prints the digits 1 to 10 in one line.

Program to find the sum of 10 given number using for loop :


#include<iostream>
Using namespace std;
#include<conio.h>
Main()
{
Int number, I, sum = 0;
Cout<<”Enter values for 10 number :”;
For(I = 10;i<10;i++)
{
Cin>>number;
Sum = sum + number;
}
Cout<<”sum is “<< sum;
Getch ()
Return 0;
}

Output :
Enter values for 10 number : 1 2 3 4 5 6 7 8 9 10
Sum is 55

4.​ Jumping Statement – goto :


●​ C supports the goto statement to branch unconditionally from one point to
another in the program.
●​ The goto requires a label in order to identify the place where the branch is to
be made. A label is any valid variable name, and must be followed by a colon.
●​ If the label: is before the statement goto label: a loop will be formed and
some statement will be executed repeatedly. Such a jump is know as a
backward jump. On the other hand, if the label: is placed after the goto label:
some statement will be skipped and the jump is know as a forward jump.

Program to show the usage of goto statement:

#include<iostream>
Using namespace std;
#include<conio.h>
Main()
{
Double x, y;
Read;
Cout<<”enter number to get its square root :”;
Cin>> x;
If(x <=0) goto read;
Y = sqrt(x);
Cout<<”square root of “<< x << “ is “ << y;
Getch()
Return 0;
}
Output :
Enter the number to get its square root : 25
Square root of 25 is 5

5.​ Break statement :

The break statement is used to terminate loop or to exit from a switch


statement, it can be used within a for, while, do-while, or switch statement.6

Program to show the usage of Switch statement :


#include<iostream>
Using namespace std;
#include<conio.h>
Main()
{
Char choice;
Cout<<”Enter a character (R/W/B);
Cin>>choice;
Choice = toUpper (choice);
Switch (choice)
{
Case ‘R’;
Cout<<”choice is red”;
Break;
Case ‘W’;
Cout<<”choice is white ;
Break;
Case ‘B’;
Cout<<choice is blue;
Break;
Default :
Cout<<”Enter valid character:”;
}
Getch();
Return 0;
}

Output :
Enter a character (R/W/B): w
Choice is White

6.​ Continue Statement:

The continue statement is used to bypass the remainder of the current pass
through a loop. The loop does not terminate when a continue statement is
encountered.
Program to show the usage of continue statement:

#include<iostream>

Using namespace std;


#include<conio.h>
Main()
{
For(int n=5; n>0;n--)
{
If(n==3) continue;
Cout<< n<<”,”;
}
Cout<< “FIRE”;
Getch()
Return 0;
}
Output :
5, 4, 2, 1, FIRE!

7.​ Return statement:

The return statement terminates the execution of a function and return control
to the calling function.
Program to show the usage of return statement:

#include<iostream>
Using namespace std;
#include<conio.h>
Int addition (int a, int b)
{
Int r;
R =a+b;
Return r;
}
Int main()
{
Int z;
Z = addition (5, 3);
Cout<<”the result is “<< z;
Getch()
Return 0;
}
Output :
The result is 8

The main calls addition function with value 5 and 3. The addition function adds the
values add assign to variable r which is returned by the addition function to main().
In the main() the result is displayed..

8.​ Exit :

Exit() is a standard library function, which terminates program execution when it is


called. The general syntax of the exit() function is

Void exit(int return_code);

The value of return_code is returned to the calling process, so the success or failure
of the program can be tested by another program that uses this one as a sub-
process. Conventionally, a return value of 0 signal that is well; non-zero values
usually signal abnormal situation.
Program to show the usage of exit() :
#include<iostream>
Using namespace std;
#include<conio.h>
#include<stdlib.h>
Int main()
{
Cout<<”Start of the program…..”<<endl;
Cout<<”exiting the program…….”<<endl;
Exit (0);
Cout<<”end of the program……”endl;
Getch()
Return 0;
}

Output:
Start the program…..
Exiting the program……
​ Arrays:

​ Array is a collection of similar data type.

​ A single variable can hold only one value at a time, if we want a variable to
store more than one value of same type we use array.
​ Array is line data structure. It can store fixed number of values.

​ The below example shows representation of array is memory

Address of first element is random, address of next element depend upon the type of
array. Hence, the type is integer and integer takes two bytes in memory, therefore
every next address will increment by two. Index of array will always starts with zero.

Declaration of Array:
Declaration of array means creating sequential blocks of memory to hold fixed
number of values

Syntax: data-type array-name [size of array]

Example:
Int arrnum [5]; //statement 1
Float arrfloat [10]; //statement 2

Initialization of Array:
Initialization means assigning value of declared array.

Example 1:
Int arrnum [] = {78, 45, 12, 89, 56};

In the above example we are declaring an initializing an array at same time. When
we declare and initialize an array at same time, giving the size of array.
Program to show the usage of array:

#include<iostream>

Using namespace std;


#include<conio.h>
Int main()
{
Int arrnum [5]
Int I;
Cout<<”enter five number….” <<endl;
For(i=0; i<5; i++) // input array from user
{
Cout<<”enter value for number “ <<i+1 <<”:”;
Cin>>arrnum [i];
}
Cout<<”entered number are;
For(i=0; i<5; i++)​ //output array is console.
{
Cout<<arrnum [i]<<”:”;
}
Getch{}
Return 0;
}

Output :
Enter five number….
Enter value for number 1:78
Enter value for number 2:45
Enter value for number 3:12
Enter value for number 4:89
Enter value for number 5:56
Entered number are: 78, 45, 12, 89, 56

Strings:
A string is a collection of characters, stored in an array followed by null (‘\0’)
character. Null character represent the end of string.

Char strName[] = “Anil”

Address of first element is random, address of next element depend upon the
type of array. Here, the type is character and character takes one byte in memory,
therefore every next address will increment by one. Index of array will always with
zero.
Input string using cin function:
The cin can read the entire world at a time. The cin ignores the any occurrence
of leading whitespace character and terminate the string at the first occurrence of
whitespace after any input.
Program to show the usage of cin function to read a string:

#include<iostream>

Using namespace std;


#include<conio.h>
Int main()
{
Char string [50];
Cout<<”enter your name:”;
Cin>>string;
Cout<<”The string is:”<<string:
Getch()
Return 0;

Output:
Enter your name: Rohan Mathew
The string is: Rohan
In the output of above example we get only the string “Rohan” although the string
entered is “Rohan Mathew”, this is because cin ignores any occurrence of learning
whitespace character and terminate the string at the first occurrence of whitespace
after any input.

​ Input string using gets() function :

​ The gets() can read the entire line at a time and the string will not terminate
until user press the enter key. The gets() will put all the leading and trailing
whitespace into string.

Program to show usage of gets() function to read a string :

#include<iostream>
Using namespace std ;
#include<conio.h>
#include<stdio.h>
Int main()
{
Char string [50];
Cout<<”enter your name:”;
Gets(string);
Cout<<”the string is :”<<string;
Getch()
Return 0;
}

Output:
Enter your name: Rohan Mathew
The string is: Rohan Mathew

In the output of above example there is whitespace in the string gets() will put all
the leading and trailing whitespace into string.

​ Pointer :

●​ It is also know as locator or indicate that point to angle address of value.


●​ Suppose v is variable that represent some particular data item.
●​ The complier will automatically assign memory cells for this data item. The
data item can then be accessed if we know the location of the first memory
cell. *the address of v’s memory location can be determined by the expression
& v where & is a unary operator, called the address operator, that evaluates
the address of its operand.
●​ Where * is a unary operator, called the indirection operator, that operator
only on a pointer variable.

Program to show the usage of pointer to display element of an array:


Int number = 30;
Int* p;
P =& number ;
Cout<<”add of variable number is :”<<& number << endl;
Cout<<”add mof p variable is :”<<p<<endl;
Cout<<”value of p variable is:”<<*p<<endl;
Return 0;
}
Output:
Add of num variable: 00ff0203
Add of p variable: 00pf0203
Value of p variable is: 30

​ Searching and sorting arrays:

o​ Searching Array:

●​ We will find we often need to search for a value in a table of number. We want
to know the index of that value within that table, or even simply whether the
value is present.
●​ She want to check or search whether the entered number/element is present
in the array or not.

Program to show searching an element in an array:


#include<iostream>
Using namespace std;
#include<conio.h>
Int main()
{
Int arr[10], I, num, n, c=0, pos;
Cout<<”Enter the array size:”;
Cin>>n;
Cout<<”Enter array element:”;
For(i=0,i<n,i++)
{
Cin>>arr[i]
}
Cout<<”enter the number to be search :”;
Cin>>num;
For(i=0,i<n,i++)
{
If(arr[i] == num)
{
C = 1;
Pos = i+1;
Break;
}
}
If(c == 0)
{
Cout<<”Number not found :”;
}
Else
{
Cout<<num<<”found at position:<<”pos;
}
Getch()
Return 0;
}

Output:
Enter the array size: 5
Enter array element: 12 23 45 64 5
Enter the number to be search: 64
64 found at position: 4

​ Sorting Array:

​ One of the fundamental problem in computer science is ordering a list of item.

​ There are plenty of solution to the problem, commonly known as sorting


algorithms.
​ Bubble sort is the simplest sorting algorithms that work by repeatedly
swapping the adjacent element if they are in wrong order.

Program to show usage sorting element of an array:


#include<iostream>
Using namespace std;
#include<conio.h>
Int main()
{
Int arrElement[50], num, I, j , temp;
Cout<<”enter the size of array:”;
Cin>>num;
Cout<<”enter he array element :”;
For(i=0,i<num,i++)
Cin>>arrelement [i];
For(i=1, i<num, ++i);
{
For(j=0, j<(num-i); ++j)
If(arrelement[j]>arrelement[j+1])
{
Temp=arrelement[j]
Arrelement[j]=arrelement([j+1])
Arrelement[j+1]=temp;
}
}
Cout<<”array after bubble sort:”;
For(i=0;i<num;i++)
{
Cout<<””<<arrelement[i]
}
Getch()
Return 0;
}
Output :
Enter the size of array is: 8
Enter the array element: 24 54 12 87 41 39 6 78
Array after bubble sort: 6 12 24 39 41 54 78 87

You might also like