0% found this document useful (0 votes)
16 views62 pages

Unit-II NOTEScontrolstructure Excercises

unit-2 c++

Uploaded by

sophin
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)
16 views62 pages

Unit-II NOTEScontrolstructure Excercises

unit-2 c++

Uploaded by

sophin
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
You are on page 1/ 62

1

Write a program in C++ Program to swap two numbers without third variable
#include <iostream>
using namespace std;
int main()
{
int a=5, b=10;
cout<<"Before swap a= "<<a<<" b= "<<b<<endl;
a=a*b; //a=50 (5*10)
b=a/b; //b=5 (50/10)
a=a/b; //a=10 (50/5)
cout<<"After swap a= "<<a<<" b= "<<b<<endl;
return 0;
}

Control statements
 The flow of execution of statements in a program is called as control.
 Control statement is a statement which controls flow of execution of the
program.
 Control statements are classified into following categories.
1.Decision making statements
2.Looping statements

1. Decision making statements


 These statements are used to control the flow of execution of a program by
making a decision depending on a condition, hence they are named as decision
making statements.
 Decision making statements are of four types
a) if statement
b) switch
c) Conditional operator
d) Go to

(a) if Statement
 The if statement is the powerful decision making statement, and is used to
control the flow of execution of statements.
 It is basically a two-way decision making statement, and is used with an
expression
 if statement is used to test the condition.
 There are various types of if statements in C++.
 Simple if statement
 if-else statement
 nested if …else statement
 if-else-if ladder

(i)Simple if statement
 Here, test condition after evaluation will be either true or false.
 if the value is true then it will execute the block of statements below it otherwise the
statement block will be skipped and the execution will jump to the statement-x .
 the statement block may be a single statement or a group of statements.
 If we do not provide the curly braces ‘{‘ and ‘}’ after if(condition) then by default if
statement will consider the first immediately below statement to be inside its block..
 When the condition is true, both the statement-block and statement-x are executed
in sequence.
Syntax:
if(test condition)
{
//statement block
}
statement-x;
flowchart

Example program

#include <iostream.h>
int main ()
{
int num = 10;
if (num % 2 == 0)
{
cout<<"It is even number";
}
return 0;
}

Example: Program to print positive number entered by the user.If the user
enters a negative number, it is skipped

#include <iostream.h>
int main() {
int number;
cout << "Enter an integer: ";
cin >> number;
// checks if the number is positive
if (number > 0) {
cout << "You entered a positive integer: " << number << endl;
}
cout << "This statement is always executed.";
return 0;
}

Output 1
Enter an integer: 5
You entered a positive number: 5
This statement is always executed.
Output 2
Enter a number: -5
This statement is always executed

Example2:Find Largest Number Using if Statement


#include <iostream.h>
#include<conio.h>
void main()
{
float n1, n2, n3;
clrscr();
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if(n1 >= n2 && n1 >= n3)
cout << "Largest number: " << n1;
if(n2 >= n1 && n2 >= n3)
cout << "Largest number: " << n2;

if(n3 >= n1 && n3 >= n2)


cout << "Largest number: " << n3;
getch();
}

(ii)if-else Statement
 The if-else statement is an extension of the simple if statement.
 The C++ if-else statement also tests the condition.
 If the test expression is true, then the true block statements are executed. Otherwise
false-block statements are executed.
 After execution of true-block or false-block statements, the control is transferred
subsequently to statement-x.
 It executes if block if condition is true otherwise else block is executed.
syntax
if(test expression)
{
true-block statements;
}
else
{
false-block statements;
}
Statement-x

flowchart

If-else Example
#include <iostream.h>
int main () {
int num = 11;
if (num % 2 == 0)
{
cout<<"It is even number";
}
else
{
cout<<"It is odd number";
}
return 0;
}

iii)IF-else-if ladder Statement


 Another way of putting ifs together when multipath decisions are involved.
 The C++ if-else-if ladder statement executes one condition from multiple statements.
 It takes the following general form.
if(condition-1)
{
//code to be executed if condition1 is true
}
else if(condition-2)
{
//code to be executed if condition2 is true
}
else if(condition-3)
{
//code to be executed if condition3 is true
}
...
else if(condition- n)
{
//code to be executed if all the conditions are false
}
else
default statement;
Statement-x;

 This contruct is known as the else…if ladder. The conditions are evaluated
from the top,downwards. As soon as a true condition is found, the statement
associated with it is executed and the control is transferrd to the statement-X.
 When all the ‘n’ conditions become false, then the final else containing the
default-statement will be executed.
Example: grading using else…if ladder

……..
if(marks>79)
Grade=”Honours”;
else if(marks>59)
Grade=”first”;
else if (marks>49)
Grade=”second”;
else if(marks>39)
Grade=”third”;
else
Grade=”fail”;
………..
#include <iostream.h>
int main()
{
int i = 20;

// Check if i is 10
if (i == 10)
cout << "i is 10";

// Since i is not 10
// Check if i is 15
else if (i == 15)
cout << "i is 15";

// Since i is not 15
// Check if i is 20
else if (i == 20)
cout << "i is 20";

// If none of the above conditions is true


// Then execute the else statement
else
cout << "i is not present";

return 0;
}
Output:
i is 20

Example 1: else…if ladder

#include <iostream.h>
int main ()
{
int num;
cout<<"Enter a number to check grade:";
cin>>num;
if (num <0 || num >100)
{
cout<<"wrong number";
}
else if(num >= 0 && num < 50){
cout<<"Fail";
}
else if (num >= 50 && num < 60)
{
cout<<"D Grade";
}
else if (num >= 60 && num < 70)
{
cout<<"C Grade";
}
else if (num >= 70 && num < 80)
{
cout<<"B Grade";
}
else if (num >= 80 && num < 90)
{
cout<<"A Grade";
}
else if (num >= 90 && num <= 100)
{
cout<<"A+ Grade";
}
}

Example 2: else...if ladder


Find Largest Number Using if...else Statement

#include <iostream.h>
#include<conio.h>
int main()
{
float n1, n2, n3;
clrscr();
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if((n1 >= n2) && (n1 >= n3))
cout << "Largest number: " << n1;
else if ((n2 >= n1) && (n2 >= n3))
cout << "Largest number: " << n2;
else
cout << "Largest number: " << n3;
getch();
return 0;
}
Output
Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3

