Python Programming Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 92

Introduction to Computer Problem Solving

SCHOOL OF COMPUTING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

UNIT – I - Problem Solving Techniques with C and C++


SCSA1104

1
Introduction to Computer Problem Solving

UNIT 1
INTRODUCTION TO COMPUTER PROBLEM SOLVING

Algorithms, building blocks of algorithms (statements, control flow, functions),


notation (pseudo code, flow chart), algorithmic problem solving for socio
economic conditions in global perspectives, simple strategies for developing
algorithms (iteration, recursion), the efficiency of algorithms.

1.1 Algorithms

An algorithm is a step by step procedure of solving a problem. The word


“algorithm” is derived from the name of the 9th century Persian mathematician Al-
Khwarizmi.

An algorithm is defined as a collection of unambiguous instructions which are


executed in a specific sequence to produce an output in a finite amount of time for a
given set of input data.

An algorithm can be written in English or in any standard representation.

An algorithm must possess the following properties

1. Finiteness: An algorithm must be executed finite number of times.

2. Definiteness: Each step of the algorithm must be accurate and clear.

3. Effectiveness: Each step must be effective, in the sense that it should be


primitive (easily convertible into a program statement) and can be
performed exactly in a finite amount of time.

4. Independent: The algorithm must be independent of any programming


code.

5. Input/output: Each algorithm must take zero or more quantities as input


data and give out one or more output values.
2
Introduction to Computer Problem Solving

Methods for Developing an Algorithm

 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.

 Finally test the algorithm with different data sets.

Example: Algorithm for Addition of two numbers:

Step1: Start

Step 2: Get two numbers a and b as input

Step 3: Add the numbers a & b and store the result in c

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 Building Blocks of Algorithm: The basic building blocks of an algorithm


are Statements, Control flow and Functions.

1.2.1 Statements: Statement may be a single action in a computer.

In a computer statements might include some of the following actions

 input data-information given to the program

 process data-perform operation on a given input

 output data-processed result

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

The three ways in executing the control flow are

 Sequence

 Selection

 Iteration

Sequence

The given set of instructions executed consecutively is called sequence


execution.

Example: Algorithm to find the average of three numbers, the algorithm is as follows

Step1: Start

Step2: Get three numbers a, b, c as input

Step3: Find the sum of a, b and c

Step4: Divide the sum by 3

Step5: Store the result in variable d

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

A selection statement is transferring the program control to a specific part of the


program based upon the condition.

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 2: Get two numbers a and b as input

Step 3: IF a>b THEN

Step 4: PRINT “A is Large”

Step 5: ELSE PRINT “B is Large”

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

Iteration is a type of execution where a certain set of statements are executed


again and again based upon condition. This type of execution is also called as looping
or repetition.

Example: Algorithm to print all natural numbers up to n, the algorithm is as follows

Step 1: Start

Step 2: Get the value of n.

Step 3: Initialize i=1

Step 4: if (i<=n) go to step 5 else go to step 7

Step 5: Print i value and increment i value by 1

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

 Reduction in line of code


 code reuse
 Better readability
 Information hiding
 Easy to debug and test
 Improved maintainability
Example: Algorithm for addition of two numbers using function Main function ()

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

1.3.1 Pseudo Code


Pseudo –False.
Code- Set of Instructions.

Pseudo code means a short, readable set of instructions written in English to explain
an algorithm.

Rules for writing Pseudo code

 Write one statement per line


 Capitalize keywords.
 Indent to hierarchy.
 Keep statements language independent.

Common keywords used in writing a Pseudo code

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:

 Pseudo code is program independent.

 It is easily understandable by layman.

 There is no Standard syntax.

 Pseudo code cannot be compiled or executed.

 It is easy to translate pseudo code into a programming language.

 It can be easily modified as compared to flowchart.


Disadvantages:

 It is not visual.

 We do not get a picture of the design.

 There is no standardized style or format.

 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:

 The flowchart should be clear, neat and easy to follow.

 The flowchart must have a logical start and finish.

 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

 Only one flow line is used with a terminal symbol.

 Within standard symbols, write briefly and precisely.

 Intersection of flow lines should be avoided.

Fig 1.1 Symbols used in Flow chart

9
Introduction to Computer Problem Solving

