0% found this document useful (0 votes)
30 views19 pages

Structured Programming in C Module - I

Uploaded by

rakesh.veeranki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views19 pages

Structured Programming in C Module - I

Uploaded by

rakesh.veeranki
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

STRUCTURED PROGRAMMING USING C UNIT - 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:

 You break the problem down into a sequence of logical steps.


 These steps are defined clearly.

 They can be carried out by a human, or by a computer, or by both.

Characteristics of Algorithm / Key Features of Algorithm

Algorithm has five important characteristics.


a) Finiteness: An algorithm must always terminate after a fixed number of steps. It
should not run endlessly. It should end with a solution.
b) Definiteness: Each step of the algorithm should clearly define. All the steps of
algorithm should be defined without ambiguity. All the steps of
algorithm should easy to interpret/understand.
c) Effectiveness: An algorithm must be developed by using very basic, simple, and
feasible operations so that anyone can trace it using paper and pencil.
All the operations should be performed exactly in fixed time.
d) Input: An algorithm should have zero or more inputs. An algorithm processes

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

Breakpoint The Breakpoint symbol is used to pause the


flowchart execution temporarily. This symbol is
used while debugging the flowchart.
Input The Input Symbol is used to read one input from
key board. It stores input in a variable.

Output The Output Symbol is used to display the data on


screen.

Declare The Declare symbol is used to declare variables.

Assign The Assign symbol is used to assign / store


value to variable.

If The If symbol is used to makes a decision and


controls the flow. The program control takes one
branch if the condition is True. The program
control takes another branch if the condition
is False.
Call The Call symbol is used to invokes a procedure
or function. It transfers control from calling
function to called function.
While The while symbol is used to execute loop
repeatedly.
For The for symbol is used to execute loop
repeatedly.

Do The Do symbol is used to execute loop


repeatedly. Do loop executes the loop at least
once.

Purpose of Flowchart

 Flowchart is used to convert algorithm into picture.


 Flowchart tells how an algorithm works.
 Flowchart tells how a process works.
 Flowchart helps to understand a process easily.
 Flowchart helps to identify mistakes.
 Flowchart helps to identify redundancies.
 Flowchart is useful during the planning phase of software development.
 Flowchart helps to break down a complex problem into smaller, manageable parts.
 Flowchart makes easier to explain the process to others

Page 4
STRUCTURED PROGRAMMING USING C UNIT - I

Examples

Example 1: Draw flowchart to print sum of two numbers:

Example 2: Draw the flowchart that calculates the simple interest.

Page 5
STRUCTURED PROGRAMMING USING C UNIT - I

Example 3: Draw the flowchart to swap two numbers.

Page 6
STRUCTURED PROGRAMMING USING C UNIT - I

Example 4: Draw the flowchart which finds the biggest number among two numbers.

Example 5: draw the flowchart to find big no from 3 nos.

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

Example 1: Draw a flowchart to print following rhyme


Twinkle, twinkle, little star,
how I wonder what you are.
Up above the world so high,
like a diamond in the sky.

Example 2: Draw a flowchart to print following rhyme


Ring o ring o roses,
A pocketful of posies,
A-tishool A-tishool,
We all fall down
Example 3: Draw a flowchart to find net salary of an employee using formula
Net = basic + hra + da - pf
Example 4: Draw a flowchart to convert a lower case character to upper case character
using ch=ch-32 .
Example 5: Draw a flowchart to find M value using M=(a+b+c+d+e)/5
Example 6: Draw a flowchart to find result of add 3 to the quantity 4 times 5
Example 7: Draw a flowchart to find y value using y=ax2+bx+c
Example 8: Draw a flowchart to convert seconds into hours and minutes
Page 9
STRUCTURED PROGRAMMING USING C UNIT - I

Example 9: Draw a flowchart to convert hours and minutes into Seconds