(iv)Nested if … else statement


 When a series of decisions are involved, we may have to use more than one if…else
statement in nested form.
 The general form of nested if…else is,

if (condition1)
{
// Executes when condition1 is true
if (condition2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
Statement-3;
}
}
Statement-x;
Example:Nested if…
// using nested if statements
#include <iostream.h>
int main()
{
int num;
cout << "Enter an integer: ";
cin >> num;
// outer if condition
if (num != 0)
{

// inner if condition
if ((num % 2) == 0)
{
cout << "The number is even." << endl;
}
// inner else condition
else
{
cout << "The number is odd." << endl;
}
}
// outer else condition
else
{
cout << "The number is 0 and is neither even nor odd." << endl;
}
cout << "This line is always printed." << endl;
}

Example:Find Largest Number Using Nested if...else statement


#include <iostream.h>
int main()
{
float n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if (n1 >= n2)
{
if (n1 >= n3)
cout << "Largest number: " << n1;
else
cout << "Largest number: " << n3;
}
else
{
if (n2 >= n3)
cout << "Largest number: " << n2;
else
cout << "Largest number: " << n3;
}
return 0;
}
Output
Enter three numbers: 2.3
8.3
-4.2
Largest number: 8.3

Excercises
1. Write a C++ program that prompts the user to input three integer values and find the greatest
value of the three values.(nested if)
3. Write a C++ program to compute the real roots of the equation: ax2+bx+c=0.(switch or else…if
ladder)
The program will prompt the user to input the values of a, b, and c. It then computes the real roots
of the equation based on the following rules:
-if a and b are zero=> no solution
-if a is zero=>one root (-c/b)
-if b2-4ac is negative=>no roots
-Otherwise=> two roots
The roots can be computed using the following formula:
x1=-b+(b2-4ac)1/2/2a
x=-b-(b2-4ac)1/2/2a

b) Switch statement
 The switch statement is a multi-way branch statement and an alternative to if-else-if
ladder.
 The C++ switch statement executes one statement from multiple conditions.
 The switch statement required only one argument, which is then checked with number of
case options.
 The switch statement evaluates the expression and looks for its value among the case
constants.
 If the value is matched with a case constant then that Case constant is executed until a
break statement is found or end of switch block is executed.
 Every case statement ends with a colon(:)
 The syntax of the switch() case statement is shown below.

switch(expression)
{
case value1:
//code to be executed;
block1;
break;
case value2:
//code to be executed;
block2;
break;
case value3:
//code to be executed;
block3;
break;
......
……..
default:
//code to be executed if all cases are not matched;
default block;
break;
}
include <iostream.h>
int main ()
{
int num;
cout<<"Enter a number to check grade:";
cin>>num;
switch (num)
{
case 10: cout<<"It is 10"; break;
case 20: cout<<"It is 20"; break;
case 30: cout<<"It is 30"; break;
default: cout<<"Not 10, 20 or 30"; break;
}
}
Output:
Enter a number:
10
It is 10

Excercises
1. write a program to enter a month number of year 2010 and display the number of
days in a month.
#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
int month,days;
cout << "\n enter a month of year 2020 ";
cout << "-----------------------------\n";
cin >> month;
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 10:
case 12:
days=31;
break;
case 2: days=29;
break;
case 4:
case 6:
case 9:
case 11: days=30;
break;
}
cout << "\n No.of days= "<<days;
getch();
}

Output:
enter a month of year 2020
6
No.of days=30

2.Program to print number in words using switch...case


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

int main()
{
int n, num = 0, i;
cout << "\n\n Print a number in words:\n";
cout << "-----------------------------\n";
cout << " Input any number: ";
cin >> n;
while (n != 0)
{
num = (num * 10) + (n % 10); n /= 10;
}
for (i = num; i > 0; i = i / 10)
{
switch (i % 10)
{
case 0: cout << "Zero "; break;
case 1: cout << "One ";
break;
case 2:
cout << "Two ";
break;
case 3: cout << "Three ";
break;
case 4:cout << "Four ";
break;
case 5:
cout << "Five ";
break;
case 6:
cout << "Six ";
break;
case 7: cout << "Seven ";
break;
case 8: cout << "Eight ";
break;
case 9: cout << "Nine ";
break;
}
}
cout << endl;
}
Output:
Print a number in words:
-----------------------------
Input any number: 8309
Eight Three Zero Nine
Excercises:
1. (switch) Write a program that determines a student’s grade. The program will read three types
of scores (quiz, mid-term, and final scores) and determine the grade based on the following rules:
-if the average score =90% =>grade=A
-if the average score >= 70% and <90% => grade=B
-if the average score>=50% and <70% =>grade=C
-if the average score<50% =>grade=F

Code: cin>>x>>y>>z;
avg=(x+y+z)/3;

if(avg>=90)cout<<"Grade A";
else if((avg>=70) && (avg<90)) cout<<"Grade B";
else if((avg>=50) && (avg<70))cout<<"Grade C";
else if(avg<50) cout<<"Grade F";
else cout<<"Invalid";

c)The ? : Operator
 conditional operator “? :” can be used to replace if...else statements.
 It has the following general form

Var= Exp1 ? Exp2 : Exp3;

Exp1, Exp2, and Exp3 are expressions.

 The value of a ‘?’ expression is determined like this: Exp1 is evaluated. If it is true,
then Exp2 is evaluated and becomes the value of the entire ‘?’ expression. If Exp1
is false, then Exp3 is evaluated and its value becomes the value of the expression
 It can be visualized into if-else statement as:
if(Exp1)
{
var = Exp2;
}
else
{
var= Exp3;
}

Example Program to Store the greatest of the two Number.

// C program to find largest among two


// numbers using ternary operator

#include <iostream.h>
void main()
{
// variable declaration
int n1 = 5, n2 = 10, max;

// Largest among n1 and n2


max = (n1 > n2) ? n1 : n2;

// Print the largest number


cout<<"Largest number between"<<n1<<” and “<<n2<<”is”<<max;
}
Output:
Largest number between 5 and 10 is 10.

Excercises
1. Write a C program to find maximum between three numbers using conditional operator.
2. Write a C program to check whether a number is even or odd using conditional operator.
3. Write a C program to check whether year is leap year or not using conditional operator.
4. Write a C program to check whether character is an alphabet or not using conditional
operator.