Advantages:

 Flowcharts help in communicating the logic of a program in a better way.

 The problems can be analyzed effectively with the help of flowchart.

 Flowcharts serve as good program documentation.

 The flowchart is ablueprint for the programmer to code efficiently.

 Flowcharts help in debugging process.

Fig 1.2 Flowchart for adding two numbers

10
Introduction to Computer Problem Solving

Disadvantages:

 The flowcharts are complex and clumsy when the program is large or
complicated.

 Altering or modifying the flowcharts may require re-drawing completely.

 The cost and time taken to draw a flowchart for larger applications are
expensive.

Example: Add two numbers

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.

Example: Print odd numbers from 1 to 100

Fig 1.3 Flowchart to Print odd numbers from 1 to 100

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.

Example: Find the largest of two numbers

Fig 1.4 Flowchart to find the largest of two numbers

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.

Example: Add two numbers using Function

12
Introduction to Computer Problem Solving

Fig 1.5a Flowchart of a calling function

Fig 1.5b Flowchart of a Sub function to add two numbers

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

Difference between Algorithm, Flowchart and Pseudo code

Algorithm Flowchart Pseudo code

An algorithm is a step by It is a graphical It is a language representation


step procedure to solve a representation of algorithm of algorithm.
problem.
User needs knowledge to User does not need User does not need
write algorithm. knowledge of program to knowledge of program
draw or understand language to understand or
flowchart write a pseudo code.

Algorithmic Problem Solving For Socio Economic Conditions in Global


Perspectives: People today have to strive hard to maintain

Providing Food for Everybody

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

Step 7: Get Feedback from beneficiaries as well as public


Step 8: Go to step 2
Step 9: Stop

Fig 1.6 Flowchart for providing food for Everybody

Process A: The number of people below poverty line in each village is


estimated and the total of people in each district is calculated.

Process B: The food committee will recommend the type of food to be


provided and also the quantity of food.

Process C: From the above inputs, the overall cost is calculated.

Process D: The Finance committee decides how to generate the revenue


needed.

15
Introduction to Computer Problem Solving

Process E: Revenue is generated by implementing Tax, Educational Cess,


Import /Export duties etc.

Process F: The distribution of food is carried out through public distribution


system.

Process G: Feedback is provided by the public and beneficiaries which again is


an input to the process to improve the quality of the food provision

Simple Strategies for Developing Algorithms (Iteration, Recursion)

Iterations:

A sequence of statements is executed until a specified condition is true is called


iterations.

1. For loop

2. While loop

Example: Print n Natural numbers using FOR Loop

Algorithm Pseudo code

Step 1: Start BEGIN

Step 2: Get the value of n. GET n

Step 3: Initialize i=1 INITIALIZE i=1

Step 4: if (i<=n) go to step 5 else go to step 7 FOR (i<=n) DO

Step 5: Print i value and increment i value by 1 PRINT i

Step 6: Go to step 4 i=i+1

Step 7: Stop ENDFOR

END

16
Introduction to Computer Problem Solving

Example: Print n Natural numbers using WHILE Loop

Algorithm Pseudo code

Step 1: Start BEGIN


Step 2: Get the value of n. GET n
Step 3: Initialize i=1 INITIALIZE i=1
Step 4: if (i<=n) go to step 5 else go to step 7 WHILE(i<=n) DO
Step 5: Print i value and increment i value by 1 PRINT i
Step 6: Go to step 4 i=i+1
Step 7: Stop ENDWHILE
END

Fig 1.8 Flowchart to print n Natural numbers using WHILE Loop

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:

A function that calls itself is known as recursion.

Recursion is a process by which a function calls itself repeatedly until some


specified condition has been satisfied.

Example: Factorial

Algorithm Pseudo code

Main Function() Main Function()

Step1: Start BEGIN

Step2: Get n GET n

Step3: call factorial(n) CALL factorial(n)

Step4: print fact PRINT fact

Step5: Stop END

Sub function factorial(n) Sub function factorial(n)

Step1: if(n==1) then fact=1 return fact IF(n==1) THEN

Step2: else fact=n*factorial(n-1) and return fact=1 RETURN fact


fact
ELSE

RETURN fact=n*factorial(n-1)

18
Introduction to Computer Problem Solving

