0% found this document useful (0 votes)
8 views43 pages

C++ Looping and Array Concepts Explained

CPCT

Uploaded by

ramyabinu81
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views43 pages

C++ Looping and Array Concepts Explained

CPCT

Uploaded by

ramyabinu81
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

MODULE 2

Looping statements - for, while, do-while statements, Jump


statements – break, continue, goto, exit (). Arrays - single and
multi-dimensional arrays, initializing array elements, pointers &
arrays, Character arrays, string functions, Unformatted console I/O
functions, Unformatted Stream I/O function
Preparation of programs for evaluation of factorial of a number,
Infinite series, Sorting, Searching and Matrix manipulations.
Loop Control Statements:

 Repetitive execution of one or more statements is


called iteration commonly known as loop.
 A loop is simply a statement or collection of
statements that is executed repetitively until a certain
condition is reached, after which execution moves to
the next executable statements.
 Sometimes the required number of repetition is known
in advance. Sometimes it will not be known in
advance, the repetition then simply continues until a
condition has been satisfied.
Types of loop control statements in C++:
 Depending on the position of the control statement in the
loop, a control structures may be classified either as the
entry-controlled loop or as the exit-controlled loop.

 In the entry controlled loop, the control conditions are


tested before the start of the loop execution. If the
conditions are not satisfied, then the body of the loop will
not be executed.
 In the case of an exit controlled loop, the test is performed
at the end of the body of the loop and therefore the body of
the loop is executed unconditionally for the first time.

Loops are used in programming to repeat a specific block


until some end condition is met. There are 3 types of loop
control statements. They are,
i. for
ii. while
iii. do-while
(i)The for loop
The for loop is designed to iterate a number of times. It is an
entry controlled loop.
Syntax of for
for (initialization;condition; increment)
{
statement;
}
How for loop works?

1. The initialization statement is executed only once at the


beginning.
2. Then, the terminating condition is evaluated.
3. If the terminating condition is false, for loop is terminated.
But if the terminating condition is true, codes inside body
of for loop is executed and update expression is updated.
4. Again, the terminating condition is evaluated and this
process repeats until the terminating condition is false.
Eg: program to print number from 1 to 10
Output
#include <iostream> 1
2
using namespace std; 3
void main() 4
{ 5
int i; 6
7
for(i=1;i<=10;i++) 8
{ 9
cout<<”\n”<<i; 10
}
}
WRITE A C++ PROGRAM FOR 2’S MULTIPLICATION TABLE USING
FOR STSTEMENT

Eg:
2*1=2
2*2=4
.
.
.
2*10=20
OUTPUT:
#include <iostream> 2*1=2
2*2=4
.
.
.
using namespace std;
void main()
{
int i;
for(i=1;i<=10;i++)
{
cout<<”\n”<<”2*”<<i<<”=”<<2*i;
}
}

IMP:::Eg: program to print sum of first 10 natural


numbers 1+2+3+…+10

#include <iostream>
Output
using namespace std; Total sum=55
void main()
{
int i,sum=0;
for(i=1;i<=10;i++)
{
sum=sum+i;
}
cout<<”Total sum=”<<sum;
}
IMP:::Eg: program to find factorial of 10
#include <iostream>
Output
using namespace std; Factoral=3628800
void main()
{
int i,sum=1;
for(i=1;i<=10;i++)
{
sum=sum*i;
}
cout<<”Factorial=”<<sum;
}
Nesting of for loops: -
Nesting of for loop means one for statement within another
for statement. For example:

1. Print the following pattern: -


*
**
***
****
#include <iostream.h>
void main()
{
int row, col;
for ( row = 1; row <= 4; row++)
{
for ( col = 1; col <= row; col++)
{
cout<<”*\t”;
}
cout<<“\n”;
}
}
2. Print the following pattern: -
1
22
333
4444

#include <iostream.h>
void main()
{
int row, col, i=1;
for ( row = 1; row <= 4; row++)
{
for ( col = 1; col <= row; col++)
{
cout<<”\t”<<i;
}
i++;
printf (“\n”);
}
}

(ii)The while loop

The simplest kind of loop is the while-loop. It is an entry