Example 10: Draw a flowchart to find y value using y=ax3-bx2-6
Example 11: Draw a flowchart to find y value using y=2x1-3x2+5x3+4
Example 12: Draw a flowchart to convert distance from miles to kilometers using
km=1.609*miles
Example 13: Draw a flowchart to find distance travelled by object using
S=ut+1/2at2

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.

 C is more powerful and flexible for system programming.

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

programming language because it allows step-by-step approach to problem-solving,


breaking down tasks into smaller, manageable procedures or functions.
5. Platform Dependent Language :- C is a platform-dependent language because its
compiled code (machine code) is depends on operating system and hardware. This
means a C program compiled for one platform (e.g., Windows) won't directly run on
another platform (e.g., Linux) without recompilation.
6. Simple Programming Language :- C is simple programming language due to its
straight forward syntax, and the direct relationship between its code and machine
instructions.
7. Typed Programming Language :- C is a typed programming language because every
variable and expression associated with data type. Compiler can understand the data
type of variable or expression at the time of compilation.
8. Portable Language :- C is a portable language because its source code can be compiled
and run on different computer systems having same platform without any
modification.
9. General Purpose Language :- C is a general-purpose programming language because it
can be used to develop a wide range of applications like operating systems, embedded
systems, game development, scientific computing.
10. Extensible Language : C is a extensible language because a user can add new features and
functions to existing C library.

Applications of C

Application of C Description and Examples

Operating System C is used to develop operating systems like UNIX and Linux, enabling
Development efficient management of hardware and system resources.

Embedded Systems and C powers embedded systems in devices such as automotive


IoT Devices controllers and smart home gadgets, ensuring real-time performance
and precise hardware control.

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.

Network Programming C is employed to implement network protocols and develop device


and Drivers drivers, ensuring efficient data transmission and seamless hardware
interactions.

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.

High-Performance C is pivotal in high-performance computing (HPC) applications and


Computing and Scientific scientific research tools like LAPACK and GNU Scientific Library
Research (GSL), enabling rapid computations and large-scale simulations

Page 11
STRUCTURED PROGRAMMING USING C UNIT - I

Structure of C Program

A “C‟ program is a group of building blocks called functions. A function is a subroutine


that may include one or more statements designed to perform a specific task. To write a
C program we first create functions and then put them together. Any C program may
contain one or more sections as shown in the figure.

Documentation Section //optional


Link Section //optional
Definition Section //optional
Global declaration Section //optional
Main( ) function section //must
{
Declaration part
Executable part
}
Subprogram Section //optional
Function -1
Function-2

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

Ex: #define PI 3.14


This statement creates a constant and named it as PI and its value is 3.14.
Global Declaration Section:
There are two places where variables and functions are declared inside a function or
declared outside the function. Variables declared outside the functions are called global
variables.
Example :
int no; // global variable
void main()
{
int no2=20; // local variable
}

Main( ) Function Section:


The main( ) is a special function used by the C system to tell the computer where the
program starts. Every program must have exactly one main function. This section has
two parts
a) Declaration part
b) Execution part

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.

The following rules need to be followed while naming identifiers.


1. Name of Identifier consists alphabets, digits or underscore.
2. Name of Identifier must begin with an alphabet or underscore.
3. Name of Identifier does not allow space.
4. Name of Identifier does not allow any special character except underscore.
5. Name of Identifier should not be Keyword.
6. Length of Name of Identifier should not exceed 32 characters.
Valid Invalid Identifiers Reason for not valid
identifiers
No1 1no Identifier should not begin with digit.
_no1 Odd numbers sum Identifier should not have space.
Odd_sum Odd-sum Identifier does not allow any special character
int, char, float, Identifier should not be a keyword
Abcdef….z012…9 Length of identifier should not exceed 32
characters

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

should be represented in upper case.

Integer Constants: An integer constant is a sequence of digits without a decimal