Fig 1.9 a) Flowchart of a calling function b) Flowchart of a Sub function to


find factorial of a given number

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.

Difference between Iteration and Recursion

Property Iteration Recursion


A set of instructions repeatedly
Definition
executed. Function calls itself.
Application For loops. For functions.
When the termination condition
Termination for the iterator ceases to be Through base case, where
satisfied. there will be no function call.

19
Introduction to Computer Problem Solving

Property Iteration Recursion


Used when time complexity Used when code size needs to
Usage needs to be balanced against an be small, and time complexity
expanded code size. is not an issue.
Code Size Larger Code Size. Smaller code size
Relatively lower time
Time Complexity
complexity Very high time complexity.

Efficiency of Algorithms: Analysis of an Algorithm

The following are some of the factors which helps in an analyzing an algorithm

 Efficiency
 Simplicity
 Generality
 Range of Growth
 Computing order of growth

The most important factor of all these is efficiency.

Efficiency or Performance Analysis


1. Amount of time required to execute an algorithm(Time Complexity)
2. Amount of storage required by an algorithm(Space Complexity)

Time Complexity

 Time complexity of an algorithm is the total time required by the algorithm to


run.
 To compute time we require two components – Variable part and fixed part.
 Variable Part - Run time
 Fixed Part - Compile time

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.

Calculation of Time Complexity

We use step count method to calculate the time complexity of an algorithm.

For example
int sum(int a[],int n)
{
Int sum=0
For (int i=0;i<n;i++)
{
Sum=sum+a[i]
}
Return sum
}

Instruction Step count


int sum(int a[],int n) 0
{ 0
Int sum=0 1
For (int i=0;i<n;i++) n+1
{
Sum=sum+a[i] N
} 0
Return sum 1
} 0
Total steps=1+n+1+n+1=2n+3

21
Introduction to Computer Problem Solving

Space Complexity: Space complexity of an algorithm is the amount of memory


space required by the algorithm to run.

Reason for estimating space before running the program

 To know if the memory is sufficient

 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.

Space complexity S(P) = C + SP,

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.

And SP is the variable space is a space dependent upon instance characteristics.

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

Data space: The amount of memory space used by Constants, variables,


arrays, structures and other data structures.

Environment stack space: When we use a function, we will require a stack to


store the return address of the main function (Calling function). This space is the
environment stack space.

22
Introduction to Computer Problem Solving

Calculation of Space complexity

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(int a[],int n)

Int sum=0

For (int i=0;i<n;i++)

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.

 4 bytes each for sum, n, i and the return value.

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

 Clean Water for All

 Generating Energy at Low Costs

 Smart Cities

 Education for all

 Tower of Hanoi Problem

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

Department of Computer Science and Engineering

UNIT - II

Problem Solving Techniques


with C and C++ - SCSA1104

1
UNIT II BASICS OF C PROGRAMMING

Introduction to C: Features of C - Structure of C program-Data Types-‘C’ Tokens-


Input/output statements-Control Statement, Functions: – Types of Functions –
Recursion. Algorithms: Reversing the digits of a number - Generation of Fibonacci
sequence- Factorial Computation.

1. Introduction to C

C programming is a general-purpose, procedural programming language developed in


1972 by Dennis M. Ritchie at the Bell Telephone Laboratories to develop the UNIX
operating system. It is machine-independent, structured programming language which is
used extensively in various applications. Many later languages have borrowed
syntax/features directly or indirectly from C language. Like syntax of Java, PHP, JavaScript,
and many other languages are mainly based on C language. C++ is nearly a superset of C
language (There are few programs that may compile in C, but not in C++).

1.1 History of C language

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

'C' language is widely used in embedded systems.

 It is used for developing system applications.

 It is widely used for developing desktop 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'.

 It is used in developing an operating system. Operating systems such as Apple's OS X,


Microsoft's Windows, and Symbian are developed using 'C' language. It is used for
developing desktop as well as mobile phone's operating system.

 It is used for compiler production.

 It is widely used in Internet of Things (IOT) applications.

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.

2.2 Machine Independent or Portable

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.3 Mid-level programming language