controlled loop.
Syntax of while
while (condition)
{
statement;
}
How while loop works?
The while loop evaluates the condition. If the condition is
true (nonzero), codes inside the body of while loop are executed.
Condition is evaluated again. The process goes on until the
condition is false. When the condition is false, the while loop is
terminated.

Eg: program to print number from 1 to 10

#include <iostream>
using namespace std; Output
1
void main() 2
{ 3
int i=1; 4
5
while(i<=10) 6
{ 7
cout<<”\n”<<i; 8
i++; 9
10
}
}
Eg: program to print sum of first 10 natural numbers

#include <iostream>
Output
Total sum=55
using namespace std;
void main()
{
int i=1,sum=0;
while(i<=10)
{
sum=sum+i;
i++;
}
cout<<”Total sum=”<<sum;
}
Eg: program find factorial of 5

#include <iostream>
Output
using namespace std; factorial=120
void main()
{
int i=1,sum=1;
while(i<=5)
{
sum=sum*i;
i++;
}
cout<<”factorial=”<<sum;
}
(iii) Do….while loop
The do..while loop is similar to the while loop with
one important difference. The body of do...while loop is
executed once, before checking the test expression. Hence,
the do...while loop is executed at least once.
Syntax of do…while
do
{
// statements
}
while (condition);
How do…. while loop works?

The code block (loop body) inside the braces is executed


once. Then, the test expression is evaluated. If the test
expression is true, the loop body is executed again. This
process goes on until the test expression is evaluated to 0
(false).When the test expression is false (nonzero), the
do...while loop is terminated.

Eg: program to print number from 1 to 10


Output
#include <iostream> 1
using namespace std; 2
void main(){ 3
4
int i=1; 5
do 6
{ 7
8
cout<<”\n”<<i; 9
10
i++;
}
while(i<=10);
}
Eg: program to print sum of first 10 natural numbers

#include <iostream>
Output
using namespace std; Total sum=55
void main()
{
int i=0,sum=0;
do
{
sum=sum+i;
i++;
}
while(i<=10);
cout<<”Total sum=”<<sum;
}
do-while while
It is exit controlled loop It is entry controlled loop
The loop executes the loop executes the statement
statement at least once only after testing condition
The condition is tested before The loop terminates if the
execution. condition becomes false.
Do while (condition)
{ {
// statements statement;
} }
while (condition);

WRITE A C++ PROGRAM FOR 2’S MULTIPLICATION TABLE


Eg:
2*1=2 while (condition)
2*2=4 {
. statement;
.
.
}
2*10=20
OUTPUT:
#include <iostream> 2*1=2
using namespace std; 2*2=4
.
void main() .
{ .
.2*10=20
int i=1;
while(i<=10)
{
cout<<”\n”<<”2*”<<i<<”=”<<2*i;
i++;
}
}

JUMP STATEMENTS – BREAK, CONTINUE,


GOTO, EXIT ()

Unconditional branching include: -


 break
 continue
 goto
 exit()
Syntax of break
break;
The break statement enables a program to skip over part of
the code. A break statement terminates the smallest enclosing
while, do-while, for, or switch statement. Execution resumes at
the statement immediately following the body of the terminated
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

#include <iostream>
using namespace std;
void main() Output
{ 1
int i; 2
3
for(i=1;i<=10;i++) 4
{
if(i==5)
{
break;
}
cout<<i;
}
}

continue
o During the loop operations, it may be necessary to
skip a part of the body of the loop under certain
conditions.
o The continue statement tells the compiler, skip the
following statements and continue with the next
iteration.
continue;
The continue is another jump statement like the break
statement as both the statements skip over a part of the code. But
the continue statement is somewhat different from break. Instead
of forcing termination, it forces the next iteration of the loop to
take place, skipping any code between
#include <iostream>
using namespace std;
void main()
{
int i;
for(i=1;i<=10;i++)
{
Output
if(i==5) 1
{ 2
continue; 3
} 4
6
cout<<i; 7
} 8
} 9
10
exit()
 This function causes immediate and normal
termination of the program.
 The exit() needs the header file stdlib.h

