Structured Programming in C Module - I
Structured Programming in C Module - I
Algorithmic Approach
An algorithmic approach is a method of solving a problem by designing step-by-step
procedure (an algorithm) that can be followed to complete a task.
In other words:
this input to produce output. All the inputs must gather before
execution of the algorithm begins.
e) Output: An algorithm has one or more outputs. After perform operations
on input, an output will be generated.
Examples of Algorithm
Example 1:
Write an algorithm that calculates the sum and average of three numbers.
Step 1: Start
Step 2: Input a, b and c values.
Step 3: Calculate sum= a+b+c
Step 4: Calculate avg = (float)sum/3
Step 5: Write sum
Step 6: Write avg
Step 7: stop.
Example 2:
Write an algorithm to convert temperature from Fahrenheit to Celsius.
Step 1: Start
Step 2: Input F value.
Step 3: Calculate C=(F-32)*5/9
Step 4: Write C
Step 5: stop.
Page 1
STRUCTURED PROGRAMMING USING C UNIT - I
Example 3: Write an algorithm which swaps two numbers/ interchange two numbers.
Using Temporary Variable Without using temporary Using bitwise operators
variable
Step 1: Start Step 1: Start Step 1: Start
Step 2: Input a, b values Step 2: Input a, b values Step 2: Input a, b values
Step 3: Calculate t=a Step 3: Calculate a=a+b Step 3: Calculate a=a^b
Step 4: Calculate a=b Step 4: Calculate b=a-b Step 4: Calculate b=a^b
Step 5: Calculate b=t Step 5: Calculate a=a-b Step 5: Calculate a=a^b
Step 6: Write a Step 6: Write a Step 6: Write a
Step 7: Write b Step 7: Write b Step 7: Write b
Step 8: Stop Step 8: Stop Step 8: Stop
Example 4:
Algorithm to find area of triangle using heron’s formula.
Sept 1:- Start
Sept 2:- Input 3 sides (a, b, c) values
Sept 3:- Calculate s= (a+b+c)/2
Sept 4:- Calculate area=sqrt( s*(s-a)*(s-b)*(s-c))
Sept 5:- Write area
Step 6:- Stop
Example 5:
Algorithm to find distance travelled by an object.
Sept 1:- Start
Sept 2:- Input (Acceleration value) a
Sept 3:- Input (Initial velocity) u
Sept 4:- Input (Time taken) t
Sept 5:- Calc d=u*t+((float)1/2)*a*(t*t)
Step 6:- Write d
Step 7:- Stop
Example 6:
Algorithm to find net salary of an employee:
Sept 1:- Start
Sept 2:- Input basic, hra, da, pf values
Sept 3:- Calculate net_salary=basic+hra+da-pf
Sept 4:- Write net_salary
Sept 5:- stop
Example 7:
Algorithm to take 3 sides of a triangle. Print whether triangle can be drawn or not.
Sept 1:- Start
Sept 2:- Write “Enter length of 3 sides of triangle”
Sept 3:- Input A,B,C
Sept 4:- if A+B>C && B+C>A && C+A>B then
Write “Triangle Can be drawn”,
goto step5.
else
Write “Triangle cannot be drawn”.
Step 5:- stop
Example 8:
Write an algorithm which finds the biggest number among three numbers.
Page 2
STRUCTURED PROGRAMMING USING C UNIT - I
Step 1: Start
Step 2: Input a, b, c values
Step 3: If a> b && a>c then
Write “A is big”
else if b>c then
Write “B is big”
else
Write “ c is big “
Step 4: Stop
Example 9:
Write an algorithm which checks whether a no is odd number or even number.
Step 1: Start
Step 2: Input no
Step 3: If no%2=0 then
Write “Even number”
else
Write “Odd number”
Step 4: Stop
Example 10:
Write an algorithm to take percentage of marks. Print the grade.
Step 1: Start
Step 2: write “enter percentage of marks”
Step 3: input p
Step 4: if p>=75 then
Write “Distinction”
else if p>=60 then
Write “First Class”
else if p>=50 then
Write “Second Class”
else
Write “Third Class”.
Step 5: stop.
Flowchart
Flowchart is a graphical representation of an algorithm.
Flowchart is a picture, it explains how data is read, compute and display result.
Flowchart uses symbols, shapes and arrow.
The symbols form a diagram that represents an algorithm.
This is very helpful in understanding complicated programs.
Flowchart is used before writing actual program.
Flowchart should be clear, neat and easy to follow.
Symbols used in Flowchart
Symbol Name Purpose
Comment The Comment symbol adds documentation to
the flowchart for the readers. Comments are
ignored during the flowchart execution.
Page 3
STRUCTURED PROGRAMMING USING C UNIT - I
Purpose of Flowchart
Page 4
STRUCTURED PROGRAMMING USING C UNIT - I
Examples
Page 5
STRUCTURED PROGRAMMING USING C UNIT - I
Page 6
STRUCTURED PROGRAMMING USING C UNIT - I
Example 4: Draw the flowchart which finds the biggest number among two numbers.
Page 7
STRUCTURED PROGRAMMING USING C UNIT - I
Page 8
STRUCTURED PROGRAMMING USING C UNIT - I
Example 6: Draw the flow chart which finds the factorial of given numbers.
Practice Sheet 1
History of C language
In the early 1960s, computer scientists worked with low-level languages, which were
hard to write and maintain.
To make programming easier, higher-level languages like ALGOL were created in 1960,
but they were still not perfect for system software.
In 1966, Martin Richards developed BCPL (Basic Combined Programming Language),
mainly used for writing compilers and system software.
In 1969, Ken Thompson improved BCPL to B, B is mainly used to develop UNIX
operating system.
In 1972, Dennis Ritchie improved B to C at AT&T Bell Laboratory.
Compiler vs Interpreter
Compiler Interpreter
Compiler is software which translate entire Interpreter is software which translate source
source code into machine code at once. code into machine code line by line.
Generate executable file Does not generate executable file
Program executes faster program executes slowly
It shows all the errors at once. It shows errors one by one
Use more memory. Use less memory.
Examples: C, C++, JAVA Examples : python, Java Script
Recompilation is required when we do the Recompilation is not required when we do the
modifications to program,. modifications to program.
Source code does not require for later Source code is required for later execution.
execution.
CPU utilization is more CPU utilization is low
Features of C
Key Features of C are
1. Middle Level Language :- C is a middle-level language because it supports features of
low-level language and high-level languages.
2. Case sensitive language :- C is called a case-sensitive language because it distinguishes
between uppercase and lowercase. For example, variable, VARIABLE,
and Variable would be treated as three distinct entities in C.
3. Structured programming language :- C is a structured programming language
because it supports modular programming by allowing code to be broken into
functions, improving clarity and reuse.
4. Procedure-Oriented Programming Language :- C is a procedure-oriented
Page 10
STRUCTURED PROGRAMMING USING C UNIT - I
Applications of C
Operating System C is used to develop operating systems like UNIX and Linux, enabling
Development efficient management of hardware and system resources.
Compilers and Many compilers are written in C, facilitating the translation of high-level
Interpreters code into machine-executable instructions.
Database Systems High-performance databases like MySQL and Oracle utilize C for
efficient data management, query processing, and transaction
handling.
Game Development and C is used in developing game engines for titles like Doom and Quake,
Graphics enabling high-performance graphics rendering and real-time
processing.
System Utilities and Essential utilities such as grep and the GNU Core Utilities are built with
Command-Line Tools C, providing fast and powerful system-level functionalities.
Page 11
STRUCTURED PROGRAMMING USING C UNIT - I
Structure of C Program
Function-n
Documentation Section:
To enhance the readability of the program, programmers can provide comments about
the program in this section. The comments are included between the delimiters /* and
*/.
Example:
/*Write a program to find sum of 2 numbers */
These statements are not executable rather they are ignored by the compiler.
Comments can be used anywhere in the program.
Link Section:
This section instructs the compiler to link functions from the “C‟ library. Library
functions are grouped category wise and stored in different files known as header files.
If we want to access the functions stored in the library, it is necessary to tell the
compiler about the files to be accessed. This can be done through a preprocessor
directive #include <filename>
Ex: #include<stdio.h>
This statement instructs the compiler to copy the content of “stdio.h” into our program
before starting the compiling step.
Definition Section:
It is used to define symbolic constants and to define macros. The preprocessor directive
#define is used for the purpose.
Page 12
STRUCTURED PROGRAMMING USING C UNIT - I
The declaration part declares all the variables that are used in the executable part.
There is at least one statement in the executable part. These two parts can appear
between the opening and closing braces. In all C programs execution begins at this
opening brace and ends at this closing brace. The closing brace of this function is the
logical end of the program. All the declaration and executable statements end with a
semicolon.
Example :
void main()
{
Declaration part
Execution part
}
Subprogram Section:
This section contains user defined functions that are used in the main function. User
defined functions are generally placed immediately after the main function.
All Sections except the main function section may be absent when they are not required.
Example Program:
/* A Sample C program */ /* documentation section*/
#include <stdio.h> /* Link section*/
#define PI 3.14 /* Definition section*/
int area; /*global variables declaration part*/
/*main( ) function section begins*/
main( )
{
int radius; /*local variables declaration part*/
printf(“Enter radius : “);
scanf(“%d”, &radius);
Page 13
STRUCTURED PROGRAMMING USING C UNIT - I
find_area(radius);
printf(“area of the circle = %d”,area);
}
/* main() function section ends*/
/* sub function section begins*/
void find_area(int radius)
{
area=PI*radius*radius;
}
/* sub function section ends*/
Tokens of C Language
Tokens in C are the most important elements to be used in creating a program in C. We can
define the token as the smallest individual element in C. For `example, we cannot create a
sentence without using words; similarly, we cannot create a program in C without using
tokens. Therefore, we can say that tokens in C are basic components for creating a program.
1. Identifiers :-
Identifiers are the names allocated to variables or methods or functions or user defined
references like arrays, structures, unions, enums and constants. Identifiers names should
be unique. Identifiers names should be meaningful. These consist of a sequence of letters,
digits and underscore. Both uppercase and lowercase letters are permitted but commonly use
lower case letters. Name of identifier is Case Sensitive. Identifiers cannot be used as
keywords. Identifiers should be written in such a way that it is meaningful, short, and easy to
read.
Examples 1:
int a;
char ch;
Here “a” and “ch” are identifiers of variables
Example 2:
void main()
{
//code
Page 14
STRUCTURED PROGRAMMING USING C UNIT - I
}
Here main is identifier of function.
Example 3:
struct Student
{
int no;
char sname[100];
};
Here Student is identifier of structure.
Example 4:
#define PI 3.14
Here PI is identifier of constant.
2. Keywords :-
Keywords are the pre defined identifiers. Keywords are the system defined identifiers.
Keywords are the reserved words. Keywords are words that have special meaning. We
should not change the meaning of keywords. If we try the change its meaning then we
will get error. Keywords are part of the syntax. These cannot be used as an identifier. All
keywords must be written in lowercase. C language provides 32 keywords.
Examples
char int float double
void long short signed
unsigned if else switch
case default while for
do goto break continue
struct union enum typedef
auto static register extern
return const sizeof volatile
3. Constants / Literals
Constant is a container that retains its value until program termination. The value of
constant cannot be changed. If we try to change the value of constant then we will get
an error. “C‟ supports several types of constants as shown in the figure. Constant name
Page 15
STRUCTURED PROGRAMMING USING C UNIT - I
4. Special Characters :
Some special characters are used in C, and they have a special meaning which cannot be
used for another purpose.
o Square brackets [ ]: The opening and closing brackets represent the single and
multidimensional subscripts.
o Simple brackets ( ): It is used in function declaration and function calling. For example,
printf() is a pre-defined function.
o Curly braces { }: It is used in the opening and closing of the code. It is used in the
opening and closing of the loops.
o Comma (,): It is used for separating for more than one statement and for example,
separating function parameters in a function call, separating the variable when printing
the value of more than one variable using a single printf statement.
o Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes
that we are using the header file.
o Asterisk (*): This symbol is used to represent pointers and also used as an operator for
multiplication.
o Tilde (~): It is used as a destructor to free memory.
o Period (.): It is used to access a member of a structure or a union.
5. Strings :- Strings are nothing but an array of characters ended with a null character (‘\0’).
This null character indicates the end of the string. Strings are always enclosed in double
quotes.
Example : +, -, *, /, %, =, ==, !=, >, <, >=, <=, &&, ||, ++, --
Usually the input is given & output is viewed on the screen with the help of input &
output functions in C. The standard or regularly used I/O functions are:
printf () :–
------------------------------
Page 17
STRUCTURED PROGRAMMING USING C UNIT - I
It stands for print formatted. It is a formatted output function. It sends a formatted string to
output devices. It is used to print output on screen. It is a general purpose output function.
It can print any type of data. It can print multiple values at a time. It executes from right side
to left side. It was defined in “stdio.h”. It returns how many bytes of information get printed
successfully on screen.
Syntax :
int printf(“Format Specifiers / formatted string”,variable1,variable2…);
here formatted string contains the text to be displayed on screen. The general form of
formatted string is “%[flag][width][.precision][length]specifier”.
Explanation :
printf(“% - 10.2lf”,salary);
Here
“-“ is called flag
10 is width
2 is precision
“l” is length
“f” is specifir
Page 18
STRUCTURED PROGRAMMING USING C UNIT - I
}
The above two input & output functions are also known as formatted I/O functions.
Page 19