The C compiler combines the capabilities of an assembly language with the features of a high-
level language and therefore it is well suited for writing both system software and business
packages. In fact, many of the C compilers available in the market are written in C.
2.4 Structured programming language.
C language is well suited for structured programming, thus requiring the user to think of a
problem in terms of function modules or blocks. A proper collection of these modules would
make a complete program. This modular structure makes program debugging, testing and
maintenance easier.

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.

3.1 Document Section

 A comment is an explanation or description of the source code of the program. It helps a


developer explain logic of the code and improves program readability.

 At run-time, a comment is ignored by the compiler.

There are two types of comments in C:

1) Single line comment

2) Multi Line Comment

Example :

// Single line comment

//Multi Line Comment

//Line 1

//Line 2

(Or)

/* Multi line comment are used in the program

Line 1…
Line 2….
…..,
………

6
*/

3.2 Preprocessor Section or Link Section or

Header File Section

 The link section provides instructions to the


compiler to link functions from the library.

 A header file is a file with extension .h which


contains C function declarations and macro
definitions to be shared between several source
files.

Some of C Header files:

 stdio.h – Defines core input and output


functions

 string.h – Defines string handling functions

 math.h – Defines common mathematical


functions Fig 3. Structure of C program

Syntax to include a header file in C:

#include<filename>

Example:

#include<stdio.h>

#include<math.h>

#include<string.h>

3.3 Definition Section

 The definition section defines all symbolic constant.

 Symbolic constant is a way of defining a variable constant whose value cannot be


changed

Syntax:

7
#define symbolic constant value

Example

#define MAX 100

#define PI 3.14

3.4 Global Declaration Section:

 The variables that are used in more than one function throughout the program are called
global variables.

 Should be declared outside of all the functions i.e., before main().

3.5 Main Method Declaration:

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.

Syntax to Declare main method

int main() or void main()

{}

It contains the following two parts

1. Declaration Part
2. Executable part

3.5.1 Declaration 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

Data type variable name;

Example:

Void main()