#include <iostream.h>
#include<stdlib.h>
using namespace std;
void main()
{
int i;
for(i=1;i<=10;i++)
{
if(i==5)
{
exit();
}
cout<<i;
}
}
goto statement: -
o It is used to branch unconditionally from one point to
another
o The goto required a label in order to identify the place
where the branch is to be made.
o A label is a valid variable name and followed by a
colon
o The general form of a goto statement is: -
Forward Backward
goto label; label:
……….. ………….
……….. …………
label: goto label;

Consider the example: - Enter 2 numbers


void main() 3
{ 4
int a,b,c; 7
Enter 2 numbers
x:
2
cout<<”Enter 2 numbers”;
3
cin>>a>>b; 5
c=a+b; .
cout<<c; .
goto x; .
}

void main()
{
int a,b,c;
goto x; Output:
hai
cout<<”Enter 2 numbers”;
cin>>a>>b;
c=a+b;
cout<<c;
x:
cout<<”hai”;
}

Arrays
C++ provides a data structure, the array, which stores a
fixed-size sequential collection of elements of the same type.
An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the
same type.
Definition: An array is a collection of variables of the same
type that are referred to by a common name.

Instead of declaring individual variables, such as number0,


number1, ..., and number99, you declare one array variable such
as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables. A specific
element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The
lowest address corresponds to the first element and the highest
address to the last element. There are 2 types of array
 One dimensional (1D)
 Multi dimensional
One dimensional (1D)
Syntax:
Datatype arrayName [ arraySize ];
Type specifies the type of elements that will be contained
in the array and size specifies the maximum number of elements
that can be stored inside the array.
Eg: int a[5];
a[0]
a[1]
a[2]
a[3]
a[4]

eg: double balance[10];


The general form of initialization of arrays is:
Type arrayname[size]={list of values};
The values in the list are separated by comma. The number of
values between {} are cannot be larger than the size required for
the array. If the elements are lesser than the size, the remaining
elements will be set to be zero, if the array type is numeric and
NULL(\0) if the type is char.
Eg: int a[10]={2,17,4,9,36,10,28,3};

a[0] 2
a[1] 17
a[2] 4
a[3] 9
a[4] 36
a[5] 10
a[6] 28
a[7] 3
a[8] 0
a[9] 0

char b[10]=”well done”;


b[0] ‘w’
b[1] ‘e’
b[2] ‘l’
b[3] ‘l’
b[4] ‘’
b[5] ‘d’
b[6] ‘o’
b[7] ‘n’
b[8] ‘e’
b[9] ‘\0’
int age[5]={22,25,30,32,35};
int scores[10] = {1, 3, 4, 5, 1, 3, 2, 3, 4, 4};
char alphabet[5] = {’A’, ’B’, ’C’, ’D’, ’E’};
C++ program to store and print 5 elements in an array
#include <iostream>
using namespace std;
void main()
{ numbers[0]=10
int numbers[5]={10,20,30,40,50}; numbers[1]=20
int i; numbers[2]=30
for ( i = 0; i< 5; ++i) numbers[3]=40
{ numbers[4]=50
cout<< numbers[i]; 10 20 30 40 50
}
}
or
#include <iostream>
using namespace std;
void main()
{
int numbers[5], i;
cout<< "Enter 5 numbers: "; Output
Enter 5 numbers
for ( i = 0; i< 5; ++i) 23
2
67
5
10
{
cin>> numbers[i];
}
for ( i = 0; i< 5; ++i)
{
cout<< numbers[i];
}
}
C++ program to store and calculate the sum of 5 numbers
entered by the user using arrays.
#include <iostream> Output
Enter 5 numbers: 3
using namespace std; 4
5
int main() 4
2
{ Sum = 18
int numbers[5], sum = 0;
cout<< "Enter 5 numbers: ";
for (int i = 0; i< 5; ++i)
{
cin>> numbers[i];
sum=sum+numbers[i];
}
cout<< "Sum = " <<sum;
return 0;
}
Program to print the numbers in reverse order: -
#include<iostream.h>
void main( )
{
int a[30], n, i;
cout<<“ Enter the limit:”;
cin>>n;
cout<< “ Enter the elements:”; Enter the limit:
4
Enter the elements:
for ( i=0; i<n; i++)
{
cin>>a[i];
}
cout<<“ The reverse order is”;
for ( i=n-1; i>=0; i--)
{
cout<<a[i]<<”\n”;
}
}

