Python Programming Notes
Python Programming Notes
Python Programming Notes
SCHOOL OF COMPUTING
1
Introduction to Computer Problem Solving
UNIT 1
INTRODUCTION TO COMPUTER PROBLEM SOLVING
1.1 Algorithms
List the data needed to solve the problem (input) and know what is the end
result (output).
Describe the various step to process the input to get the desired output. Break
down the complex processes into simpler statements.
Step1: Start
Step 4: Print c
Step 5: Stop.
The above algorithm is to add two numbers a and b. The numbers are the input
provided by the user .After adding the result is stored in a variable c and it is printed.
1.2.2 Control flow: The process of executing the statements in the given
sequence is called as control flow.
3
Introduction to Computer Problem Solving
Sequence
Selection
Iteration
Sequence
Example: Algorithm to find the average of three numbers, the algorithm is as follows
Step1: Start
Step6: Print d
Step7: Stop
The above algorithm finds the average of three numbers a, b and c. The numbers are
the input provided by the user .After adding the total is divided by 3 and the result is
stored in a variable d and it is printed.
Selection
If the condition is true, one part of the program will be executed, otherwise the other
part of the program will be executed.
4
Introduction to Computer Problem Solving
Example: Algorithm to find the Largest of two numbers, the algorithm is as follows
Step1: Start
Step 6: ENDIF
Step 7: Stop
The above algorithm is used to find the Largest of two numbers a and b. The numbers
are the input provided by the user .The number a and b are compared, If a is larger
Print “A is Large” or if b is larger print “B is Large”.
Iteration
Step 1: Start
Step 6: Go to step 4
Step 7: Stop
5
Introduction to Computer Problem Solving
The above algorithm is for printing first n natural numbers .The user provides
the input. The first value, i is initialized. A loop is initialized. The first value is
printed and the number is incremented. The i value is checked with n, the user input.
The numbers are printed until i becomes greater than n.
1.2.3 Functions
Function is a sub program which consists of block of instructions that performs
a particular task. For complex problems, the problem is been divided into smaller and
simpler tasks during algorithm design.
Benefits of Using Functions
Step 1: Start
Step 2: Call the function add ()
Step 3: Stop
The above algorithm is to call the function add. This function is called as Main
function or calling function.
Subfunction add ()
Step 1: Function start
Step 2: Get two numbers as input and store it in to a and b
Step 3: Add the numbers a & b and store the result in c
Step 4: Print c
6
Introduction to Computer Problem Solving
Step 5: Return.
The above algorithm is called as the called function which is to add two numbers a
and b. The numbers are the input provided by the user .After adding the result is
stored in a variable c and it is printed.
1.3 NOTATIONS
Pseudo code means a short, readable set of instructions written in English to explain
an algorithm.
Comment: //
Start: BEGIN
Stop: END
Input: INPUT, GET, READ
Calculate: COMPUTE, CALCULATE, ADD, SUBTRACT, INITIALIZE
Output: OUTPUT, PRINT, DISPLAY
Selection: IF, ELSE, ENDIF
Iteration: WHILE, ENDWHILE, FOR, ENDFOR
Example: Pseudo code to Add two numbers
7
Introduction to Computer Problem Solving
BEGIN
GET a, b
ADD c=a+b
PRINT c
END
Advantages:
It is not visual.
For a beginner, it is more difficult to follow the logic or write pseudo code
as compared to flowchart.
Flow Chart
Flow chart is defined as the graphical or diagrammatical representation of the process
of solving a problem. It represents the steps of a process in a sequential order.
8
Introduction to Computer Problem Solving
Rules:
Only one flow line should come out from a process symbol
Only one flow line should enter a decision symbol. However, two or three
flow lines may leave the decision symbol
9
Introduction to Computer Problem Solving
Advantages:
10
Introduction to Computer Problem Solving
Disadvantages:
The flowcharts are complex and clumsy when the program is large or
complicated.
The cost and time taken to draw a flowchart for larger applications are
expensive.
The above flowchart is used for adding two numbers Number1 and Number2.The
numbers are the input provided by the user .After adding, the result is stored in the
variable Sum and is printed.
The above flowchart is used for printing all odd numbers up to 100. The first value, i
is initialized as zero. A loop is initialized. Starting from i=0, each value is divided by
11
Introduction to Computer Problem Solving
2 and the remainder is captured .This operation is called modulo of a number. The
modulo of first value is calculated if the result is not equal to zero then the number is
printed and the number is incremented. The i value is checked with the limit, 100.
The numbers are printed until the value is less than the input value.
The above flowchart is to find the Largest of two numbers NO1 and NO2.The
numbers are the input provided by the user .The number NO1 and NO2 are
compared, If NO1 is larger, the number NO1 is printed or if NO2 is larger, the
number NO2 is printed.
12
Introduction to Computer Problem Solving
13
Introduction to Computer Problem Solving
The flowchart 1.5a is for the calling function. This function is also called as
Main function . The flowchart1.5b is called as the called function which is to add two
numbers a and b.The numbers are the input provided by the user .After adding the
result is stored in a variable c and it is printed.
Types of Flowcharts
Process Flowchart
Data Flowchart
Business Process Modeling Diagram
Step 1: Start
Step 2: Estimation of people below poverty line.
Step 3: Recommendation about the type and quantity of food from the food
committee
Step 4: Decide the cost
Step 5: Generation of Revenue to meet the food demand
Step 6: Provide food through public distribution system at all levels.
14
Introduction to Computer Problem Solving
15
Introduction to Computer Problem Solving
Iterations:
1. For loop
2. While loop
END
16
Introduction to Computer Problem Solving
The above flowchart is to print all natural numbers up to n .The user provides
the input value n. The first value, i is initialized as one. A loop is initialized. The i
value is checked with n, the user input. The numbers are printed until the value is less
than the user input value. When the condition becomes false the loop terminates.
17
Introduction to Computer Problem Solving
Recursion:
Example: Factorial
RETURN fact=n*factorial(n-1)
18
Introduction to Computer Problem Solving
The flowchart 1.9a is to call the function factorial. This function is called as
Main function or calling function. The flowchart1.5b is called as the called function
which is to find the factorial of the number passed from the main function. The loop
exists until the n value becomes one. Factorial is a recursive function where the
function itself is called again and again.
19
Introduction to Computer Problem Solving
The following are some of the factors which helps in an analyzing an algorithm
Efficiency
Simplicity
Generality
Range of Growth
Computing order of growth
Time Complexity
20
Introduction to Computer Problem Solving
Time complexity can be represented as a numerical function T(n), where T(n) can be
measured as the number of steps, provided each step consumes constant time.
For example
int sum(int a[],int n)
{
Int sum=0
For (int i=0;i<n;i++)
{
Sum=sum+a[i]
}
Return sum
}
21
Introduction to Computer Problem Solving
The program must be of lesser size in a multiuser system ,since there will be
multiple copies of the same program
To compute the space we require two components – Variable space and fixed space.
Where C is a Constant, that is the fixed space and it denotes the amount of space
taken by instructions, simple variables, constants and identifiers.
Space complexity can also be represented as the sum of instruction space, Data
space and Environment stack space.
Instruction space: The memory space required for storing the compiled
instructions. It depends on the Compiler used, compiler options and the target
computer
22
Introduction to Computer Problem Solving
Type Size
bool, char, unsigned char, signed char, int8 1 byte
int16, short, unsigned short 2 bytes
float, int32, int, unsigned int, long, unsigned long 4 bytes
double, int64, long double 8 bytes
Examples:
int c= a+b
return c
In the above example, variables a, b, and c are all integer types, so they will take up 4
bytes each, so total memory requirement will be (4(3) + 4) = 20 bytes, the additional
4 bytes is for return value. Since this space requirement is fixed for the above
example, it is called Constant Space Complexity.
Int sum=0
Sum=sum+a[i]
Return sum
23
Introduction to Computer Problem Solving
In the above example, 4*n bytes of space is required for the array a[]
n elements.
Hence the total memory requirement will be (4n + 12), which is increasing linearly
with the increase in the input value n, hence it is called as Linear Space Complexity.
Case Studies
Networked Healthcare
Smart Cities
24
Introduction to Computer Problem Solving
QUESTIONS :
1. Write an algorithm and flowchart for solving quadratic equation (of the
form ax2 + bx + c).
2. M1,M2, M3 are the marks scored in 3 tests. Write an algorithm to find the
average of best 2 marks.
3. Write an algorithm and pseudo code to check whether a given integer is
prime number or not.
4. Write a recursive function to add two numbers a and b.
5. Describe the algorithm for finding sum and average of n numbers.
6. Draw a flow chart for computing factorial of a given number.
7. Draw the flow chart for finding sum of first n natural numbers.
8. Draw a flow chart print all prime number between to intervals.
9. Explain the algorithm to find minimum in a list and Maximum in a list.
10. Develop an algorithm for conversion from Celsius to Fahrenheit and vice
versa.
25
School of Computing
UNIT - II
1
UNIT II BASICS OF C PROGRAMMING
1. Introduction to C
The root of all modern languages is 'ALGOL.' It was first introduced in 1960. 'ALGOL'
introduced the concept of structured programming to the developer community. In 1967, a
new computer programming language was announced called as 'BCPL' which stands for
Basic Combined Programming Language. BCPL was designed and developed by Martin
Richards, especially for writing system software. This was the era of programming
languages. Just after three years, in 1970 a new programming language called 'B' was
introduced by Ken Thompson that contained multiple features of 'BCPL.' This programming
language was created using UNIX operating system at AT&T and Bell Laboratories. Both
the 'BCPL' and 'B' were system programming languages.
2
Fig. 1 History of C language
In 1972, a great computer scientist Dennis Ritchie created a new programming language
called 'C' at the Bell Laboratories. It was created from 'ALGOL', 'BCPL' and 'B' programming
languages. 'C' programming language contains all the features of these languages and many more
additional concepts that make it unique from other languages.
American National Standards Institute (ANSI) defined a commercial standard for 'C'
language in 1989. Later, it was approved by the International Standards Organization (ISO) in
1990. 'C' programming language is also called as 'ANSI C'. The standardization committee of C
added a few features of C++/Java to enhance the usefulness of the language. The result was the
1999 standard for C. This version is usually referred to as C99. The history and development of
C is illustrated in Fig. 1.
3
1.2 Where is C used? Key Applications
Most of the applications by Adobe are developed using 'C' programming language.
It is used for developing browsers and their extensions. Google's Chromium is built using
'C' programming language.
It is used to develop databases. MySQL is the most popular database software which is
built using 'C'.
2. Features of C
C is the widely used language. It provides many features that are illustrated in fig.2.
Fig 2. Features of C
4
2.1 Rich Library
It is a robust language whose rich set of built-in functions and operators can be used to write any
complex program. C provides a lot of inbuilt functions that make the development fast.
C is highly portable. This means that C programs written for one computer can be run on another
with little or no modification. The compiler and preprocessor makes it possible to run on
different computer or devices
2.5 Recursion
In C, we can call the function within the function. It provides code reusability for every function.
2.6 Fast
Programs written in C are efficient and fast. This is due to its variety of data types, functions and
powerful operators. It is many times faster than BASIC. For example, a program to increment a
variable from 0 to 15000 takes about one second in C while it takes more than 50 seconds in an
interpreter BASIC.
2.7 Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the allocated
memory at any time by calling the free() function.
2.8 Pointer
C provides the feature of pointers. We can directly interact with the memory by using the
pointers.
5
We can use pointers for memory, structures, functions, array, etc.
2.9 Easy to extend
C is also an extensible language. Another important feature of C program, is its ability to extend
itself. A C program is basically a collection of functions that are supported by the C library. We
can continuously add our own functions to C library.
3. Structure of a C program
C program can be written in this structure only. Writing a C program in any other structure
will hence lead to a Compilation Error. The structure of a C program is illustrated in figure 3.
Example :
//Line 1
//Line 2
(Or)
Line 1…
Line 2….
…..,
………
6
*/
#include<filename>
Example:
#include<stdio.h>
#include<math.h>
#include<string.h>
Syntax:
7
#define symbolic constant value
Example
#define PI 3.14
The variables that are used in more than one function throughout the program are called
global variables.
The next part of a C program is to declare the main() function. Every „C‟ program must have one
main() function where the program execution begins.
{}
1. Declaration Part
2. Executable part
It refers to the variables that are to be used in the function. The variables are to be declared
before any operation in the function and these are called local variables
Syntax
Example:
Void main()
8
{
int a;
It contains at least one valid C Statement. The Execution of a program begins with opening brace
‟{„ and ends with closing brace ‟}‟ .The closing brace of the main function is the logical end of
the program.
Sub programs are basically functions are written by the user (user defined functions).
They may be written before or after a main () function and called within main () function.
• All statements in „C‟ program should be written in lower case letters. Uppercase letters
are only used for symbolic constants
• Blank space may be inserted between the words. Should not be used while declaring a
variable, keyword, constant and function
• The program statements can be written anywhere between the two braces following the
declaration part.
9
{
scanf("%f",&r);
return 0;
float area(float r)
Type the program and edit it in standard „C‟ editor and save the program with .c as an
extension.
10
Fig.4 Creating the program
• This is the process of converting the high level language program to Machine level
• Language (Equivalent machine instruction) -> Compiler does it!
• Errors will be reported if there is any, after the compilation
• Otherwise the program will be converted into an object file (.obj file) as a result of the
compilation
• After error correction the program has to be compiled again
11
Fig. 5 Compiling and Linking the program
12
Fig. 6 Executing the program
In a passage of text, individual words and punctuation marks are called tokens. Similarly,
in a C program the smallest individual units are known as C tokens. We cannot create a
sentence without using words; similarly, we cannot create a program in C without using
tokens in C. Therefore, we can say that tokens in C is the building block or the basic
component for creating a program in C language. C has six types of tokens as shown in
Fig. 7. C programs are written using these tokens and the syntax of the language.
C Tokens
Every C word is classified as either a keyword or an identifier. All keywords have fixed
meanings and these meanings cannot be changed.
Keywords serve as basic building blocks for program statements.
All keywords must be written in lowercase.
Keywords cannot be used as normal identifiers names.
•
Table 2. ANSI C Keywords
3.2 Identifiers
Identifiers refer to the names of variables, functions and arrays. These are user-defined
names and consist of a sequence of letters and digits, with a letter as a first character.
Example :
int num;
char name;
14
Sum() // where num and name, sum are identifier names
3.3 Constants
Constants in C refer to fixed values that do not change during the execution of a
program.
Fig.8. Constants
Example:
123
Integer numbers are inadequate to represent quantities that vary continuously, such as
distances, heights, temperatures, prices, and so on.
These quantities are represented by numbers containing fractional parts like 17.548.
Example:
15
3.3.3 Single character constants
A single character constant (or simply character constant) contains a single character
enclosed within a pair of single quote marks.
Example
Examples
C supports some special backslash character constants that are used in output functions.
Each one of them represents one character, although they consist of two characters.
16
3.4 Strings in C
Strings in C are always represented as an array of characters having null character '\0' at
the
end of the string. This null character denotes the end of the string. Strings in C are
enclosed
within double quotes, while characters are enclosed within single characters. The size of a
char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.
char a[] = "javatpoint"; // The compiler allocates the memory at the run time.
Operators in C
C supports a rich set of built-in operators. An operator is a symbol that tells the
computer to perform certain mathematical or logical manipulations. The data items on
which the operators are applied are known as operands. Operators are applied between the
operands Operators are used in programs to manipulate data and variables. Depending on
the number of operands, operators are classified as follows:
A unary operator is an operator applied to the single operand. For example: increment
The binary operator is an operator applied between two operands. The following is the list
17
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
6. Conditional operators
7. Bitwise operators
8. Special operators
When both the operands in a single arithmetic expression such as a+b are integers, the
expression is called as integer expression and the operation is called integer arithmetic.
Example
a=14, b=4;
18
Operation Output
a+b 18
a-b 10
a*b 56
An arithmetic which is involving real values (decimal values) is called real arithmetic.
• x = 6.0/7.0 = 0.857143
• y = 1.0/3.0 = 0.333333
• z = –2.0/3.0 = –0.666667
When one operand is integer and another is real i.e both the types of variables (integer and
real) values are used for operation is called as mixed more arithmetic.
Example
19
#include<stdio.h>
#include<conio.h>
main ()
printf(“Enter days\n”) ;
scanf(“%d”, &days) ;
months = days / 30 ;
We often compare two quantities, and depending on their relation, take certain decision.
For example, we may compare the age of two persons, or the price of two items, and so on.
These comparisons can be done with the help of relational operators.
When arithmetic expressions are used on either side of the relational operator, the
20
arithmetic operator will be executed first and then the results will be compared. Relational
operators are used in decision making statements.
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10, b=20;
if(a > b)
{
printf(“A is Largest\n");
}
else
{
printf(“B is Largest\n");
} }
In addition to the relational operators, C has the following three logical operators.
&& meaning logical AND
|| meaning logical OR
! meaning logical NOT
21
termed as a logical expression or a compound relational expression. Like the simple relational
expressions, a logical expression also yields a value of one or zero, according to the truth table
shown in Table 3.3. The logical expression given above is true only if a > b is true and x == 10
is true. If either (or both) of them are false, the expression is false.
Example
Example Program
#include<stdio.h>
#include<conio.h>
Void main()
printf(“a is greater”);
else
22
Example
a=10
c=a+b;
C has a set of „shorthand ‟ assignment operators of the form
v op= exp;
Where v is a variable, exp is an expression and op is a C binary arithmetic operator. The operator
op= is known as the shorthand assignment operator.
The assignment statement
v op= exp;
is equivalent to
v = v op (exp);
with v evaluated only once.
23
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
// calculating sum
sum = number1 + number2;
printf("%d %d %d", number1, number2, sum);
return 0;
}
C has very useful operators not generally present in other languages. These are increment and
decrement operators:
++ and – -
The operator ++ adds 1 to the operand while -- substracts 1. Both of them are unary operators.
++m is equivalent to m=m+1; (or m+=1)
- -m is equivalent to m=m- 1; (or m- =1)
We will be using this increment and decrement operators in for and while loop.
A prefix operator first adds 1 to the operand and then the result is assigned to the
variable on left. Eg. ++var
On the other hand, a postfix operator first assigns the value to the variable on left and
then increments the operand.eg. var++
Example:
Consider m=10
a=++m
a = 11
b = m++
b = 10
The c language has a unusual operator, useful for making two way decisions. This operator is
a combination of ? and : and takes three operands. This operator is popularly known as
24
conditional operator. The general syntax of this operator is .
Conditional expression ? expression1: expression2
Eg.
Large=(num1>num2)?num1:num2
In the above example the largest number between num1 and num2 will be assigned to large.
That is if num1 is larger then num2 num1 will be assigned to large. This is similar to if
statement but the syntax differs.
Example:
#include <stdio.h>
int main()
{
int a=5,b; // variable declaration
b=((a==5)?(3):(2)); // conditional operator
printf("The value of 'b' variable is : %d",b);
return 0;
}
C has distinction of supporting special operators known as bitwise operator for manipulating
of data at bit level. These are used for testing the bits, or shifting them right or left.
Operator meaning
& bitwise AND
| bitwise OR
^ bitwise exclusive OR
<< shift left
>> shift right
~ one‟s complement
C supports some special operators such as comma(,) operator, sizeof operator, pointer operator.
25
Eg.
Eg.
M= sizeof (a);
• A data type specifies a type of data that a variable can store such as integer, float or
character.
• ANSI C supports three classes of data types:
1. Primary (or fundamental) data types
2. Derived data types
3. User-defined data types
Five fundamental data types:
integer (int) - 2 byte
character (char) -1 byte
floating point (float) - 4 byte
double-precision floating point (double) -8 byte
Void
The void type has no values. This is usually used to specify the type of functions.
The type of a function is said to be void when it does not return any value to the
calling function.
• char: The most basic data type in C. It stores a single character and requires a single
byte of memory in almost all compilers.
• int: As the name suggests, an int variable is used to store an integer. It requires 2 bytes of
memory.
• float: It is used to store decimal numbers (numbers with floating point value) with
single precision. It requires 4 bytes of memory.
26
• double: It is used to store decimal numbers (numbers with floating point value) with
double precision. It requires 8 bytes of memory.
3.7 Variables
After designing suitable variable names, we must declare them to the compiler.
27
Declaration does two things:
1. It tells the compiler what the variable name is.
The declaration of variables must be done before they are used in the program.
Syntax:
Syntax:
variable_name = constant;
Example
a=10;
It is also possible to assign a value to a variable at the time the variable is declared.
Syntax:
Examples
28
C permits the initialization of more than one variables in one statement using multiple
assignment operators.
Example
p = q = s = 0;
x = y = z = MAX;
Input means to provide the program with some data to be used in the program and Output
means to display data on screen or write the data to a printer or a file. C programming language
provides many built-in functions to read any given input and to display data on screen when
there is a need to output the result.
The standard input-output header file, named stdio.h contains the definition of the functions
printf() and scanf(), which are used to display output on screen and to take input from user
respectively.
printf() statement
Eg: printf(“%f”,si);
printf(“%d”,i);
scanf() statement
29
scanf( ) is a predefined,standard C function used to input data from keyboard.
Eg: scanf(“%d”,&n);
scanf(“%f”,&interest);
#include<stdio.h>
int main()
int number;
printf("enter a number:");
scanf("%d",&number);
return 0;
The getchar() function reads a character from the terminal and returns it as an integer.
This
function reads only single character at a time. You can use this method in a loop in case
you want to read more than one character.
The putchar() function displays the character passed to it on the screen and returns the
same character. This function too displays only a single character at a time. In case you
want to display more than one characters, use putchar() method in a loop.
A control flow statements is a primary concept in most high level programming languages.
30
It is a block of code that control the flow of a program.
Jumping Statements
1. if statement
2. switch statement
4. goto statement
31
statements „control‟ the flow of execution, they are also known as control statements.
The if statement is a powerful decision-making statement and is used to control the flow of execution of
statements. The different forms of if statement are:
1. Simple if statement
2. 2. if.....else statement
4. 4. else if ladder.
Takes an expression in parenthesis and a statement or block of statements. If the expression is true then
the statement or block of statements gets executed otherwise these statements are skipped.
Syntax:
if(Condition)
Statements;
Example:
#include<stdio.h>
void main()
int a=5;
if(a%2==0)
printf(“number %d is even.”,a);
32
3.9.1.1.2 If Else Statements
This is also one of the most useful conditional statement used in C to check conditions.
Syntax:
if(condition)
true statements;
else
false statements;
Example:
#include<stdio.h>
void main()
int a=5;
if(a%2==0)
printf(“number %d is even”,a);
Else
printf(“number %d is odd”,a);
33
3.9.1.1.3 Nested If Statements
If within a If condition is called Nested If condition. It is a conditional statement which is used when we
want to check more than 1 conditions at a time in a same program.
Syntax:
if(condition)
if(condition)
{true statement;}
else{statements;}
Example:
#include<stdio.h>
void main()
int a,b,c;
if(a>b){
if(a>c){
printf(“a is big”);
else{
printf(“c is big”);
else{
if(b>c){
34
printf(“b is big”);
else{
printf(“c is big”);
getch();
Else if ladder is similar to if else control statement. Else if() ladder is used to check for another
condition if the previously specified condition becomes false.
Syntax:
if(condition){
Statement;
else if(condition){
Statement;
else{
Statement;
Example:
void main()
int a,b,c;
35
if(a>b && a>c){
printf(“a is big”);
else if(b>c){
printf(“b is big”);
else{
printf(“c is big”);
getch();
• This is a multiple or multi way branching decision making statement. When we use nested if-else
statement to check more than 1 condition then the complexity of a program increases in case of a lot
of conditions.
• Thus, the program is difficult to read and maintain. So to overcome this problem, C provides 'switch
case'. Switch case checks the value of a expression against a case values, if condition matches the
case values then the control is transferred to that point.
Syntax:
switch(expression){
case exp1:
statement;
break;
case exp2:
statement;
break;
default;
statement;
36
}
Example:
#include<stdio.h>
void main()
char c=„a‟;
switch(c)
case „a‟:
case „e‟:
case „i‟:
case „o‟:
case „u‟:
printf(“character %c is
vowel”,c);
break;
default:
printf(“character %c is
constant”,c);
getch();
'A loop' is a part of code of a program which is executed repeatedly. A loop is used using condition.
The repetition is done until condition becomes true.
37
While Loop
For Loop
Do While Loop
While Loop :
This is an entry controlled looping statement. It is used to repeat a block of statements until
condition becomes true.
Syntax:
while (condition)
Statements;
Increment/decrement;
Example:
#include<stdio.h>
void main() {
int i;
clrscr();
i=1;
while(
i<=10){
printf(“%d\t”,i);
i++;
getch();
38
}
For Loop :
This is an entry controlled looping statement. In this loop structure, more than one variable can be
initialized. One of the most important feature of this loop is that the three actions can be taken at a time
like variable initialization, condition checking and increment/decrement.
Syntax:
Statements;
Example
#include<stdio.h>
void main() {
int i;
clrscr(); i=1;
for(i=1;i<=20; i+=2) {
printf(“%d\t”,i);
getch();
Do While Loop:
This is an exit controlled looping statement. Sometimes, there is need to execute a block of
statements first then to check condition. At that time such type of a loop is used. In this, block of
statements are executed first and then condition is checked.
Syntax:
do {
39
statements ;
( increment/decrement);
} while (condition);
Example:
#include<stdio.h>
void main() {
int i;
clrscr(); i=1;
do{
printf(“%d\t”,i);
i++;
}while(i<=5);
getch();
• Break
• Continue
• Goto
It is necessary to exit immediately from a loop as soon as the condition is satisfied. When break
statement is used inside a loop, then it can cause to terminate from a loop. The statements after break
statement are skipped.
Syntax:
if(condition)
break;
40
}
#include<stdio.h>
void main() {
int i;
for(i=1;i<=10; i++){
If(i==5){
break;
else{
printf(“%d\t”,i);
getch();
It is required to skip a part of a body of loop under specific conditions. The working structure of
'continue' is similar as that of that break statement but difference is that it cannot terminate the loop.
It causes the loop to be continued with next iteration after skipping statements in between. Continue
statement simply skips statements and continues next iteration.
Syntax:
if(condition)
continue;
Example
#include<stdio.h>
void main() {
int i;
41
for(i=1;i<=10; i++){
If(i==5){
continue;
else{
printf(“%d\t”,i);
getch();
GOTO STATEMENT
• The goto statement is a jump statement which jumps from one point to another point within a
function or program. The goto statement is marked by label statement. Label statement can be
used anywhere in the function above or below the goto statement. Simple break statement cannot
work here properly. In this situation, goto statement is used.
Syntax:
if(condition)
goto step;
step: statements;
Example
#include<stdio.h>
void main() {
Int i;
for(i=1;i<=10;i++){
If(
42
i==5){
goto step:
else{
printf(“%d\t”,i);
step:
printf(“Error”);
3.10 Functions
A function is a group of statement that is used to perform a specified task which repeatedly occurs
in the main program. By using function, we can divide the complex problem into a manageable
problem. A function can help to avoid redundancy.
43
User-defined function
The function defined by the users according to their context (or) requirements is
The User defined function is written by the programmer to perform specific task (or)
These functions are helpful to break down the large program into a number of the
smaller function.
The user can modify the function in order to meet their requirements.
• Function Declaration
• Function Calling
• Function Definition
1. Function Declaration
2. Function Call
3. Function Definition
Function Declaration
Like normal variable in a program, the function can also be declared before they
The name of the parameter is optional, but the data type is a must.
44
If the function does not return any value, then the return type void is must.
Syntax:
Description:
Parameter list or argument list : list of parameters that the function can convey.
Example:
Function Call
The function call be called by simply specifying the name of the function, return value and
parameters if presence.
Syntax: function_name();
function_name(parameter);
Description:
Example
fun();
fun(a,b);
fun(10,20);
c=fun(a,b);
e=fun(2.3,40);
45
Function Definition
It is the process of specifying and establishing the user defined function by specifying
Syntax:
Example 1
#include<stdio.h>
#include<conio.h>
void main()
clrscr();
getch();
int a,b,c;
scanf(“%d%d”,&a,&b); c=a+b;
printf(‚add=%d‛,c);
int a,b,c;
46
printf(“Enter two values”);
scanf(“%d%d”,&a,&b);
c=a-b;
printf(“sub=%d”,c);
Example 2 :
#include<stdio.h>
#include<conio.h>
void oddoreven()
scanf("%d",&oe);
if(oe%2==0)
else
void main()
clrscr();
oddoreven();
getch();
Function Parameter
The Parameter provides the data communication between the calling function and called
47
function. There are two types of parameters.
Actual parameter: passing the parameters from the calling function to the
called function i.e the parameter, return in function is called actual parameter
Formal parameter: the parameter which is defined in the called function i.e. The
Example:
main()
………..
parameters
………..
Fun(int x,int y)
…………
…………
Example Program
#include<stdio.h>
#include<conio.h>
{ sub=-2.500000
clrscr();
48
add(3,4); //Function call
getch();
int c;
c=a+b;
printf(“add=%d”,c);
float c;
c=a-b;
printf(“sub=%f”,c);
Example 2:
number #include<stdio.h>
int fact(int);
int f;
clrscr();
scanf("%d",&f);
49
printf("The Factorial of given number %d is %d",f,fact(f));
getch();
int fact(int f)
if(f==1) return 1;
else
return(f*fact(f-1));
The functions are classified into four types depends on whether the arguments are present or not,
whether a value is returned or not. These are called function prototype. In „C‟ while defining user
defined function, it is must to declare its prototype. A prototype states the compiler to check the
return type and arguments type of the function.
A function prototype declaration consists of the function‟s return type, name and argument. It
always ends with semicolon. The following are the function prototypes
, no data transfer takes place between the calling function and the called function.
i.e., the called program does not receive any data from the calling program and does not send
back any value to the calling program.
Syntax:-
50
main() void Fun()
{{
………..
………..
………..
………..
Fun();
……….. }
………..
Example program 1
#include<stdio.h>
#include<conio.h>
void mul();
void main()
Output:
mul=24
clrscr();
mul();
getch();
51
}
void mul()
int a,b,c;
scanf(“%d%d”,&a,&b);
c=a*b;
printf(“mul=%d”,c);
Example program 2
//Program for finding the area of a circle using Function with no argument
I#include<stdio.h>
#include<conio.h>
void circle();
void main()
circle();
void circle()
int r;
float cir;
printf("Enter radius");
scanf("%d",&r);
cir=3.14*r*r;
52
printf("The area of circle is %f",cir);
Output:
Enter radius 5
In this prototype, data is transferred from the calling function to called function. i.e., the called
function receives some data from the calling function and does not send back any values to calling
function. It is one way data communication.
Syntax:-
{{
……….. ………..
……….. ………..
Fun(a,b);
……….. }
………..
Example program 1:
#include<stdio.h>
#include<conio.h>
void add(int,int);
void main()
clrscr();
int a,b;
53
printf(“Enter two values”);
scanf(“%d%d”,&a,&b);
add(a,b);
getch();
int c;
c=x+y;
printf(“add=%d”,c);
Example program 2:
//Program to find the area of a circle using Function with argument and no return value
The solid lines indicate data transfer and dotted line indicates a transfer of control.
Output:
add=10
#include<stdio.h>
#include<conio.h>
void circle(int);
void main()
int r;
clrscr();
54
printf("Enter radius");
scanf("%d",&r);
circle(r);
void circle(int r)
float cir;
cir=3.14*r*r;
getch();
Syntax:-
{{
……….. ………..
……….. ………..
c=Fun(a,b); return(z);
……….. }
Example program 1:
#include<stdio.h>
#include<conio.h>
55
void add(int,int);
The solid lines indicates data transfer takes place in between the calling program and called program
Output:
Add=10
Output:
Enter radius 5
void main()
clrscr();
int a,b,c;
scanf(“%d%d”,&a,&b);
c=add(a,b);
printf(“Add=%d”,c);
getch();
int m;
m=x+y;
return m;
Example Program 2
56
// Program to find the area of a circle using Function with argument
#include<stdio.h>
#include<conio.h>
float circle(int);
void main()
int r;
clrscr();
printf("Enter radius");
scanf("%d",&r);
getch();
Output:
Enter radius 5
float circle(int r)
float cir;
cir=3.14*r*r;
return cir;
57
communication
Syntax:-
{{
………..
………..
………..
………..
Fun();
return(z);
……….. }
………..
Example program 1
#include<stdio.h>
#include<conio.h>
int add();
void main()
clrscr();
int z;
z=add();
printf(“Add=%d”,z);
getch();
int add()
58
{
calling program
Output:
Add=10
int a,b,c;
scanf(“%d%d”,&a,&b);
c=a+b;
return c;
Example Program 2
value
#include<stdio.h>
#include<conio.h>
float circle();
void main()
clrscr();
getch();
59
}
float circle()
float cir;
int r;
printf("Enter radious");
scanf("%d",&r);
cir=3.14*r*r;
return cir;
Output:
Enter radius 5
executed. We can pass some of the information (or) data to the function for
They are
1. Call by value
2. Call by reference
Call by Value:
rameter of the
function.
60
because formal parameter are photocopies of the actual parameter.
n.
Once control returns back to the calling function the changes made disappears.
Example Program
#include<stdio.h>
#include<conio.h>
void cube(int);
int cube1(int);
void main()
int a;
clrscr();
scanf(“%d”,&a);
Output:
getch();
void cube(int x)
x=x*x*x;
61
return x;
int cube1(int x)
x=x*x*x;
return x;
Call by reference
Example Program
#include<stdio.h>
#include<conio.h>
void swap(int,int);
void main()
int a=5,b=10;
clrscr();
Output:
swap(&a,&b);
62
printf(“After swapping a=%d b=%d”,a,b);
getch();
int *t;
t=*x;
*x=*y;
*y=t;
Recursion
#include <stdio.h>
Output:
63
Factorial = 120
Discussion:
For 1! , the functions returns 1, for other values, it executes like the one below:
When the value is 5, it comes to else part and calculates like this,
=120
Example :
// Find the maximum number among five different integers using nested function call
and recursion.
int m;
of function max
printf("%d",m);
getch();
64
Output: 11
65
2! = 2*1!
3! = 3*2!
4! = 4*3!
If we start with f = 0! = 1 we can rewrite the first few steps in computing n! as
We know that 0! = 1 = f
f=1 0!
f = f*1 1!
f = f*2 2!
f = f*3 3!
f = f*4 4!
From step (2) onwards we are actually repeating the same process over and over. For the general
(i+1)th step we have,
f = f*i 1<i<n
This general step can be placed in a loop to iteratively generate n!.
Algorithm :
Step 1-> start
Step 2-> Declare the variables fact, i, n
Step 3->initialize fact = 1,i=1
Step 4->Read the value of n from user.
Step 5->Repeat step 4 to 6 until i<=n
Step 6-> fact = fact*i
Step 7-> i =i+1
Step 8-> Print fact
Step 9-> stop
Program:
#include<stdio.h>
#include<conio.h> // preprocessor section
Void main() // main function
{
int n,i,fact=1;
66
printf(“Enter the value of n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
fact = fact*I;
}
printf(“%d”,fact);
}
67