2. LOOPS IN C++
 In looping, a sequence of statements are executed until some conditions for
termination of the loop are satisfied.
 A program loop consists of two segments one known as the body of the loop and the
other known as control statement.
 The control statement tests conditions and then directs the repeated execution of the
statements contained in the body of the loop.
 Depending on the position of the control statement in the loop, control structure may
be classified as entry-controlled loop or exit-controlled loop.
 Three loop contructs for performing loop operations. They sre,
1. The while statement
2. The do statement
3. The for statement
 A loop statement allows us to execute a statement or group of statements multiple
times

1.The while statement


 The simplest looping structure is the while statement.
 The syntax of the while loop is:
while (test condition)
{
// body of the loop
}
 The while is an entry-controlled loop statement.
 A while loop execution is as follows
• A while loop evaluates the condition
• If the condition evaluates to true, the code inside the while loop is
executed.
• The condition is evaluated again.
• This process continues until the condition is false.
• When the condition evaluates to false, the loop terminates.
 Then the control is transferred out of the loop
 On exit, the program continues with the statement immediately after the body of the
loop
 The body of the loop may contain a single statement for a number of statements.
Flow chart for while statement

Example program: Display Numbers from 1 to 5


#include <iostream.h>
int main()
{
int i = 1;
// while loop from 1 to 5
while (i <= 5)
{
cout << i << " ";
++i;
}
return 0;
}

Output
12345

This program is executed as follows:


Another Example: Sum of Positive Numbers Only
// program to find the sum of positive numbers
// if the user enters a negative number, the loop ends
// the negative number entered is not added to the sum
#include <iostream.h>
int main()
{
int number;
int sum = 0;
// take input from the user
cout << "Enter a number: ";
cin >> number;
while (number >= 0)
{
// add all positive numbers
sum += number;
// take input again if the number is positive
cout << "Enter a number: ";
cin >> number;
}
// display the sum
cout << "\nThe sum is " << sum << endl;

return 0;
}

Output
Enter a number: 6
Enter a number: 12
Enter a number: 7
Enter a number: 0
Enter a number: -2
The sum is 25

2. The do statement

 On some occasions it is necessary to execute the body of the loop before the test is
performed.
 Such situations can be handled with the help of the do statement.
 The syntax of do statement is,
 On reaching the do statement, the program proceeds to evaluate the body of the
loop first.
 At the end of the loop, the test condition in the while statement is evaluated.
 if the condition is true, the program continues to evaluate the body of the loop once
again.
 This process continues as long as the condition is true.
 when the condition becomes false, the loop will be terminated and the control goes
to the statement that appears immediately after the while statement.

Flowchart for do….while statement

Example: program to print numbers up to 10


#include <iostream.h>
#include <conio.h>
void main()
{
int i = 1;
do
{
cout<<i<<"\n";
i++;
} while (i <= 10) ;
getch();
}

Output:
1
2
3
4
5
6
7
8
9
10
Example: program to print numbers and their cubes up to 10
#include <iostream.h>
# include<conio.h>
void main()
{
clrscr();
int x=1;
cout<<“\n number and cubes”;
//do while loop
do
{
cout << x << " “<<x*x*x;
x++;
} while (x <= 10);
getch();
}
Output
12345

3.The for statement


 The for loop allows execution of a set of instructions until a condition is met.
 The C++ for loop is used to iterate a part of the program several
times.
 If the number of iteration is fixed, it is recommended to use for loop
than while or do-while loops.
 The for loop is another entry controlled loop that provides a more concise
loop control structure.
 General Syntax is for initialization condition increment decrement body of the
loop

Syntax
for(initialization; condition; incr/decr)
{
body of the loop
//code to be executed
}

 The initialization is an assignment statement that is used to set the


loop control variables.
 The condition is a relational expression that determines the number
of iterations desired, or the condition to exit the loop.
 The increment/decrement decides how to change the state of
variables

Flowchart

Example:1 Displaying numbers from 1 to 10


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

void main()
{
clrscr();
for(int i=1;i<=10;i++)
{
cout<<i <<"\n";
}
getch();
}

Output:
1
2
3
4
5
6
7
8
9
10

Example: 2 program to display all lowercase alphabets


#include <iostream.h>
#include <conio.h>
void main()
{
clrscr();
char ch;
cout<<“\n the lowercase letters are”;
for(ch=‘a’;ch<=‘z’;ch++)
cout<<ch;
getch();
}

Find power of any number using for loop


#include <iostream.h>
int main()
{
int bs, ex, num=1,i;
cout << "\n\n Find power of any number using for loop:\n";
cout << "---------------------------------------------\n";
cout << " Input the base: ";
cin >> bs; cout << " Input the exponent: ";
cin>>ex;
for (i = 1; i <=ex; i++)
{
num=num*bs;
}
cout <<bs<<" ^ "<<ex<<" = "<<num<<endl ;
}

Sample 0utput
Find power of any number using for loop:
---------------------------------------------
Input the base: 2
Input the exponent: 5
2 ^ 5 = 32

Exercises

1. Write a program in C++ to find the first 10 natural numbers.


2. Write a program in C++ to find the sum of first 10 natural numbers.
3. Write a program in C++ to display n terms of natural number and their
sum.
4. Write a program in C++ to find the perfect numbers between 1 and
500.
// finding perfect numbers
#include <iostream.h>
int main()
{
cout << "\n\n Find the perfect numbers between 1 and 500:\n";
cout << "------------------------------------------------\n";
int i = 1, u = 1, sum = 0;
cout << "\n The perfect numbers between 1 to 500 are: \n";
while (i <= 500)
{
while (u <= 500)
{
if (u < i)
{
if (i % u == 0)
sum = sum + u;
}
u++;
}
if (sum == i) {
cout << i << " " << "\n";
}
i++;
u = 1;
sum = 0;
}
}

Program flow
Nested for loops
 Whenever a loop construct appears within another loop construct, it is said to be
nested loop structure.
 The loops should not overlap each other.
 The variable names used in the expressions of for loop constructs must be different
from one loop to another.
 Syntax:
for(initialization1; condition1; incr/decr)
{
statement-1;
for(initialization2; condition2; incr/decr)
{
//statement;
}
}
Example2:print the number pattern 1
2 3
4 5 6
7 8 9 10…..
#include <iostream.h>
#include <conio.h>
void main()
{ int i,j,k=0;
clrscr();
for( j=1;j<5;j++)
{
for( i=1;i<=j;i++)
{
cout<<++k <<"\t";
}
cout<<“\n”;
}
getch();
}

Exercises:
1. Write a C++ program that will print the following pattern(while…..)
*******
******
*****
****
***
**
*
2.Write a program that will print the following pattern(looping statements)

1******
12*****
123****
1234***
12345**
123456*
3. Write a C++ program that will print the pattern as shown below:
*
***
*****
*******
*********
*********
*******
*****
***
*
4. Write a program that will ask the user to input n positive numbers. The program will terminate if
one of those number is not positive.(while or do…while)
8. Write a C++ program using two for loops to produce the following pattern of asterisks

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

Can one write the code with only one for loop?
5. Write a C++ program which calculates the sum 1/1 + 1/2 + 1/3 + 1/4 + ... + 1/N
where N is a positive integer. (for……)

6. Fibonaccci Series in C++ without Recursion(for)


1. int n1=0,n2=1,n3,i,number;
2. cout<<"Enter the number of elements: ";
3. cin>>number;
cout<<n1<<" "<<n2<<" "; //printing 0 and 1
for(i=2;i<number;++i) //loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
cout<<n3<<" ";
n1=n2;
n2=n3;
}
7. Prime Number checking Program(for)

#include <iostream>
using namespace std;
int main()
{
int n, i, m=0, flag=0;
cout << "Enter the Number to check Prime: ";
cin >> n;
m=n/2;
for(i = 2; i <= m; i++)
{
if(n % i == 0)
{
cout<<"Number is not Prime."<<endl;
flag=1;
break;
}
}
if (flag==0)
cout << "Number is Prime."<<endl;
return 0;
}

Output:

Enter the Number to check Prime: 17


Number is Prime.
Enter the Number to check Prime: 57
Number is not Prime.
8. Palindrome program in C++(while..)
#include <iostream>
using namespace std;
int main()
{
int n,r,sum=0,temp;
cout<<"Enter the Number=";
cin>>n;
temp=n;
while(n>0)
{
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
cout<<"Number is Palindrome.";
else
cout<<"Number is not Palindrome.";
return 0;
}

9. Factorial Program using Loop(for)

#include <iostream>
using namespace std;
int main()
{
int i,fact=1,number;
cout<<"Enter any Number: ";
cin>>number;
for(i=1;i<=number;i++){
fact=fact*i;
}
cout<<"Factorial of " <<number<<" is: "<<fact<<endl;
return 0;
}

10. Armstrong Number in C++(while)


Armstrong number is a number that is equal to the sum of cubes of its digits. For example 0,
1, 153, 370, 371 and 407 are the Armstrong numbers.

Let's try to understand why 371 is an Armstrong number.

371 = (3*3*3)+(7*7*7)+(1*1*1)
where:
(3*3*3)=27
(7*7*7)=343
(1*1*1)=1
So:
27+343+1=371
#include <iostream>
using namespace std;
int main()
{
int n,r,sum=0,temp;
cout<<"Enter the Number= ";
cin>>n;
temp=n;
while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(temp==sum)
cout<<"Armstrong Number."<<endl;
else
cout<<"Not Armstrong Number."<<endl;
return 0;
}
11. Sum of digits program in C++(while)

include <iostream>
using namespace std;
int main()
{
int n,sum=0,m;
cout<<"Enter a number: ";
cin>>n;
while(n>0)
{
m=n%10;
sum=sum+m;
n=n/10;
}
cout<<"Sum is= "<<sum<<endl;
return 0;
}
12.C++ Program to reverse number(while)
include <iostream>
using namespace std;
int main()
{
int n, reverse=0, rem;
cout<<"Enter a number: ";
cin>>n;
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
cout<<"Reversed Number: "<<reverse<<endl;
return 0;
}

Output:

Enter a number: 234


Reversed Number: 432
______________________________________________________

The jump statements


 Jump statements are used to alter the flow of control unconditionally.
 That is, jump statements transfer the program control within a function
unconditionally.
 The jump statements defined in C++ are break, continue, goto and return.
 Return() is used only in functions.
 The go to and return() may be used anywhere in the program.
 But continue and break statement may be used with a loop statement.
 In switch statement, break is used most frequently.

(i) The goto statement

 The goto statement can be used anywhere within a function or a loop.


 The goto statement does not require any condition.
 This statement passes control anywhere in the program without any
condition.
 goto statements transfer the control from one part to another part in a program
which is specified by a label
 Labels are user-defined identifiers followed by a colon that are prefixed to a
statement to specify the destination of a goto Statement
 The general format is

Syntax-1
goto label;
--------------
--------
---------
label: statement;

 If the statements appear after a go to statement this type of goto is known as


forward go to
Syntax-2
label: statement;
-------
----
-----
goto label;
 If the statements appear before a go to statement this type of goto is known as backward go
to
Example program:
// program to demonstrate use of goto statement
#include<iostream.h>
# include <conio.h>
void main()
{
int x;
clrscr();
cout<<”enter a number:”;
cin>>x;
if(x%2==0)
goto even;
else
goto odd;
even: cout<<x<<”is even number”;
return;
odd: cout<<x<<”is odd number”;
}
Example program:
/* This program calculates the average of numbers entered by user.
If user enters negative number, it ignores the number and
calculates the average of number entered before it. */

# include <iostream.h>
int main()
{
float num, average, sum = 0.0;
int i, n;
cout << "Maximum number of inputs: ";
cin >> n;
for(i = 1; i <= n; ++i)
{
cout << "Enter n" << i << ": ";
cin >> num;

if(num < 0.0)


{
// Control of the program move to jump:
goto jump;
}
sum += num;
}

jump:
average = sum / (i - 1);
cout << "\nAverage = " << average;
return 0;
}
Maximum number of inputs: 10
Enter n1: 2.3
Enter n2: 5.6
Enter n3: -5.6
Average = 3.95
Reason to Avoid goto Statement

 The goto statement gives power to jump to any part of program but,
makes the logic of the program complex and tangled.
 In modern programming, goto statement is considered a harmful
construct and a bad programming practice.
 The goto statement can be replaced in most of C++ program with the use
of break and continue statements.

Example :program to print values from 11 to 19 except 15


#include <iostream.h>
int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
LOOP:
do
{
if( a == 15)
{
// skip the iteration.
a = a + 1;
goto LOOP;
}
cout << "value of a: " << a << endl;
a = a + 1;
} while( a < 20 );

return 0;
}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19