Multidimensional Arrays
The general form of a multidimensional array declaration–

type name[size1][size2]...[sizeN];

int threedim[5][10][4];

Two-Dimensional Arrays
The simplest form of the multidimensional array is the two-
dimensional array. Two-dimensional (2D) arrays are indexed by
two subscripts, one for the row and one for the column.
Type arrayName [ x ][ y ];
A two-dimensional array can be think as a table, which will
have x number of rows and y number of columns. A 2-
dimensional array a, which contains three rows and four
columns can be shown as below –
Eg:
int a[3][4];
Thus, every element in array a is identified by an element
name of the form a[i ][ j ], where a is the name of the array, and
i and j are the subscripts that uniquely identify each element in
a.
Initializing Two-Dimensional Arrays
An element in 2-dimensional array is accessed by using the
subscripts, i.e., row index and column index of the array.
For example −
int a[2][3]={1,5,8,4,9,6};

1 5 8
4 9 6

PROGRAM TO STORE AND DISPLAY MATRIX


ELEMENTS
#include<iostream> Output
using namespace std; Enter the matrix elements row-
void main() wise :
{ 2 a[0][0]
3
int mat[3][3]; 4
int i, j; 5
6
cout<< "Enter the matrix elements row-wise : "; 7
for ( i = 0; i< 3; i++ ) //R i=3,j=3 8
9
{ 1
for ( j = 0; j < 3; j++ ) //C You have entered the matrix
234
{ 567
cin>> mat[i][j]; 891

}
}
cout<< "You have entered the matrix : ";
for ( i = 0; i< 3; i++ )
{
for ( j = 0; j < 3; j++ )
{
cout<< mat[i][j];
}
cout<< “\n”;
}
}
PROGRAM TO STORE AND DISPLAY TRANSPOSE
MATRIX
#include<iostream> Output
using namespace std; Enter the matrix elements row-
void main() wise :
{ 2 a[0][0]
3
int mat[3][3]; 4
int i, j; 5
6
cout<< "Enter the matrix elements row-wise : "; 7
for ( i = 0; i< 3; i++ ) //R 8
9
{ 1
for ( j = 0; j < 3; j++ ) //C You have entered the matrix
234
{ 567
cin>> mat[i][j]; 891

} 2 5 8
3 6 9
} 4 7 1
cout<< "You have entered the matrix : ";
for ( i = 0; i< 3; i++ )
{
for ( j = 0; j < 3; j++ )
{
cout<< mat[i][j];
}
cout<< “\n”;
}
cout<< "Transpose : ";
for ( i = 0; i< 3; i++ )
{
for ( j = 0; j < 3; j++ )
{
cout<< mat[j][i];
}
cout<< “\n”;
}

//Program for matrix addition


123 321 4 4 4
231 432 6 6 3
432 231 6 6 3
A B C

#include<iostream>
using namespace std;
void main()
{
int A[3][3],B[3][3],C[3][3],i,j;
cout<<"Enter the elements of First matrix";
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cin>>A[i][j];
}
}
cout<<"Enter the elements of Second matrix";
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cin>>B[i][j];
}
}
cout<<"Resultant matrix is";
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
C[i][j] =A[i][j]+B[i][j];
cout<<C[i][j]<<"\t";
}
}
}
0 1 2 3 4 5 6 7 8 9
10 70 80 20 90 60 30 50 40 0
10 70 80 20 90 60 30 50 40 0
10 70 80 20 90 60 30 50 40 0
10 70 20 80 90 60 30 50 40 0
10 70 20 80 90 60 30 50 40 0
10 70 20 80 60 90 30 50 40 0
10 70 20 80 60 30 90 50 40 0
10 70 20 80 60 30 50 90 40 0
10 70 20 80 60 30 50 40 90 0
10 70 20 80 60 30 50 40 0 90
10 20 70 60 30 50 40 0 80 90
.
.
.

WAP to sort an array of numbers/Bubble sort