point. No commas, no blank spaces are allowed. It could be either positive or
negative. If no sign proceeds it is assumed to be positive. It may be specified in
decimal, octal or hexadecimal notation.
Decimal Integer Constant: It consists of sequence of one or more decimal digits
from 0 to 9. It can be preceded by an optional – or + sign.
Ex: 0 , -321 , 3412
Octal Integer Constant: It consists of the digit 0 followed by a sequence of one or
more octal digits from 0 to 7.
Ex: 012 , 07134
Hexadecimal Integer Constant: It consists of the digit 0, followed by one of the
letter x or X , followed by a sequence of one or more hexadecimal digits from 0 to 9
or letter from A to F or a to f.
Ex: 0x2 0X9F, 0xbcd
The largest integer value that can be stored is machine dependent.

Real Constants: A Real constant or floating point constant is a sequence of digits


with a decimal point. No commas, no blank spaces are allowed. It could be either
positive or negative. If no sign proceeds it is assumed to be positive.
Ex: valid floating-point constants 0.00083 , -0.35 , 435.98 , 95
A real constant may also be expressed in exponential (or scientific) notation.
The scientific notation is often used to express numbers that are very small or very
large. For ex, that 0.000000011 is written as 1.1 × 10-8. The general form is
Mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an
integer. The exponent is an integer number with an optional + or – sign.
Ex: valid floating-point constants: 0.65e4 , 12e-2, 1.5E+5
Invalid floating point constants:
6,700.25 commas is not permitted
5e+2.5 exponents must be an integer
Floating point constants are normally represented as double precision
quantities. However, the suffixes f or F may be used to force single precision and l
or L to extend double precision.
Character Constants: Any single character enclosed with in pair of single
quotation marks is called a character constant.
Ex: ‘5’, ‘x’, ‘ ‘
The last constant is a blank space. The character constant ‘5’ is not the same as 5.
Character Constants have integer values known as ASCII values. Since
each character constant represent an integer value it is also possible to perform
Page 16
STRUCTURED PROGRAMMING USING C UNIT - I

arithmetic operations on character constants.


String Constant: A String Constant is a sequence of characters enclosed in double
quotes. The characters may be letters, numbers, special characters and blank space.
Ex: “VVIT”, “P”, “5+3”
The character constant (ex: ‘p’) is not equivalent to the string
constant (ex: “p”). A string constant does not have an associated ASCII value,
whereas character constant has an integer value.

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 : char str[] = "Hello, World!";

6. Operators:- Operator is a tool / symbol which is used to perform operations.


Operators are used to manipulate data and variables. The variables and constants can
be combined together by various operators to form expressions. The operators
perform operations to generate output.

Example : +, -, *, /, %, =, ==, !=, >, <, >=, <=, &&, ||, ++, --

Formatted IO Functions / Formatted Input & Output Functions

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

Example : Write a C program to print following rhyme


Row, row, row your boat
Gently down the stream
Merrily, merrily, merrily, merrily
Life is but a dream
#include <stdio.h>
void main()
{
printf("Row, row, row your boat\n");
printf("Gently down the stream\n");
printf("Merrily, merrily, merrily, merrily\n");
printf("Life is but a dream\n");
}
scanf():-
-----------------------------------
It stands for scan formatted. It is used for input. It reads input from keyboard. It can read
any type of data. It can read multiple values at a time. It was defined in “stdio.h”. It
execute from left side to right side. It returns how many items successfully read.
Syntax:
scanf(“format specifiers / formatted string”, &variable1, &variable2,..);
here “&” symbol gives the address of variable.
Example: Write a C program to convert hours and minutes into Seconds
#include <stdio.h>
void main()
{
int hours, minutes, total_seconds;
printf("Enter hours: ");
scanf("%d", &hours);
printf("Enter minutes: ");
scanf("%d", &minutes);
total_seconds = (hours * 3600) + (minutes * 60);
printf("Total time in seconds: %d", total_seconds);

Page 18
STRUCTURED PROGRAMMING USING C UNIT - I

}
The above two input & output functions are also known as formatted I/O functions.

Page 19

You might also like