(ii)break
 The break statement is extensively used in loops and switch statements.
 A break statement immediately terminates the loop or the switch statement,
bypassing the remaining statements.
 The control then passes to the statement that immediately follows the loop or
the switch statement.
 A break statement can be used in any of the three C++ loops.
 Note that a break statement used in a nested loop affects only the inner loop
in which it is used and not any of the outer loops.
 Similarly, a break statement used in a switch statement breaks out of that
switch statement and not out of any loop that contains the switch statement.
Syntax:
break;

Example program
#include <iostream.h>

int main ()
{
// Local variable declaration:
int a = 10;
// do loop execution
do {
cout << "value of a: " << a << endl;
a = a + 1;
if( a > 15)
{
// terminate the loop
break;
}
} while( a < 20 );

return 0;
}
Output:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15

iii)The continue Statement


 The continue statement is used to ‘continue’ the loop with its next iteration.
 Continue statement skips any remaining statements in the current iteration
and immediately passes the control to the next iteration.
 The continue statement does not terminate the loop (as in the case of break
statements), rather it only terminates the current iteration of the loop.
 Like a break statement, a continue statement can be used in any of the three
loops.
 The syntax of a continue statement in C++ is
continue;

Example program :1
// program to print the value of i
#include <iostream.h>
int main()
{
for (int i = 1; i <= 5; i++)
{
// condition to continue
if (i == 3)
{
continue;
}
cout << i << endl;
}
return 0;
}

Example program :2
// program to print the sum value of I except multiples of 5
#include <iostream.h>
int main()
{
int sum=0;
for (int i = 1; i <= 50; i++)
{
// condition to continue
if (i %5==0)
{
continue;
}
sum+=i;
}
cout <<“sum=“<< sum<<endl;
return 0;
}

Example program :3
// display sum of factors of a number
#include<iostream.h>
int main ()
{
int x=0, y, sum=0;
cout<<"Enter a number: ";
cin>>y;
while(1)
{
x++;
if (x>y)
break;
if(y%x!=0)
continue;
sum=sum+x;
}
cout<<"\n Sum of factors: "<<sum;
return 0;
}
Output
Enter a number: 8
Sum of factors: 15

Functions in C++
A large size program can be divided into smaller ones.
The smaller programs can be written in the form of functions.
The process of dividing a large program into small subprograms and manipulating
them independently is known as modular programming.
The concept of modular approach of C++is obtained from functions.
The advantages of functions are are,
 Support for modular programming
 Reduction in program size
 Code duplication is avoided
 Code reusability is provided
 Functions can be called repetitively
 A set of functions can be used to form libraries
C ++ program is a combination of one or more functions.
Execution of every C/C + + program starts with user defined function main().
C ++ supports two types of functions,
(i) Library function
(ii) User defined function
Library function can be used in any program by including respective header files
using #include
(ex) #include<string.h>
The programmer can also define their own functions for performing specific task.
such functions are called user-defined functions
the user defined functions defined in C++ are called member functions
__________________________________________________________

The main() function


 In c++, the main() always returns integer value to the operating system by default.
The return value of the function main() is used by the Operating System to check
whether the program is executed successfully or not.
 if the returned value is zero, it means that the program is executed successfully .
 A non-zero value indicates that the program execution was unsuccessful
 The statement return 0; indicates that the program execution is successful.
 The prototype of main() function in C++ is as follows:

int main() int main(int argc, char*argv[])


 The keyword int before function main() is not compulsory, since every function
including main() by default returns an integer value
 (ex)
int main()
{
statement 1;
statement 2;
Statements;
return 0;
}
 The function main() can be declared as void and return statement can be omitted.
(e.g) void main()
{
statement 1;
statement 2;
Statements;
}

PARTS OF FUNCTION
 A function is a group of statements that together perform a task.
 Every C++ program has at least one function, which is main(), and all the most trivial programs
can define additional functions.
 A function is known with various names like a method or a sub-routine or a procedure etc.
 A function has 5 parts:
(a) function prototype declaration
(b) definition of your function (function declarator)
(c) function call
(d) actual and formal argument
(e) the return statement

(a) Function prototype declaration


 Whenever a function is invoked in another function, it must be declared before use. Such a
declaration is known as function declaration are function prototype
 A function declaration tells the compiler about a function's name, return type, and
parameters.
 A function declaration tells the compiler about a function name and how to call the function.
The actual body of the function can be defined separately.

A function declaration has the following parts −


return_type function_name( parameter list );

 The parameter list is optional hence we can have function to have the data type of each
parameter without mentioning the parameter

returntype functionName(datatype 1,datatype 2,………,


datatype n);
 The return type is void when your function returns no values.
 A parameterless function is declared by using void inside the parentheses.
Examples of function prototype statements:

void show(void);

float sum(float, int);

int max(int, int);

float sum(float x, int y);

int max(int num1, int num2);

(b)Defining a Function
 A function definition provides the actual body of the function The general form of
a C++ function definition is as follows −

return_type function_name( parameter list )


{
body of the function
}

 In the function definition, the first line is called function declarator and is followed
by function body.
 Here are all the parts of a function −

 Return Type − A function may return a value. The return_type is the data type of
the value the function returns. Some functions perform the desired operations
without returning a value. In this case, the return_type is the keyword void.
 Function Name − This is the actual name of the function. The function name and
the parameter list together constitute the function signature.
 Parameters − A parameter is like a placeholder. When a function is invoked, you
pass a value to the parameter. This value is referred to as actual parameter or
argument. The parameter list refers to the type, order, and number of the
parameters of a function. Parameters are optional; that is, a function may contain
no parameters.
 Function Body − The function body contains a collection of statements that define
what the function does.

(C) Function Call