8
{

int a;

3.5.2 Execution Part:

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.

3.6 Sub Program section

 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.

 This is optional to the programmer.

Constraints while writing a C program

• 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.

• All the statements should end with a semicolon (;)

3.7 Example to illustrate structure of C program

// Program to illustrate structure of C program // Document section //Single line comment

#include<stdio.h> // Link Section

#define PI 3.14; // Definition Section

float area(float r); // Global Declaration section

int main() //Main Function

9
{

float r; // Declaration Part

printf(" Enter the radius:n"); // Executable Part

scanf("%f",&r);

printf("the area is: %f",area(r));

return 0;

float area(float r)

return pi * r * r; //sub program or User defined function

3.8 Compilation and Execution of C program

1. Creating the program

2. Compiling the Program

3. Linking the Program with system library

4. Executing the program

3.8.1 Creating the program:

 Type the program and edit it in standard „C‟ editor and save the program with .c as an
extension.

 This is the source program.

10
Fig.4 Creating the program

3.8.2 Compiling (Alt + F9) 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

3.8.3 Linking the program with system Library


 Before executing a c program, it has to be linked with the included header files and
other system libraries -> Done by the Linker

3.8.4 Executing the Program:


 This is the process of running (Ctrl + F9) and testing the program with sample data. If
there are any run time errors, then they will be reported.

12
Fig. 6 Executing the program

3.9 ‘C’ TOKENS

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

Keywords Constants Strings Operators

Float -15.7 “ABC” +,-


While 66 “year” *,/,
Identifiers Special %
Main Symbols [], {}
amount
13
3.1 Keywords

 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.

 Both uppercase and lowercase letters are permitted.

 The underscore character is also permitted in identifiers.

Rules for Identifiers

1. First character must be an alphabet (or underscore).

2. Must consist of only letters, digits or underscore.

3. Cannot use a keyword. excempted

4. Must not contain white space

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.

 C supports several types of constants as illustrated in Fig.7.

Fig.8. Constants

3.3.1 Integer Constant:

 An integer constant refers to a sequence of digits.

Example:

123

124 – 321 0 654321 +78

3.3.2 Real or floating point constants:

 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.

 Such numbers are called real (or floating point) constants.

Example:

0.0083 –0.75 435.36 +247.0

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

„5‟ „X‟ „;‟ „ ‟

3.3.4 String constants

 A string constant is a sequence of characters enclosed in double quotes. The characters


may be letters, numbers, special characters and blank space.

Examples

“Hello!” “1987” “WELL DONE” “?...!” “5+3” “X”

Backslash character constants

 C supports some special backslash character constants that are used in output functions.

 For example, the symbol „\n‟ stands for newline character.

 Each one of them represents one character, although they consist of two characters.

 These characters combinations are known as escape sequences.

Table 1. Backslash character constants

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

string is a number of characters that the string contains.

Now, we describe the strings in different ways:

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.

char a[10] = {'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented in the form of


characters.

3.5 Operators and Expressions in C

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:

3.5.1 Unary Operator

A unary operator is an operator applied to the single operand. For example: increment

operator (++), decrement operator (--), sizeof, (type)*.

3.5.2 Binary Operator

The binary operator is an operator applied between two operands. The following is the list

of the binary operators:

17
1. Arithmetic operators

2. Relational operators

3. Logical operators

4. Assignment operators

5. Increment and decrement operators

6. Conditional operators

7. Bitwise operators

8. Special operators

3.5.2.1 Arithmetic Operators


 C provides all the basic arithmetic operators such as +, –, *, and /
 Integer division truncates any fractional part.
 The modulo division operation produces the remainder of an integer division.
Examples
a–b a/b
a+b a%b
a*b –a * b
Arithmetic Operators can be classified as:
1. Integer Arithmetic
2. Real Arithmetic
3. Mixed mode Arithmetic

3.5.2.1.1 Integer arithmetic Table 2. Arithmetic 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

a/b 3(decimal part truncated)

a%b 2( remainder of division)

Table 3. Arithmetic Operation

Here in the above example we are using only integer values.

3.5.2.1.2 Real arithmetic

 An arithmetic which is involving real values (decimal values) is called real arithmetic.

 If x, y, and z are floats, then we will have:

• x = 6.0/7.0 = 0.857143

• y = 1.0/3.0 = 0.333333

• z = –2.0/3.0 = –0.666667

3.5.2.1.3 Mixed mode arithmetic

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.

E.g. Float a=10.5; Int b=30; C=a+b; //c=40.5

Eg. 15/10.0 =1.5

This type of expression that c=a+b is called mixed arithmetic.

Example

19
#include<stdio.h>

#include<conio.h>

main ()

int months, days ;

printf(“Enter days\n”) ;

scanf(“%d”, &days) ;

months = days / 30 ;

printf(“Months = %d” , months) ;

3.5.2.2 Relational operator

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.

Table 4: Relational Operators

An expression such as a<b or 1 < 20 containing a relational operator is termed as a relational


expression. The value of a relational expression is either one or zero. It is one if the specified
relation is true and zero if the relation is false.

Example 10 < 20 is true but 20 < 10 is false

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");
} }

3.5.2.3 Logical operators

In addition to the relational operators, C has the following three logical operators.
&& meaning logical AND
|| meaning logical OR
! meaning logical NOT

Table 5 Truth Table Logical operators


The logical operators are used when we want to check more than one condition and make
decision. An expression of this kind, which combines two or more relational expressions, is

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

1. if (age > 55 && salary < 1000)

2. if (number < 0 || number > 100)

Example Program

#include<stdio.h>

#include<conio.h>

Void main()

int a =20, b =10;

if(a>b && a>c)

printf(“a is greater”);

else

printf(“a is not greater”);

It combines two or more relational expressions

3.5.2.4 Assignment operator

Assignment operators are used to assign the result of an expression to a variable.

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.

Table : 6 Statement with assignment and shorthand operator

The use of short hand operator has three advantages


• What appears on the left-hand side need not be repeated and therefore it becomes easier to
write.
• The statement is more concise and easier to read.
• The statement is more efficient.
Example Program
#include <stdio.h>
int main()
{
int number1, number2, sum;

23
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
// calculating sum
sum = number1 + number2;
printf("%d %d %d", number1, number2, sum);
return 0;
}

3.5.2.5 Increment and decrement operator

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

3.5.2.6 Conditional operator

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;
}

3.5.2.7 Bitwise operators

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

3.5.2.8 Special operators

C supports some special operators such as comma(,) operator, sizeof operator, pointer operator.