#include<iostream>
using namespace std;
int main()
{
int i,j,a[20],n,temp,index,x;
cout<<"enter the number of elements in the array:";
cin>>n;
Output
cout<<"enter the elements: ";
enter the number of elements in the array:10
for(i=0;i<n;i++) enter the elements: 10 70 80 20 90 60 30 50 40 0
{
sorted array is:0 10 20 30 40 50 60 70 80 90
cin>>a[i];
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1;j++) I=0 j=2
{
if(a[j]>a[j+1]) A[2]=80
{ A[3]=20
temp=a[j]; Temp=80
a[j]=a[j+1]; A[2]=20
a[j+1]=temp; A[3]=80
}
}
}
cout<<"sorted array is:";
for(i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
}
Q. Linear Search/ Simply Search

10 70 80 20 90 60 30 50 40 0
Key=90
#include<iostream>
using namespace std;
void main( )
{
int n,x,A[20],i,flag=0;
cout<<"Enter the size of the
array"; cin>>n;
cout<<"Enter the
elements:"; for(i=0;i<n;i+
+)
{
cin>>A[i];
}
cout<<"Enter the element to
search"; cin>>x;
for(i=0;i<n;i++)
{
if(A[i]==x)
{
flag=1;
break;
}
}
if(flag==1)
{
cout<<"the element found at position "<<i;
}
else
{
cout<<"Element not found";
}
}
Q. wap to find selection sort

0 1 2 3 4 5 6 7 8 9
0 10 30 80 90 70 60 50 40 20

0 10 20 30 40 50 60 70 80 90
#include<iostream>
using namespace std;
void main( )
{
int n,A[20],i,j,min,p;
cout<<"Enter the size of the array";
cin>>n;
cout<<"Enter the elements:";
for(i=0;i<n;i++)
{
cin>>A[i];
}
for(i=0;i<=n-2;i++)
{
min=A[i];
p=i;
for(j=i+1;j<=n-1;j++)
{
if(A[j]<min)
{
min=A[j];
p=j;
}
}
A[p]=A[i];
A[i]=min;
}
cout<<”sorted elements”;
for(i=0;i<=n-1;i++)
{
cout<<A[i];
}
}
Q. Matrix Multiplication
00*00+01*10+02*20
123 321 1*3+2*4+3*2 1*2+2*3+3*3 1*1+2*2+3*1
231 432
432 231
A B C

#include<iostream>
using namespace std;
void main()
{
int A[3][3],B[3][3],C[3][3],i,j,k;
cout<<"Enter the elements of First
matrix"; for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cin>>A[i][j];
}
}
cout<<"Enter the elements of Second
matrix"; for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cin>>B[i][j];
}
}
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
C[i][j]=0 ;
for(k=0;k<3;k++)
{
C[i][j]=C[i][j]+ A[i][k]*B[k][j] ;
}
cout<<C[i][j]<< "\t" ;
}
}
}
FACTORIAL OF A NUMBER

#include <iostream>
using namespace std;
void main()
{
int n;
int factorial = 1;
cout << "Enter a positive integer: ";
cin>> n;
for(int i = 1; i<=n; ++i)
{
factorial=factorial*i;
}
cout <<factorial;
}
Q. Infinite series
1.
//infinite series 1+1/2 +1/3+ ....1/n
#include<iostream>
using namespace std;
void main()
{
int n;
float i,sum=0;
cout<<"Enter the number of terms:";
cin>>n;
for(i=1;i<=n;i++)
{
sum=sum+(1/i);
}
cout<<"Sum of the series is: "<<sum;
}
2.
//infinite series 1/2 + 1/22 +1/23+ ....1/2n
½+1/4+1/8+1/16+…+

#include<iostream>
using namespace std;
void main()
{
int n;
float i,sum=0,term=1;
cout<<"Enter the number of terms:";
cin>>n;
for(i=1;i<=n;i++)
{
term=term*2;
sum=sum+float(1/term);
}
cout<<"Sum of the series is: "<<sum;
}
3.
//infinite series 1+ 1/2! +1/3!+ ....1/n!
#include<iostream>
using namespace std;
void main()
{
int n;
float i,sum=0,term=1;
cout<<"Enter the number of terms:";
cin>>n;
for(i=1;i<=n;i++)
{
term=term*i;
sum=sum+float(1/term);
}
cout<<"Sum of the series is: "<<sum;
}
4.
//infinite series 1+ 2/2! +3/3!+ ....n/n!
#include<iostream>
using namespace std;
void main()
{
int n;
float i,sum=0,term=1;
cout<<"Enter the number of terms:";
cin>>n;
for(i=1;i<=n;i++)
{
term=term*i;
sum=sum+float(i/term);
}
cout<<"Sum of the series is: "<<sum;
}

5.
//infinite series ex= 1+ x+ x2/2! +x3/3!+ ....xn/n!
#include<iostream>
using namespace std;
void main()
{
int n;
float i,x,sum=1,term=1;
cout<<"Enter the number of
terms:";
cin>>n;
cout<<"Enter the value of x:";
cin>>x;
for(i=1;i<=n;i++)
{
term=term*(x/i);
sum=sum+term;
}
cout<<"Sum of the series is: "<<sum;
}
Q) 12 +2 2 +32 +. . .+ n2
#include<iostream>
using namespace std;
void main()
{
int n,I,sum=1;
cout<<"Enter the number of
terms:";
cin>>n;
for(i=1;i<=n;i++)
{
sum=sum+(i*i);
}
cout<<"Sum of the series is: "<<sum;
}

Binary search

2 3 5 7 8 10 12 15 18 20 34
#include<iostream>
using namespace std;
void main( )
{
int n,a[20],i,f,key,l,m;
cout<<"Enter the size of the
array"; cin>>n;
cout<<"Enter the
elements:"; for(i=0;i<n;i+
+)
{
cin>>a[i];
}
cout<<"Enter the element to
search"; cin>>key;
f=0;
l=n-1;
m=(f+l)/2;
while(f<=l)
{
if(a[m]<key)
{
f=m+1;
}
else if(a[m]==key)
{
cout<<key<<”found”;
break;
}
else
{
l=m-1;
}
m=(f+l)/2;
}
if(f>l)
{
cout<<”not found”;
}
}
Pointers
A pointer is a variable whose value is the address of
another variable. Pointers are used in C program to access the
memory and manipulate the address. Every variable is a memory
location and every memory location has its address defined
which can be accessed using ampersand (&) operator which
denotes an address in memory.
int s=5;
s Variable name
5

Value
2000 location address
Declaration of Pointer
data_type *pointer_variable_name;
int *p;
Above statement defines, p as pointer variable of type int,
that means p can hold the address of a integer variable.
Eg:
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch // pointer to character
Points to be Noted
 Normal variable stores the value whereas pointer variable
stores the address of the variable.
 & symbol is used to get the address of the variable.
Ex: int *p,a; //declaring a pointer variable p and normal variable a
of type int
p= &a; // Address of a is assigned to p
cout<<*p; // p is pointing to a, so *p will contain value of a

 symbol is used to get the value of the variable that the