A function gets activated only when call to function is invoked. When a program calls a
function, program control is transferred to the called function. A called function performs
defined task and when it’s return statement is executed or when its function-ending
closing brace is reached, it returns program control back to the main program.To call a
function, we simply need to pass the required parameters along with function name, and
if function returns a value, then you can store returned value.

Syntax

function_name(argument_list);

For example –

max(a, b);

(d)Actual and formal arguments


 If a function is to use arguments, it must declare variables that accept the values of
the arguments. These variables are called the formal parameters of the function.
(simply, the arguments declared in the function declaration are known as formal
arguments.)
 The formal parameters behave like other local variables inside the function and are
created upon entry into the function and destroyed upon exit.
 An actual argument is a variable or an expression contained in a function call, that
replaces the formal parameter which is a part of the function declaration.

e) The return statement


 The return statement is used to return value to the caller function.
 The return statement returns only one value at a time.
 When a return statement encountered, the compiler transfers the control of the program to
caller function.

Syntax
return(variable name);
Or
return variable name;

Example Program:1

Example Program:2

#include <iostream.h>

// function declaration
int max(int num1, int num2);
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int ret;
// calling a function to get max value.
ret = max(a, b);
cout << "Max value is : " << ret << endl;
return 0;
}
// function returning the max between two numbers
int max(int num1, int num2) {
// local variable declaration
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
OUTPUT:
Max value is : 200
Example Program:3
// program to check odd or even using function
#include <iostream.h>
#include <conio.h>
void main ()
{
void check(int);
// local variable declaration:
int a;
clrscr();
cout << "enter the number to check odd or even:
";
cin>>a;
// calling a function
check(a);
getch();
}

void check(int k)
{
if (k%2==0)
cout << "\n The number is even ";
else
cout << "\n The number is odd ";
}
OUTPUT:
enter the number to check odd or even:205
The number is odd

Argument passing (with its types) in C++

 The Main objective of passing argument to function is message


passing. Message passing is nothing but communication
between two functions.i.e., between caller and callee function
 Passing information from calling function (Method) to the
called function (method) is known as argument passing.
 By using argument passing, we can share information from
one scope to another in C++ programming language.
 We can pass arguments into the functions according to
requirement.
 C++ supports three types of argument passing:
1. call by value(Pass by Value)
2. Call by address(Pass by Address)
3. Call by reference(Pass by Reference)

While calling a function, there are three ways that arguments can be passed
to a function −

Sr.No Call Type & Description

1 Call by Value

This method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter
inside the function have no effect on the argument.

2 Call by Pointer(address)
This method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the argument.
3 Call by Reference
This method copies the reference of an argument into the formal
parameter. Inside the function, the reference is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the argument.

By default, C++ uses call by value to pass arguments.


1) Pass by Value
In case of pass by value, we pass argument to the function at
calling position. That does not reflect changes into parent function.
Scope of modification is reflected only in called function.
(otherwise)
 in this type, of value of actual argument is passed to the formal
argument and operation done on the formal arguments.
 any change in the formal argument does not affect the actual
argument, because formal arguments are photocopy of actual
arguments.
 Hence, when a function is called by Call by Value, Which does not
affect the actual contents of actual arguments
 Changes made in the formal argument are local to the block of
called function

Consider the example:

#include <iostream.h>

void fun(int a)
{
a=20;
}
int main()
{
int a =10;

fun(a);

cout<<"Value of A: "<<a<<endl;
return 0;
}

Output
Value of A: 10

Here, variable a is passing as call by value in called function fun(), and


the value is changing in the function body but when we print the value
in main(), it is unchanged.
2) Pass by Address or pass by Pointer
 Instead of passing values addresses are passed.
 Function operates on address rather than values.
 Hence the formal arguments are pointers to the actual arguments.
 The changes made in the arguments are permanent
(otherwise)
The call by address method of passing arguments to a function copies the
address of an argument into the formal parameter. Inside the function, the
address is used to access the actual argument used in the call. This means
that changes made to the parameter affect the passed argument.

Consider the example:

#include <iostream>
using namespace std;

void fun(int &b)


{
b=20;
}

int main()
{
int a =10;

fun(a);

cout<<"Value of A: "<<a<<endl;
return 0;
}

Output
Value of A: 20

Consider the function definition (or declaration) void fun(int &b), while
calling the function fun(), reference of a will be passed in the function
body, whatever changes will be made in the function body, will change
the original value. Thus, value of a is changed and it is now 20 in main().

Another example

void swap(int *x, int *y)


{
int temp;
temp = *x; /* save the value at address x */
*x = *y; /* put y into x */
*y = temp; /* put x into y */
return;
}
#include <iostream.h>>
// function declaration
void swap(int *x, int *y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;

return 0;

}
The above code is put together in a file, compiled and executed, it produces the
following result −
 Before swap, value of a :100
 Before swap, value of b :200
 After swap, value of a :200
 After swap, value of b :100
3) Pass by Reference
 In case of pass by reference, we pass argument to the
function at calling position. That reflects changes into
parent function. Scope of modification is reflected in calling
function also.
 The call by reference method of passing arguments to a function
copies the reference of an argument into the formal parameter.
Inside the function, the reference is used to access the actual
argument used in the call. This means that changes made to the
parameter affect the passed argument.
 To pass the value by reference, argument reference is passed to the
functions just like any other value. So accordingly you need to
declare the function parameters as reference types as in the
following function swap(), which exchanges the values of the two
integer variables pointed to by its arguments.

Consider the example:

#include <iostream>
using namespace std;

void fun(int *b)


{
*b=20;
}

int main()
{
int a =10;

fun(&a);

cout<<"Value of A: "<<a<<endl;

return 0;
}

Output
Value of A: 20

Another example:

// function definition to swap the values.


void swap(int &x, int &y) {
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */

return;
}
#include <iostream.h>
// function declaration
void swap(int &x, int &y);
int main () {
// local variable declaration:
int a = 100;
int b = 200;

cout << "Before swap, value of a :" << a << endl;


cout << "Before swap, value of b :" << b << endl;
/* calling a function to swap the values using variable reference.*/
swap(a, b);
cout << "After swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;

return 0;
}
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100

Lvalues and Rvalues


 Left of the assignment operator is Lvalue and right
