CPP Unit 2 N 3 Bcom
CPP Unit 2 N 3 Bcom
Formatted console input/output functions are used to take one or more inputs from the user at
console and it also allows us to display one or multiple values in the output to the user at the
console.
Functions Description
putchar()
Displays a single character value at the console.
In c programming language, there are two decision making statements they are as follows...
1. if statement
2. switch statement
Simple if statement
Simple if statement is used to verify the given condition and executes the block of statements
based on the condition result. The simple if statement evaluates specified condition. If it is
TRUE, it executes the next statement or block of statements. If the condition is FALSE, it skips
the execution of the next statement or block of statements. The general syntax and execution
flow of the simple if statement is as follows...
Simple if statement is used when we have only one option that is executed or skipped based on
a condition.
#include <stdio.h>
#include<conio.h>
void main()
{
int n ; clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n> 0 ) }
printf("Given number is natural number
") ; O/P: Enter any integer number: 4
getch(); Given number is natural number
if - else statement
The if - else statement is used to verify the given condition and executes only one out of the two
blocks of statements based on the condition result. The if-else statement evaluates the specified
condition. If it is TRUE, it executes a block of statements (True block). If the condition is
FALSE, it executes another block of statements (False block). The general syntax and execution
flow of the if-else statement is as follows...
The if-else statement is used when we have two options and only one option has to be executed
based on a condition result (TRUE or FALSE).
#include <stdio.h>
#include<conio.h>
void main(){
int year ;
clrscr() ;
printf("Enter year: ") ;
scanf("%d", &year) ;
if ( year%4 == 0 ) }
printf("Given year is leap year\n") ; Output :
else
printf("Given year is not leap year\n") ; Enter year: 2017
Given year is not leap year
Nested if statement
Writing a if statement inside another if statement is called nested if statement. The general
syntax of the nested if statement is as follows..
Like the name indicate, nested else if contains if statement inside an if statement. If we want to
check a condition even a condition is hold, then we use nested if.
#include <stdio.h> }
#include <stdlib.h> }
int main()
{ Output :
int n1 = 30,n2 = 20 ,n3 = 10;
if(n1 > n2) Largest is 30
{ Here n1(30) is greater than n2(20), so again
if(n1>n3) check with the value of n3(10). Then
{ decided a decision( printf("Largest is
printf("Largest is %d",n1); %d",n1); )
}
Writing a if statement inside else of a if statement is called if - else - if statement. The general
syntax of the if-else-if statement is as follows...
Example Program | Find the largest of three numbers.
#include <stdio.h>
#include<conio.h>
void main() {
int a, b, c ; clrscr() ;
printf("Enter any three integer numbers: ") ;
scanf("%d%d%d", &a, &b, &c) ;
if( a>b && a>c)
printf("%d is the largest number", a) ;
else if (b>a && b>c)
printf("%d is the largest number", b) ; Output :
else if(c>a && c>b)
printf("%d is the largest number", c) ; Enter any three integer numbers: 55 60 20
} 60 is the largest number
Using switch statement, one can select only one option from more number of options very
easily. In switch statement, we provide a value that is to be compared with a value associated
with each option. Whenever the given value matches with the value associated with an option,
the execution starts from that option. In switch statement every option is defined as a case.
The switch statement contains one or more number of cases and each case has a value
associated with it. At first switch statement compares the first case value with the switchValue,
if it gets matched the execution starts from the first case. If it doesn't match the switch statement
compares the second case value with the switchValue and if it is matched the execution starts
from the second case. This process continues until it finds a match. If no case value matches
with the switchValue specified in the switch statement, then a special case called default is
executed.
When a case value matches with the switchValue, the execution starts from that particular case.
This execution flow continues with next case statements also. To avoid this, we use "break"
statement at the end of each case. That means the break statement is used to terminate the
switch statement. However it is optional.
syntax break;
case 3:
Switch(expression) block 3;
{ break;
case 1: ……………………
block 1; ……………………
break; default:
case 2: }
block 2; Switch program example :
#include<stdio.h> #include <conio.h> case 2: printf("Two");
int main() { break;
int nmbr; case 3: printf("Three");
printf("Enter a number: "); break;
scanf("%d",&nmbr) ; default: printf("Number is not 1,2 or
switch(nmbr) 3");
{ }
case 1: printf("One"); getch(); }
break;
Loops provide a way to repeat a set of statements and control how many times they are
repeated.
C supports three looping statements.
Both while and for statements are called as entry-controlled loops because they evaluate the
expression and based on the value of the expression they transfer the control of the program
to a particular set of statements.
Do-while is an example of exit-controlled loop as the body of the loop will be executed once
and then the expression is evaluated.
In above syntax, the condition is checked first. If it is true, then the program control flow goes
inside the loop and executes the block of statements associated with it. At the end of loop
increment or decrement is done to change in variable value. This process continues until test
condition satisfies
For loop example program:
#include <stdio.h>
Void main()
{
int x;
for ( x = 0; x < =10; x++ )
{
printf( "%d\n", x );
}
getch();
}
o/p: 0 1 2 3 4 5 6 7 8 9 10
#include<stdio.h> #include<conio.h>
void main() {
int i; clrscr();
for(i=1; i<=10; i++)
{
if(i==5)
continue;
printf("%d",i);
}
getch();
}
o/p: 1 2 3 4 6 7 8 9 10
Example program for Continue :
2.5 Goto statement:
A goto statement is used to branch (transfer control) to another location in a program.
Syntax:
The label can be any valid identifier name and it should be included in the program followed by
a colon.
Example program
Output :
Hello World
Hope you are fine
Note : Break, continue ad goto statements are also called as jumping statements.
A loop inside another loop is called nesting of loops. There can be any number of
loops inside one another with any of the three combinations depending on the
complexity of the given problem. Let us have a look at the different combinations.
Syntax
outer_loop
{
inner_loop
{
// Inner loop statement/s
}
Nested for loop
for(initialization; condition; update)
{
// statements
for(initialization; condition; update)
{
// Inner loop statements
}
// statements
}
Nested while loop Nested do...while loop
while(condition) do
{ {
// statements // statements
while(condition) do
{ {
// Inner loop statements // Inner loop statements
} }
while(condition);
// statements
} // statements
}
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
C code
#include <stdio.h>
int main()
{
int i; //for outer loop counter
int j; //for inner loop counter
1. Till the inner loop condition fails the control iterates inside the inner loop, when inner
loop condition fails the control moves to the outer loop
2. When ever the control is moving from outer loop to inner loop the value
2.7.1 FUNCTIONS
Functions
Function means, a large program can be divided into a series of individual related
programs called modules. These modules are called functions.
function is set of program to perform some specific and well defined tasks.
a) Reusability: The function writes once and use many times is called Reusability.
b) Modular Program Approach: A large program is divided into smaller sub programs. so
that each sub program performs a specific task. This approach makes the program
development more manageable.
c) Efficiency: means by avoiding redundant instructions the size of program can be
reduced. Which increase efficiency of program.
d) Function sharing: A function can be shared by many programmers.
e) It is very easy to identify the logical errors and correct.
f) It is very easy to read and understand.
2.7.3 The functions can be classified into two categories. Or types of functions
Advantages :
1 : The programmer’s job is made easier because the functions are already available.
2 : The library functions can be used whenever required.
Disadvantages : The standared library functions are limited, programmes can not completely
on these library functions. The programmer has to write his own programs.
2 : User Defined Functions : These functions which are written by the programmer to do some
specific tasks are called User Defined Functions.
2 : Function Call : The function can be called by simply using the function name.
Syntax : function-name();
function-name(parameters);
return value = function-name(parameters);
3 : Function Definition : The program module that is written to achieve a specific task is called
function definition.
#include<stdio.h>
void add(); //function declaration/prototype
void main()
{
add(); //Function call
}
void add() // function definition
{ printf(“Enter the values of a and b”);
int a,b,c; scanf(“%d%d”,&a,&b);
c=a+b; Enter the values of a and b
printf(“the sum is %d”,c); 5
} 5
the sum is 10
output :
2.7.5 PARAMETERS : parameters provides the data communication between the calling
function and called function.
They are two types of parametes 1 : Actual parameters. 2 : Formal
parameters.
1 : Actual Parameters : These are the parameters transferred from the calling function
(main program) to the called function (function).
2 : Formal Parameters :These are the parameters transferred into the calling function (main
program) from the called function(function).
Ex : main()
{
fun1( a , b ); //Calling function / main fun
}
fun1( x, y ) //called function / user def fun
{
..... .
}
Where
a, b are the Actual Parameters
x, y are the Formal Parameters
1 : Local Variable : The local variables are defined within the body of the function or
block. These variables can access by that function only, other functions can not access these
ariables.
Ex : fun1(int a,int b)
{
int c,d; // Here c and d are the Local variable
}
2 : Global Variable : Global variables are defined outside the main() function and multiple
functions can use these variables.
Return Statement : The return statement may or may not send back any values to the calling
function(main program).
Syntax : return; // does not return any value
or
return(exp); // the specified exp value to calling function.
A function can contain more than one return statements, when the return value can return values
based on certain condition.
If a function can return some values other than int type, then we must specify the data
type to be return.
1 : In this category, there is no data transfer between the calling function and called function.
2 : But there is flow of control from calling function to the called function.
3 : When no parameters are there , the function cannot receive any value from the calling
function.
4: When the function does not return a value, the calling function cannot receive any value from
the called function.
Ex #include<stdio.h>
#include<conio.h>
void sum();
void main()
{
sum();
getch();
}
void sum() int a,b,c;
{
printf("enter the values of
a and b");
scanf("%d%d",&a,&b); Output :
c=a+b; enter the values of a and b
printf("sum=%d",c); 5
} 5
sum= 10
1 : In this category, there is no data transfer between the calling function and called function.
2 : But there is data transfer from called function to the calling function.
3 : When no parameters are there , the function cannot receive any values from the calling
function.
4: When the function returns a value, the calling function receives one value from the called
function.
Ex : #include<stdio.h>
#include<conio.h>
int sum();
void main()
{
int c;
clrscr();
c=sum();
printf("sum=%d",c);
getch();
}
int sum()
{
int a,b,c;
printf("enter the values of a Output :
and b”); enter the values of a and b
scanf("%d%d",&a,&b); 5
c=a+b; 5
return c; sum= 10
}
Ex : #include<stdio.h>
#include<conio.h>
void sum(int a,int b);
void main()
{
int m,n;
clrscr();
printf("Enter m and n values:");
scanf("%d%d",&m,&n);
sum(m,n);
getch();
}
1 : In this category, there is data transfer from the calling function to the called function using
parameters.
2 : But there is no data transfer from called function to the calling function.
3 : When parameters are there , the function can receive any values from the calling function.
4: When the function returns a value, the calling function receive a value from the called
function.
Ex : #include<stdio.h>
#include<conio.h>
int sum(int a,int b);
void main()
{
int m,n,c;
clrscr();
printf("Enter m and n values");
scanf("%d%d",&m,&n);
c=sum(m,n);
printf("sum=%d",c); }
getch();
} Output :
int sum(int a,int b) enter the values of a and b
{ 5
int c; 5
c=a+b; sum= 10
return c;
2.8 Recursion
A function that calls itself is known as a recursive function. And, this technique is known as
recursion.
void main()
{
recursion();
}
void recursion()
{
recursion(); /* function calls itself */
}
The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function,
otherwise it will go into an infinite loop.
Recursive functions are very useful to solve many mathematical problems, such as calculating
the factorial of a number
#include<stdio.h>
int factorial(int);
int main()
{
int factorial(int n);
int fact;
clrscr();
printf(“enter the number”);
scanf(“%d”,&n);
fact=factoria(n);
printf("factorial of a given number is %d",fact);
getch();
int factorial(n)
{
int fact;
if(n==1)
return 1;
else
fact=n*factorial(n-1);
return fact;
}
When ever we are using recursive functions in our programming there are some limitiations
1.The recursive functions may involve extensive overhead because they use function calls
repeatidly.
2.Whenever we make a call we need to use some separate memory allocations
3.If the program has a large number of recursive calls then we need to run the program may be
out of memory..
2.9 ARRAYS
Definition:
C supports a derived data type known as array that can be used to handle large amounts
of data (multiple values) at a time.
An array is a collection of elements of the same data type, which share a common name.
Array elements are always stored in contiguous memory locations.
Each element in the group is referred by its position called index.
The first element in the array is numbered 0, so the last element is one less than the size
of the array.
Before using an array its type and dimension must be declared, so that the compiler will
know what kind of an array and how large an array.
A list of items can be given one variable name using only one subscript and such a
variable is called one-dimensional array or single-dimensional variable.
datatype array-name[size];
The data-type specifies the type of elements such as int, float or char. And the size indicates the
maximum number of elements that can be stored in that array.
Eg:
int a[5] ; here a is an array containing 5 integer elements.
float height[10]; here height is array containing 10 real elements.
char name[20]; here name is an array containing 20 characters.
Note: C language character strings are as simple as array of characters. And every string
should be terminated by null character (‘\0’).
After an array is declared its elements must be initialized. Otherwise they will contain
garbage values. An array can be initialized at either of the following stages.
At compile time
At run time
Eg:
int a [ 6 ] = { 3, 5, 23, 28, 6, 11 }; will initialize the given values to array a.
C allows us to define the data in the form of table of items by using two-dimensional
arrays.
Eg: int a [ 3] [ 4 ] ; Here a is two dimensional array with row size 3 and column size 4.,
and the total elements we can store in this array a is 12 (i.e. 3 * 4 ).
Each dimension of the array is indexed from zero to its maximum size minus one; the
first index selects the row and the second index selects the column with in that row. Two
dimensional arrays are stored in memory as follows:
Eg:
o/p: 12 3 34
void main()
{
int arr[3][4];
int i, j, k;
printf("Enter array element");
for(i = 0; i < 3;i++)
{
for(j = 0; j < 4; j++)
{
scanf("%d", &arr[i][j]);
}
}
for(i = 0; i < 3; i++)
{
for(j = 0; j < 4; j++)
{
printf("%d", arr[i][j]);
}
}
}
#include<stdio.h>
void main()
{
int i;
int arr[3] = {2, 3, 4}; // Compile time array initialization
printf("%d %d %d \t",arr[0],arr[1],arr[2]);
}
o/p: 2 3 4
o/p: 2 3 4
Each character of the string occupies one-byte of memory. The characters of the string are stored in contiguous
memory locations.
Declaration of Strings:-
Reading Strings:
The input function scanf ( ) can be used with %s format specification to read a string.
Eg: char name[30];
scanf(“%s”, name);
The scanf() function to read single word.
So multi word strings can’t read by using scanf() function.
Operators can’t work with strings directly. So to manipulate strings we have a large number of string handling
functions in C standard library and the responsible header file is “string.h”. Some of those functions are:
strcpy ( ), strcmp ( ), strcat ( ), strlen ( ), strrev ( ) etc.
strcpy( ):- It is to copy one string into another, and it returns the resultant string.
Syntax: strcpy ( string1, string2);
String2 is copied into string1.
Eg: char city1[10] = “HYDERABAD”;
char city2[12] = “BANGLORE”;
strcpy (city1, city2);
Here city2 is copied into city1. So city1=“ HYDERABAD”andcity2=”BANGLORE”. The size of the array
city1 should be large enough to receive the contents of city2
strcmp( ):- It is to compare two strings to check their equality. If they are equal it returns zero, otherwise it
returns the numeric difference between the first non matching characters in the strings. (i.e. +ve if first one is
greater, -ve if first one is lesser).
Syntax: strcmp (string1, string2);
Eg: char city1[10] = “HYDERABAD”;
char city2[12] = “BANGLORE”;
strcmp (city1, city2);
Here city1 and city2 are compared, and returns the numeric difference between ASCII value of ‘H’ and ASCII
value of ‘B’ as they are not equal.
Strcmp(“RAM”,ROM”); It returns some –ve value.
Strcmp(“RAM”,RAM”): It returns 0 as they are equal.
strcat ( ):- This function is used to join two strings together, and it returns the resultant string.
Syntax: strcat ( string1, string2);
String1 is appended with string2 by removing the null character of string1 and string2 remains unchanged. The
resultant string is stored in string1.
Eg: char city1[10] = “HELLO”;
char city2[12] = “WORLD”;
strcat (city1, city2);
Here city2 is appended to city1. So city1= “HELLOWORLD” and city2=”WORLD”.
strlen( ):- It is to find out the length of the given string and it returns an integer value, that is the number of
characters in the given string. It takes only one parameter
Syntax: strlen ( string1);
It gives the length of string1.
Eg: char city[10] = “HYDERABAD”;
strlen (city); it gives the value 9.
strrev ( ):- This function is to find out the reverse of a given string.
Syntax: strrev (string);
Eg: char city[10] = “HYDERABAD”;
strrev (city); it give the string “DABAREDYH”
Built in functions :
C <ctype.h> header or C type functions or character type functions in c
The functions that operate on single-byte characters are defined in ctype.h header file
Header file <ctype.h> includes numerous standard library functions to handle characters (especially test
characters).
You will find various library functions defined under <ctype.h> for character handling
All C inbuilt functions which are declared in ctype.h header file are given below.
Function Description
Date functions in c
Time functions in C are used to interact with system time routine and formatted time outputs are
displayed. Example programs for the time functions are given below.
Function Description
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
time_t now;
time(&now);
#include<stdio.h>
#include<time.h>
int main()
time(&t);