Comma operator can be used to link related expressions

25
Eg.

int a,b, c=a+b;

sizeof operator is used to find the size of the variable or identifier.

Eg.

M= sizeof (a);

Here in the above example the size of a will be assigned to M.

3.6 Data Types

• 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.

Table 8. Size and Range of data types on 16-bit machines

3.7 Variables

 A variable is a data name that may be used to store a data value.


 Unlike constants that remain unchanged during the execution of a program, a variable
may take different values at different time during execution.
 A variable name can be chosen by the programmer in a meaningful way.
Example
• Average
• Height
• Total
• Counter_1
• class_strength
variable names may consist of letters, digits, and the underscore(_) character
Conditions to write variable name
 They must begin with a letter.
 Length should not be normally more than eight characters, since only the first eight
characters are treated as significant by many compilers.
 Uppercase and lowercase are significant.
 It should not be a keyword.
 White space is not allowed

3.7.1 Declaration of 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.

2. It specifies what type of data the variable will hold.

 The declaration of variables must be done before they are used in the program.
Syntax:

Data_type v1; // For single variable declaration

e.g: int count;

data-type v1,v2,....vn ; // For multiple variable declaration

eg: int number, total;

3.7.2 Assigning values to the variables:

Values can be assigned to variables using the assignment operator = as follows:

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:

data-type variable_name = constant;

Examples

int final_value = 100;

char yes = „s‟;

 The process of giving initial values to variables is called initialization.

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;

3.8 Input and Output Statements

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

printf( ) is predefined ,standard C function for printing output.

The general form of printf() is,

printf(“<format string>”,<list of variables>);

<format string> could be,

%f for printing real values.

%d for printing integer values.

%c for printing character values.

Eg: printf(“%f”,si);

printf(“%d”,i);

scanf() statement

29
scanf( ) is a predefined,standard C function used to input data from keyboard.

The general form of scanf() is

scanf(“<format string>”,<address of variables>);

Eg: scanf(“%d”,&n);

scanf(“%f”,&interest);

& is pointer operator which specifies the address of that variable.

#include<stdio.h>

int main()

int number;

printf("enter a number:");

scanf("%d",&number);

printf("cube of number is:%d ",number*number*number);

return 0;

getchar() & putchar() functions

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.

3.9 Control Flow Statements

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.

There are three types of control flow statements:

 Branching / Decision Making Statements

 Iterative / Looping Statements

 Jumping Statements

3.9.1 Decision Making Statements

C program executes program sequentially. Sometimes, a program requires checking of


certain conditions in program execution. C provides various key condition statements to check
condition and execute statements according conditional criteria. These statements are called as
'Decision Making Statements' or 'Conditional Statements.'

C language possesses such decision-making capabilities by supporting the following


statements:

1. if statement

2. switch statement

3. Conditional operator statement

4. goto statement

These statements are popularly known as decision-making statements. Since these

31
statements „control‟ the flow of execution, they are also known as control statements.

3.9.1.1 Decision Making with IF Statement

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

3. 3. Nested if....else statement

4. 4. else if ladder.

3.9.1.1.1 Simple if statement

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 {false statement;}

else{statements;}

Example:

#include<stdio.h>

void main()

int a,b,c;

a=5, b=6, c=8;

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();

3.9.1.1.4 Else if ladder

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;

a=5, b=6, c=7;