of the assignment operator is Rvalue
Consider the following expression:
result=(a+b);
An "lvalue" is an expression, variable, constant etc which appears
at left-hand side of an assignment operator.
In the expression result =(a+b); - result is an "lvalue".
An "rvalue" is an expression, variable, constant etc which appears
at right- hand side of an alignment operator.
In the expression result =(a+b); - (a+b) is an "rvalue";
Consider the following expression, which is also a
valid "lvalue" assignment.
((a+b)? a:b) =10;
In the expression, either a or b will be the result
of "lvalue" expression and 10 can be assigned in a or b. so this
expression is also a valid expression.

Return by Reference
 In C++ Programming, not only can you pass values by
reference to a function but you can also return a value by
reference.
 Functions in C++ can return a reference as it’s returns a pointer.
 A reference allows creating alias for the pre-existing variable.
 A reference that returns reference variable is an alias for referred variable.
 When function returns a reference it means it returns a implicit pointer.
 Return by reference is very different from Call by reference. Functions
behaves a very important role when variable or pointers are returned as
reference.
See this function signature of Return by Reference Below:
dataType& functionName(parameters);
where,
 dataType is the return type of the function,
 and parameters are the passed arguments to it.
Example:
#include <iostream.h>
# include<conio.h>
void main()
{
clrscr();
int &min(int&j,int &k);
int a=18,b=11,c;
c=min(a,b);
cout<<“minimum value=“<<c;
getch();
}
int &min(int&j,int&k)
{
if(k<j ) return k;
else return j;
}

Output
minimum value=11
In this program, the statement int &min(int&j,int &k) declares prototype
of function min(). The & reference operator is used because the function
returns reference to int and also receives arguments as reference,. The
function min() receives two integers as reference and returns minimum
value out of two by reference

Default Values for Parameters


C++ compiler allows the programmer to assign default values in the function
prototype declaration or in the function declarator. When the function is
called with less parameter or without parameters, the default values are
used for the operations.
Normally the default values are placed in function prototype
declaration. The compiler checks for the default values in function prototype
and function declarator and provides these values to those arguments that
are omitted in function call.
This is done by using the assignment operator and assigning values for
the arguments in the function definition. If a value for that parameter is not
passed when the function is called, the default given value is used, but if a
value is specified, this default value is ignored and the passed value is used
instead. Consider the following example −

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

int main ()
{
// function declaration:
int sum(int a, int b = 10, int c=15, int d=20);
// local variable declaration:
int a = 2;
int b = 3;
int c = 4;
int d = 5;

// calling a function to add the values.


cout << "\n sum is :" << sum(a,b,c,d);//2+3+4+5
cout << "\n sum is :" << sum(a,b,c);//2+3+4+20
cout << "\n sum is :" << sum(a,b);//2+3+15+20
cout << "\n sum is :" << sum(a);// 2+10+15+20
cout << "\n sum is :" << sum(b,c,d);// 3+4+5+20
return 0;
}
int sum(int j, int k, int l, int m)
{
return (j+k+l+m);
}

When the above code is compiled and executed, it produces the


following result −
Total value is :300
Total value is :120
Another example:

#include <iostream.h>

int sum(int a, int b = 20)


{
int result;
result = a + b;
return (result);
}
int main ()
{
// local variable declaration:
int a = 100;
int b = 200;
int result;
// calling a function to add the values.
result = sum(a, b);
cout << "Total value is :" << result << endl;

// calling a function again as follows.


result = sum(a);
cout << "Total value is :" << result << endl;
return 0;
}
When the above code is compiled and executed, it produces the
following result −
Total value is :300

Exercise programs using functions:

1. Write a program in C++ to show the 5. Write a program in C++ to find the
simple structure of a function. sum of the series
Expected Output : 1!/1+2!/2+3!/3+4!/4+5!/5 using the
function.
The total is : 11
Expected Output :
2. Write a program in C++ to find the The sum of the series is : 34
square of any number using the 6. Write a program in C++ to convert
function. decimal number to binary number
using the function.
Expected Output : Test Data :
Input any decimal number : 65
The square of 20 is : 400.00
Expected Output :
3. Write a program in C++ to swap two
numbers using function. The Binary value is : 1000001
Expected Output :
7. Write a program in C++ to check
Before swapping: n1 = 2, n2 = whether a number is a prime number
4
After swapping: n1 = 4, n2 = 2 or not using the function.
The number 5 is a prime
number.
4. Write a program in C++ to check a 8. Write a program in C++ to get the
given number is even or odd using the largest element of an array using the
function. function.
The entered number is odd. Test Data :
Input the number of elements to be
stored in the array :5 The perfect numbers between 1
to 100 are :
Input 5 elements in the array : 6 28
element - 0 : 1
element - 1 : 2 11. Write a program in C++ to check
element - 2 : 3 whether two given strings are an
element - 3 : 4 anagram.
element - 4 : 5 Test Data :
Expected Output : Input the first String : spare
Input the second String : pears
The largest element in the
array is : 5 Expected Output :
9. Write a program in C++ to check spare and pears are Anagram.
armstrong and perfect numbers using 12. Write a C++ programming to find
the function. out maximum and minimum of some
Test Data : values using function which will return
Input any number: 371 an array.
Expected Output : Test Data :
The 371 is an Armstrong Input 5 values
number. 25
The 371 is not a Perfect 11
number.
35
10. Write a program in C++ to print all
65
perfect numbers in given range using
20
the function.
Expected Output :
Test Data :
Input lowest search limit of perfect Number of values you want to
input: Input 5 values
numbers : 1 Minimum value is: 11
Input lowest search limit of perfect Maximum value is: 65
numbers : 100
Expected Output :

Inline Functions in C++


 Inline function is one of the important feature of C++.
 When the program executes the function call instruction the
CPU stores the memory address of the instruction following
the function call, copies the arguments of the function on
the stack and finally transfers control to the specified
function.
 The CPU then executes the function code, stores the
function return value in a predefined memory
location/register and returns control to the calling function.
This can become overhead if the execution time of function
is less than the switching time from the caller function to
called function (callee).
 For functions that are large and/or perform complex tasks,
the overhead of the function call is usually insignificant
compared to the amount of time the function takes to run.
 However, for small, commonly-used functions, the time
needed to make the function call is a lot more than the time
needed to actually execute the function’s code. This
overhead occurs for small functions because execution time
of small function is less than the switching time.
 C++ provides an inline functions to reduce the function call