pointer is pointing to (here p is pointing to a, so *p will
contain value of a.

#include<iostream> Output
using namespace std; value of q is 50
void main() value of q is 50
{ value of ptr is 3000
int *ptr, q;
q = 50;
ptr = &q; //address of q is assigned to ptr
cout<<" value of q is "<< *ptr; //printing value of q using ptr
cout<<"\n value of q is "<< q;
cout<<"\n value of ptr is "<<ptr;
}
Sum of 2 numbers using pointers
#include<iostream> Output

using namespace std; enter 2 numbers


5
void main() 7
{ 13
int *p,*q, a, b, sum;
cout<<"enter 2 numbers :";
cin>>a>>b;
p=&a; // address of a is assigned to p
q=&b; // address of b is assigned to q
sum= *p + *q; //*p contain value of a and *q contains value of b
cout<<sum;
}

String operations
C++ support sting handling function through string.h header file.
1. Concatenation
The function strcat() joins or concates two strings together.

strcat(string1,string2);
The string2 is append to string1 after removing the null
character at the end of the string1.
#include<iostream.h>
#include<string.h>
using namespace std;
void main()
{
string s1=”hello”; Output:
string s2=”hai”; hellohai
strcat(s1,s2);
cout<<s1;
}
2. Comparison
The function strcmp() is used to compare two strings given
as arguments. if both are same value zero is return.
Otherwise return value is the numeric difference between
the first non-matching characters.

strcmp(string1,string2);
str1 < str2 Returns –ve value

str1 == str2 Returns 0(Zero)

str1 > str2 Returns +ve value

#include<iostream.h>
#include<string.h>
using namespace std;
void main() Output:
{ 4
string s1=”hello”;
string s2=”hai”;
int n=strcmp(s1,s2);
cout<<n;
}
3. Copy
The function strcpy() copies on e string to another.
strcpy(string1,string2);
String2 is copied to the string variable string1.
#include<iostream.h>
#include<string.h>
using namespace std;
void main()
{
string s1=”hello”;
string s2; Output:
strcat(s2,s1); hello
cout<<s2;
}
4. Length
The function strlen() counts and return the number of
characters in a string
n=strlen(string);
Where n is an integer variable which receives the length of
string.
#include<iostream.h>
#include<string.h> Output:
using namespace std; 5
void main()
{
string s1=”hello”;
int n=strlen(s1);
cout<<n;
}
5. Upper/lower case
The function strupr() & strlwr() convert a string to upper
or lower case.
strupr(string);
strlwr(string);

#include<iostream.h>
#include<string.h> Output:
using namespace std; hello
void main() HELLO
{
string s1=”Hello”;
cout<<strlwr(s1);
cout<<strupr(s1);
}
The standard C++ library is iostream and standard input / output
functions in C++ are:
1. cin
2. cout

There are mainly two types of consol I/O operations form:

1. Unformatted consol input output


2. Formatted consol input output

1) Unformatted consol input output operations


These input / output operations are in unformatted mode. The following
are operations of unformatted consol input / output operations:

get()
It is a method of cin object used to input a single character from
keyboard.

[Link]();
#include<iostream>
using namespace std;
A
void main() A
{
char c=[Link]();
cout<<c;
}

put()

It is a method of cout object and it is used to print the specified character


on the screen or monitor.

put(variable / character);
A
#include<iostream> A
c
using namespace std;
void main()
{
char c=[Link]();
[Link](c); //Here it prints the value of variable c;
[Link]('c'); //Here it prints the character 'c';
}

getline(char *buffer,int size)

This is a method of cin object and it is used to input a string with


multiple spaces.
[Link](char *buffer,int
size)
#include<iostream> Enter name:
Neethumol
using namespace std; Neethumol
void main()
{
cout<<"Enter name :";
char c[10];
[Link](c,10); //It takes 10 charcters as input;
cout<<c;
}

write(char * buffer, int n)

It is a method of cout object. This method is used to read n character


from buffer variable.

[Link](char * buffer, int n)

#include<iostream>
using namespace std; Enter name:
Neethumolm
void main() Neethumol
{
cout<<"Enter name : ";
char c[10];
[Link](c,10);
[Link](c,9);
}
cin

It is the method to take input any variable / character / string.

cin>>variable;
#include<iostream>
using namespace std; Enter value:
23
void main()
{
int a;
cout<<”enter a value”;
cin>>a;
}
cout

This method is used to print variable / string / character.

cout<< variable;

#include<iostream>
using namespace std; Enter value:
23
void main() 23
{
int a;
cout<<”enter a value”;
cin>>a;
cout<<a;
}
2) Formatted console input output operations

In formatted console input output operations we uses following


functions to make output in perfect alignment. These functions are
available in header file <iomanip>. iomanip refers input output
manipulations.

width(n)

This function is used to set width of the output.

cout<<setw(int n);
#include<iostream>
#include<iomanip> 10

using namespace std;


void main()
{
int x=10;
cout<<setw(20)<<x;
}

fill(char)

This function is used to fill specified character at unused space.


setfill('character')

#include<iostream>
#include<iomanip> ##################10
using namespace std;
void main()
{
int x=10;
cout<<setw(20);
cout<<setfill('#')<<x;
}

precison()

This method is used for setting floating point of the output.

setprecision(n)
#include<iostream>
#include<iomanip>
using namespace std;
void main()
{
float x=10.12345;
cout<<setprecision(5)<<x;
}

You might also like