35
if(a>b && a>c){

printf(“a is big”);

else if(b>c){

printf(“b is big”);

else{

printf(“c is big”);

getch();

3.9.1.2 Switch Case Statements

• 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();

3.9.1.3 Looping Statements

'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.

• There are two types of looping statements.

 Entry controlled loop

37
While Loop

For Loop

 Exit controlled loop

Do While Loop

3.9.1.3.1 Entry Control 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:

for(initialization; test-condition; increment/decrement)

Statements;

Example

#include<stdio.h>

void main() {

int i;

clrscr(); i=1;

for(i=1;i<=20; i+=2) {

printf(“%d\t”,i);

getch();

3.9.1.3.2 Exit Control

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();

3.9.1.2.4 JUMPING STATEMENTS

There are three types of jumping statements:

• 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.

Function can be of two types, there are

1. Built-in Function (or) Predefined Function (or) Library Function

2. User defined Function


Difference between Predefined and User-defined Functions

43
User-defined function

 The function defined by the users according to their context (or) requirements is

known as a user defined function.

 The User defined function is written by the programmer to perform specific task (or)

operation, which is repeatedly used in the main program.

 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.

 Every user define function has three parts namely

• Function Declaration

• Function Calling

• Function Definition

Elements of User-Defined Function

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

 defined and invoked

 Function declaration must end with semicolon (;)

 A function declaration must declare after the header file

 The list of parameters must be separated by comma.

 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.

 If there are no parameters, simply place void in braces.

 The data type of actual and formal parameter must match.

Syntax:

Return_type function_name (datatype parameter1, datatype parameter2,…);

Description:

Return type : type of function

Function_name : name of the function

Parameter list or argument list : list of parameters that the function can convey.

Example:

int add(int x,int y,int z);

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);

return_value =function_name (parameter);

Description:

function_name : Name of the function

Parameter : Actual value passed to the calling function

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

all of its element and characteristics.

Syntax:

Return_type function_name (datatype parameter1, datatype parameter2)

Example 1

#include<stdio.h>

#include<conio.h>

void add(); //Function Declaration void sub();//Function Declaration

void main()

clrscr();

add(); //Function call

sub(); //Function call

getch();

void add() //Function Definition

int a,b,c;

printf(“Enter two values”);

scanf(“%d%d”,&a,&b); c=a+b;

printf(‚add=%d‛,c);

void sub() //Function Definition

int a,b,c;

46
printf(“Enter two values”);

scanf(“%d%d”,&a,&b);

c=a-b;

printf(“sub=%d”,c);

Example 2 :

//Program to check whether the given number is odd or even

#include<stdio.h>

#include<conio.h>

void oddoreven()

printf("Enter One value");

scanf("%d",&oe);

if(oe%2==0)

printf("The Given Number%d is even");

else

printf("The Given Number %d is odd");

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

parameter, return in the function definition is called formal parameter

Example:

main()

……….. Where ……….. a,b are the actual Fun(a,b);

………..

parameters

………..

} x,y are formal parameter

Fun(int x,int y)

…………

…………

Example Program

#include<stdio.h>

#include<conio.h>

void add(int,int); //Function Declaration Output:

void sub(float,int);//Function Declaration

void main() add=7

{ sub=-2.500000

clrscr();

48
add(3,4); //Function call

sub(2.5,5); //Function call

getch();

void add(int a,int b)//Function Definition

int c;

c=a+b;

printf(“add=%d”,c);

void sub(float a, int b) //Function Definition

float c;

c=a-b;

printf(“sub=%f”,c);

Example 2:

//program for factorial of given

number #include<stdio.h>

#include<conio.h> void main()

int fact(int);

int f;

clrscr();

printf("Enter one value");

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));

Output: Enter one value 5

The Factorial of given number 5 is 120

Function Prototype (or) Function Interface

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

 Function with no argument and no return value.

 Function with argument and no return value.

 Function with argument and with return value.

 Function with no argument with return value.

Function with no argument and no return value

, 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()

The dotted lines indicates that,

there is only transfer of control,

but no data transfer.

Output:

Enter two values 6 4

mul=24

clrscr();

mul();

getch();

51
}

void mul()

int a,b,c;

printf(“Enter two values”);

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

and no return value

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

The area of circle 78.500000

Function with argument and no return value

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:-

main() void Fun(x,y)

{{

……….. ………..

……….. ………..

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();

void add(int x,int y)

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.

a and b are the actual parameters

x and y are formal parameters

Output:

Enter two values 6 4

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;

printf("The area of circle is %f",cir);

getch();

Function with argument and with return value.

called function. i.e., the


called function receives some data from the calling function and sends back returned value to the
calling function. It is two way data communication

Syntax:-

main() int Fun(x,y)

{{

……….. ………..

……….. ………..

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

a,b are the actual parameter x,y are formal parameter

Output:

Enter two values 6 4

Add=10

Output:

Enter radius 5

The area of circle 78.500000

void main()

clrscr();

int a,b,c;

printf(“Enter two values”);

scanf(“%d%d”,&a,&b);

c=add(a,b);

printf(“Add=%d”,c);

getch();

void add(int x,int y)

int m;

m=x+y;

return m;

Example Program 2

56
// Program to find the area of a circle using Function with argument

and with return value

#include<stdio.h>

#include<conio.h>

float circle(int);

void main()

int r;

clrscr();

printf("Enter radius");

scanf("%d",&r);

printf("the area of circle is %f",circle(r));

getch();

Output:

Enter radius 5

the area of circle 78.500000

float circle(int r)

float cir;

cir=3.14*r*r;

return cir;

Function with no argument with return value

function, but the


called program may send some return value to the calling function. It is one way data

57
communication

Syntax:-

main() int Fun()

{{

………..

………..

………..

………..

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
{

The dotted line indicates a

control transfer to the called

program and the solid line

indicates data return to the

calling program

Output:

Enter two values 6 4

Add=10

int a,b,c;

printf(“Enter two values”);

scanf(“%d%d”,&a,&b);

c=a+b;

return c;

Example Program 2

// Program to the area of a circle using no argument with a return

value

#include<stdio.h>

#include<conio.h>

float circle();

void main()

clrscr();

printf("the area of circle is %f",circle());

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

the area of circle 78.500000

Parameter Passing Methods (or) Passing Arguments to Function

can be called whenever required.

executed. We can pass some of the information (or) data to the function for

processing is called a parameter.

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();

printf(“Enter one values”);

scanf(“%d”,&a);

Output:

Enter one values 3

Value of cube function is 3

Value of cube1 function is 27

printf(“Value of cube function is=%d”, cube(a));

printf(“Value of cube1 function is =%d”, cube1(a ));

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

address is used to access arguments used in the call.

changes made in the arguments are permanent.

Example Program

#include<stdio.h>

#include<conio.h>

void swap(int,int);

void main()

int a=5,b=10;

clrscr();

printf(“Before swapping a=%d b=%d”,a,b);

Output:

Before swapping a=5 b=10

After swapping a=10 b=5

swap(&a,&b);

62
printf(“After swapping a=%d b=%d”,a,b);

getch();

void swap(int *x,int *y)

int *t;

t=*x;

*x=*y;

*y=t;

Recursion

A function calling same function inside itself is called as recursion.

Example: // C program to find the factorial of a number.

#include <stdio.h>

int fact(int); // function declaration

void main() // main function

printf("Factorial =%d",fact(5)); // fact(5) is the function call

int fact(int n) // function definition

if (n==1) return 1; else

return n * fact(n-1); // fact(n-1) is the recursive function call

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,

= 5 * fact (5-1) = 5 * fact (4)

= 5* 4* fact (4-1) = 5 * 4* fact (3)

= 5* 4* 3* fact (3-1) = 5 * 4* 3* fact (2)

= 5* 4* 3* 2* fact (2-1) = 5 * 4* 3* 2* fact (1)

= 5* 4* 3* 2* 1 (if (n==1) then return 1, hence we get 1)

=120
Example :

// A program that contains both nested functions and recursion in it.

// Find the maximum number among five different integers using nested function call

and recursion.

int max(int x,int y) // function defintion

return x>y ? x:y; // condition operator is used (exp1?exp2:exp3)

void main() // main function

int m;

m=max(max(4,max(11,6)),max(10,5)); //nested, recursive call

of function max

printf("%d",m);

getch();

64
Output: 11

3.10 Factorial computation


Given Problem:
Given a number n, compute n factorial where n>=0
Algorithm Development:
Definition: Factorial of a positive integer n is product of all values from n to 1. For example, the
factorial of 3 is (3 * 2 * 1 = 6).
We are given that
5! = 1*2*3*4*5
n =5
n! = 1*2*3*4…………*(n-1)*n for n>=1
and by definition
0! = 1
Applying the factorial definition we get
0! = 1
1! = 1*1
2! = 1*2
3! = 1*2*3
4! = 1*2*3*4
5! =1*2*3*4*5
We see that 5! contains all the factors of 4!. The only difference is the inclusion of the
number 5. We can generalize this by observing that n! can always be obtained from (n-1)! By
simply multiplying it by n.
n! = n*(n-1)! for n>=1
using this definition we can write the first few factorials as
1! = 1*0!

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

You might also like