overhead.
 Inline function is a function that is expanded in line when it
is called. When the inline function is called whole code of
the inline function gets inserted or substituted at the point
of inline function call. This substitution is performed by the
C++ compiler at compile time.
 Inline function may increase efficiency if it is small.
member, inlining is only a request to the compiler, not a
command.

Syntax:

inline return-type function-name(parameters)


{
// function code
}
Example:
inline float square((float k)
{
return(k*k);
}

Example program:

#include<iostream.h>
# include<conio.h>
inline float square(float j)
{
return(j*j);
}
void main()
{
clrscr();
int p=4;
s=square(p);
cout<<”Square value:”<<s;
getch();
}

Output
Square value:16

 Compiler can ignore the request for inlining. Compiler may


not perform inlining in such circumstances like:
1) If a function contains a loop. (switch,if, for, while, do-
while)
2) If a function contains static variables.
3) If a function is recursive.
4) If a function return type is other than void, and the return
statement doesn’t exist in function body.
5) If a function contains switch or goto statement.
 the function main() cannot work as inline
Note:
 Inline functions provide following advantages:
1) Function call overhead doesn’t occur.
2) It also saves the overhead of push/pop variables on the stack
when function is called.
3) It also saves overhead of a return call from a function.
4) When you inline a function, you may enable compiler to perform
context specific optimization on the body of function. Such
optimizations are not possible for normal function calls. Other
optimizations can be obtained by considering the flows of calling
context and the called context.
5) Inline function may be useful (if it is small) for embedded
systems because inline can yield less code than the function call
preamble and return.

Function Overloading
 Defining member functions with the same name and different parameters
is known as function overloading or function polymorphism
 Polymorphism means one function having many forms
 The overloaded function must be different in its argument list and with
different data types
 The function would perform different operation depending on the
argument list in the function call
 The correct function to be invoked is determined by checking the number
and type of arguments
 The examples of overloaded function are given below. All the functions
defined should be equivalent to their prototypes.

int add(int a,int b);


int add(int a,int b,int c);
double add(double x,double y);
double add(int p,double q);
double add(double p,int q);
The respective function calls are,
cout<<add(5,10);
cout<<add(5,10,15);
cout<<add(12.5,7.5);
cout<<add(15,10.0);
cout<<(0.75,5);

example without class void print(char const *c)


{
#include <iostream.h>
cout << " Here is char* " << c << endl;
void print(int i)
}
{
cout << " Here is int " << i << endl;
int main()
}
{
void print(double f)
print(10);
{
print(10.10);
cout << " Here is float " << f << endl;
print("ten");
}
return 0;
} void print(double f)
{
cout << "Printing float: " << f <<
endl;
}
void print(char* c)
{
cout << "Printing character: " << c <<
endl;
}
};
int main(void)
{
example with class
printData pd;
#include <iostream.h> // Call print to print integer
class printData pd.print(5);
{ // Call print to print float
public: pd.print(500.263);
void print(int i) // Call print to print character
{ pd.print("Hello C++");
cout << "Printing int: " << i << endl; return 0;
} }
 Execrcises:
1. find area of rectangle, triangle and sphere(area of rectangle=l*b,
triangle=1/2 bh, sphere=4/3 r3)
2. Find volume of cube(s*S*S*,cylinder(*R*R*h) rectangular box(i*B*H)

Principles of Overloading
1. If two functions have the similar type and the number of
arguments( data type), the function cannot be overloaded. The return
type may be similar or void, but argument data type or number of
arguments must be different.
For example,
sum(int,int,int);
sum(int,int);
these functions can be overloaded. Here the type of arguments
in both functions, but number of arguments are different.
sum(int,int,int);
sum(float,float, float);
these functions can be overloaded. Here the number of
arguments is same but the data types are different.
2. Passing constant values directly instead of variables result in
ambiguity. For example,
int sum(int,int);
float sum(float,float,float);
here sum() is an overloaded function for integer and float
values.
If values are passed as
sum(2,3);
sum(1.1,2.3);
the compiler will flag an error because the compiler cannot
distinguish between these two functions. Hence in both the above calls,
integer version of function sum() is executed.

3. The compiler attempts to find an accurate function declaration that


matches in types and number of arguments and invokes that function.
The arguments passed or checked with all declared functions. if
matching function is found then that that function gets executed.
4. If there is no accurate match found, compiler makes the implicit
conversion of actual arguments. For example char is converted to
int and float is converted to double. If all above steps fail, then
compiler performs user built functions.
5. If internal conversion fails user-defined conversion is carried out with
implicit conversion and integral integral promotion.
6. sometime while making internal conversion, ambiguity is created if one
data type is compatible with two or more data types. If such situation
occurs the compiler displays an error message.
7. If a program has two versions of functionsi.e., one for float and second
for double data type, then if we pass a float number, the double version
of function is selected for execution. But the same is not applicable
with integer and long integer.

LIBRARY FUNCTIONS
Mathematical Functions
Some of the important mathematical functions in header file <math.h> are
Function Meaning
sin(x) Sine of an angle x (measured in
radians)
cos(x) Cosine of an angle x (measured in
radians)
tan(x) Tangent of an angle x (measured in
radians)
asin(x) Sin-1 (x) where x (measured in
radians)
acos(x) Cos-1 (x) where x (measured in
radians)
exp(x) Exponential function of x (ex)
log(x) logarithm of x
log 10(x) Logarithm of number x to the base
10
sqrt(x) Square root of x
pow(x, y) x raised to the power y
abs(x) Absolute value of integer number x
fabs(x) Absolute value of real number x

function

Function Meaning
isalpha(c) It returns True if C is an uppercase
letter and False if c is lowercase.
isdigit(c) It returns True if c is a digit (0 through
9) otherwise False.
isalnum(c) It returns True if c is a digit from 0
through 9 or an alphabetic character
(either uppercase or lowercase)
otherwise False.
islower(c) It returns True if C is a lowercase letter
otherwise False.
isupper(c) It returns True if C is an uppercase
letter otherwise False.
toupper(c) It converts c to uppercase letter.
tolower(c) It converts c to lowercase letter.

character Functions
All the character functions require <ctype.h> header file. The following table
lists the

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy