0% found this document useful (0 votes)
6 views

Notes of UNIT1,2

The document outlines a course on C Programming for Engineers, detailing its objectives, outcomes, and content structure across five units. Topics include computer fundamentals, programming basics, functions, arrays, pointers, file handling, and basic algorithms. The course aims to equip students with essential programming skills and problem-solving techniques using the C language.

Uploaded by

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

Notes of UNIT1,2

The document outlines a course on C Programming for Engineers, detailing its objectives, outcomes, and content structure across five units. Topics include computer fundamentals, programming basics, functions, arrays, pointers, file handling, and basic algorithms. The course aims to equip students with essential programming skills and problem-solving techniques using the C language.

Uploaded by

24e11a0403
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

Lecture Notes

C PROGRAMMING FOR
ENGINEERS

N.Haripriya (Ph.D)
Assistant Professor
ECE
C PROGRAM FOR ENGINEERS

B.Tech. I Year I Sem. L T P C


3 0 0 3
Course Objectives:
1. To learn the fundamentals of computers.
2. To understand the various steps in Program development.
3. To learn the syntax and semantics of C Programming Language.
4. To learn the usage of structured programming approach in solving problems.

Course Outcomes: Upon completing this course, the students will be able to
1. Draw flowcharts for solving arithmetic and logical problems
2. Develop modular reusable code by understanding concepts of functions.
3. Formulate algorithms and programs using arrays, pointers, strings and structures.
4. Write a programs using Searching and sorting algorithms

UNIT- I
Introduction to Computer Algorithms and Programming
Components of a computer system: Memory, processor, I/O devices, storage, operating system, the
concept of assembler, compiler, interpreter, loader, and linker.
From algorithm to program: Representation of an algorithm, flowchart, Pseudocode with examples,
converting algorithms to programs.
Programming Basics: Structure of C program, writing and executing the first C program, Syntax and
logical errors in compilation, object, and executable code. Components of C language, standard I/O in
C, data types, variables and constants, memory storage, and storage classes.
UNIT – II
Expressions and Statements
Expressions and their evaluation: Operands and Operators, formation of expressions using arithmetic,
relational, logical, and bitwise operators, precedence and associativity rules, mixed operands, type
conversion, and evaluation of expressions.

LECTURE NOTES 1
C PROGRAM FOR ENGINEERS

Statements: Simple and compound statements, Conditional Branching: if and switch statements, nested
if-else, dangling else problem, use of break and default with switch. Iteration and loops: use of while,
do-while and for loops, nested loops, use of break and continue statements.

UNIT - III
Functions and Arrays
Designing Structured Programs: Introduction to functions, advantages of modularizing a program
into functions, types of functions, passing parameters to functions: call by value, call by reference,
passing arrays to functions, recursion with example programs.
Arrays: Array notation and representation, manipulating array elements, using multi-dimensional
arrays, character arrays, C strings, string input/output functions, Array of strings, string manipulation
functions with example programs.
UNIT – IV
Pointers and File handling
Pointers: Introduction, declaration, applications, dynamic memory allocation (malloc, calloc, realloc,
free), use of pointers in self-referential structures.
File handling: File I/O functions, standard C pre-processors, defining and calling macros, command
line arguments.
UNIT – V
Derived types And Basic Algorithms:
Structures, Union, Enums and Bit-fields: Defining, declaring, and usage of structures, unions, and
their arrays, passing structures, and unions to functions, introduction to enums and bit-fields.
Basic Algorithms: Searching and Sorting Algorithms (Bubble, Insertion, and Selection), finding roots
of equations, notion of order of complexity through example programs.

TEXT BOOKS:
1. B. A. Forouzan and R. F. Gilberg -Programming & Data Structures, 3rd Ed., Cengage Learning`
2. Byron Gottfried - Schaum’s Outline of Programming with C, McGraw-Hill
REFERENCE BOOKS:
1. Ajay Mittal - Programming in C: A practical approach, Pearson Education, 2010
2. Kernighan Brian W. and Ritchie Dennis M.- The C programming, Pearson Education.
3. J. R. Hanlyand, E. B. Koffman -Problem Solving and Program Design, 5th Ed., Pearson Education.
4. H. Cheng - C for Engineers and Scientists, McGraw-Hill International Edition
5. V. Rajaraman - Computer Basics and C Programming, PHI Learning, 2015.

LECTURE NOTES 2
C PROGRAM FOR ENGINEERS

UNIT 1
Introduction to components of a computer system: Memory, processor, I/O
Devices, storage
INTRODUCTION TO COMPUTERS
Any programming language is implemented on a computer. Right from its inception, to the
present day, all computer system (irrespective of their shape & size) performs the following 5
basic operations. It converts the raw input data into information, which is useful to the users.
1. Input: It is the process of entering data & instructions to the computer system.
2. Storing: The data & instructions are stored for either initial or additional processing, as &
when required.
3. Processing: It requires performing arithmetic or logical operation on the saved data to
convert it into useful information.
4. Output: It is the process of producing the output data to the end user.
5. Controlling: The above operations have to be directed in a particular sequence to be
completed.
Based on these 5 operations, we can sketch the block diagram of a computer.

Block Diagram of a Computer

LECTURE NOTES 3
C PROGRAM FOR ENGINEERS

Memory Organization in Computer


A memory unit is the collection of storage units or devices together. The memory unit stores
the binary information in the form of bits. Generally, memory/storage is classified into 2
categories:
• Volatile Memory: This loses its data, when power is switched off.
• Non-Volatile Memory: This is a permanent storage and does not lose any data when power
is switched off.
Memory Hierarchy

The total memory capacity of a computer can be visualized by hierarchy of components. The
memory hierarchy system consists of all storage devices contained in a computer system from
the slow Auxiliary Memory to fast Main Memory and to smaller Cache memory.
Auxillary memory access time is generally 1000 times that of the main memory, hence it is at
the bottom of the hierarchy.
The main memory occupies the central position because it is equipped to communicate directly
with the CPU and with auxiliary memory devices through Input/output processor (I/O).
When the program not residing in main memory is needed by the CPU, they are brought in
from auxiliary memory. Programs not currently needed in main memory are transferred into
auxiliary memory to provide space in main memory for other programs that are currently in
use.
The cache memory is used to store program data which is currently being executed in the CPU.
Approximate access time ratio between cache memory and main memory is about 1 to 7~10

LECTURE NOTES 4
C PROGRAM FOR ENGINEERS

Central Processing Unit (Processor)


Together the Control Unit & the Arithmetic Logic Unit are called as the Central Processing
Unit (CPU). The CPU is the brain of the computer. Like in humans, the major decisions are
taken by the brain itself & other body parts function as directed by the brain. Similarly in a
computer system, all the major calculations & comparisons are made inside the CPU. The CPU
is responsible for activating & controlling the operation of other units of the computer system.
Memory Unit:
A memory unit is the collection of storage units or devices together. The memory unit stores
the binary information in the form of bits. Generally, memory/storage is classified into 2
categories:
• Volatile Memory: This loses its data, when power is switched off.
• Non-Volatile Memory: This is a permanent storage and does not lose any data when power
is switched off.
Arithmetic Logic Unit:
The actual execution of the instructions (arithmetic or logical operations) takes place over here.
The data & instructions stored in the primary storage are transferred as & when required. No
processing is done in the primary storage. Intermediate results that are generated in ALU are
temporarily transferred back to the primary storage, until needed later. Hence, data may move
from the primary storage to ALU & back again to storage, many times, before the processing
is done.
Control Unit:
This unit controls the operations of all parts of the computer but does not carry out any actual
data processing. It is responsible for the transfer of data and instructions among other units of
the computer. It manages and coordinates all the units of the system. It also communicates with
Input/Output devices for transfer of data or results from the storage units.

Input/ Output Devices


We need to first enter the data & instruction in the computer system, before any computation
begins. This task is accomplished by the input devices. (The data accepted is in a human
readable form. The input device converts it into a computer readable form).
Input device: The input device is the means through which data and instructions enter in a
computer.
1. Camera - most cameras like this are used during live conversations. The camera transmits
a picture from one computer to another, or can be used to record a short video.

LECTURE NOTES 5
C PROGRAM FOR ENGINEERS

2. Compact Disc (CD) - CDs store information. The CD can then be put into another computer,
and the information can be opened and added or used on the second computer. Note: A CD-R
or CD-RW can also be used as an OUTPUT device.

3. Keyboard - The keyboard is a way to input letters or numbers into different applications or
programs. A keyboard also has special keys that help operate the computer.

4. Mouse - The mouse is used to open and close files, navigate web sites, and click on a lot of
commands (to tell the computer what to do) when using different applications.

5. Microphone - A microphone is used to record sound. The sound is then saved as a sound
file
on the computer.

6. Scanner - A scanner is used to copy pictures or other things and save them as files on the
computer.

7. Joystick - A joystick is used to move the cursor from place to place, and to click on various
items in programs. A joystick is used mostly for computer games.

8. Bar Code Scanner - A bar code scanner scans a little label that has a bar code on it. The
information is then saved on the computer. Bar code scanners are used in libraries a lot.

LECTURE NOTES 6
C PROGRAM FOR ENGINEERS

Output Unit:
The job of an output unit is just the opposite of an input unit. It accepts the results produced by
the computer in coded form. It converts these coded results to human readable form. Finally, it
displays the converted results to the outside world with the help of output devices (Eg:
monitors, printers, projectors etc..).
Output device: Device that lets you see what the computer has accomplished.
1. Monitor - A monitor is the screen on which words, numbers, and graphics can be seem. The
monitor is the most common output device.

2. Compact Disk - Some compact disks can be used to put information on. This is called
burning information to a CD. NOTE: A CD can also be an input device.

3. Printer - A printer prints whatever is on the monitor onto paper. Printers can print words,
numbers, or pictures.

4. Speaker - A speaker gives you sound output from your computer. Some speakers are built
into the computer and some are separate.

5. Headphones - Headphones give sound output from the computer. They are similar to
speakers, except they are worn on the ears so only one person can hear the output at a time.

LECTURE NOTES 7
C PROGRAM FOR ENGINEERS

Storage Unit
The data & instruction that are entered have to be stored in the computer. Similarly, the end
results & the intermediate results also have to be stored somewhere before being passed to the
output unit. The storage unit provides solution to all these issues. This storage unit is designed
to save the initial data, the intermediate result & the final result. This storage unit has 2 units:
Primary storage & Secondary storage.
Primary Storage:
The primary storage, also called as the main memory, holds the data when the computer is
currently on. As soon as the system is switched off or restarted, the information held in primary
storage disappears (i.e. it is volatile in nature). Moreover, the primary storage normally has a
limited storage capacity, because it is very expensive as it is made up of semiconductor devices.
Secondary Storage:
The secondary storage, also called as the auxiliary storage, handles the storage limitation & the
volatile nature of the primary memory. It can retain information even when the system is off.
It is basically used for holding the program instructions & data on which the computer is not
working on currently, but needs to process them later.
Magnetic Disk
The Magnetic Disk is Flat, circular platter with metallic coating that is rotated beneath
read/write heads. It is a Random access device; read/write head can be moved to any location
on the platter.
Floppy Disk
These are small removable disks that are plastic coated with magnetic recording material.
Floppy disks are typically 3.5″ in size (diameter) and can hold 1.44 MB of data. This portable
storage device is a rewritable media and can be reused a number of times. Floppy disks are
commonly used to move files between different computers. The main disadvantage of floppy
disks is that they can be damaged easily and, therefore, are not very reliable.
Hard disk
A hard disk consists of one or more rigid metal plates coated with a metal oxide material that
allows data to be magnetically recorded on the surface of the platters. The hard disk platters
spin at a high rate of speed, typically 5400 to 7200 revolutions per minute (RPM). Storage
capacities of hard disks for personal computers range from 10 GB to 120 GB (one billion bytes
are called a gigabyte).

LECTURE NOTES 8
C PROGRAM FOR ENGINEERS

CD: Compact Disk (CD) is portable disk having data storage capacity between 650-700 MB.
It can hold large amount of information such as music, full-motion videos, and text etc. It
contains digital information that can be read, but cannot be rewritten. Separate drives exist for
reading and writing CDs. Since it is a very reliable storage media, it is very often used as a
medium for distributing large amount of information to large number of users. In fact today
most of the software is distributed through CDs.
DVD
Digital Versatile Disk (DVD) is similar to a CD but has larger storage capacity and enormous
clarity. Depending upon the disk type it can store several Gigabytes of data (as opposed to
around 650MB of a CD). DVDs are primarily used to store music or movies and can be played
back on your television or the computer too. They are not rewritable media. It‘s also termed
DVD (Digital Video Disk)

Operating System
The Operating System is a program with the following features −
 An operating system is a program that acts as an interface between the software and the
computer hardware.
 It is an integrated set of specialized programs used to manage overall resources and
operations of the computer.
 It is a specialized software that controls and monitors the execution of all other
programs that reside in the computer, including application programs and other system
software.
Objectives of Operating System
The objectives of the operating system are
 To make the computer system convenient to use in an efficient manner.

LECTURE NOTES 9
C PROGRAM FOR ENGINEERS

 To hide the details of the hardware resources from the users.


 To provide users a convenient interface to use the computer system.
 To act as an intermediary between the hardware and its users, making it easier for the
users to access and use other resources.
 To manage the resources of a computer system.
 To keep track of who is using which resource, granting resource requests, and mediating
conflicting requests from different programs and users.
 To provide efficient and fair sharing of resources among users and programs.
Characteristics of Operating System
Here is a list of some of the most prominent characteristic features of Operating Systems −
 Memory Management − Keeps track of the primary memory, i.e. what part of it is in
use by whom, what part is not in use, etc. and allocates the memory when a process or
program requests it.
 Processor Management − Allocates the processor (CPU) to a process and deallocates
the processor when it is no longer required.
 Device Management − Keeps track of all the devices. This is also called I/O controller
that decides which process gets the device, when, and for how much time.
 File Management − Allocates and de-allocates the resources and decides who gets the
resources.
 Security − Prevents unauthorized access to programs and data by means of passwords
and other similar techniques.
 Job Accounting − Keeps track of time and resources used by various jobs and/or users.
 Control Over System Performance − Records delays between the request for a
service and from the system.
 Interaction with the Operators − Interaction may take place via the console of the
computer in the form of instructions. The Operating System acknowledges the same,
does the corresponding action, and informs the operation by a display screen.
 Error-detecting Aids − Production of dumps, traces, error messages, and other
debugging and error-detecting methods.
 Coordination Between Other Software and Users − Coordination and assignment of
compilers, interpreters, assemblers, and other software to the various users of the
computer systems.

LECTURE NOTES 10
C PROGRAM FOR ENGINEERS

Concept of assembler, compiler, interpreter, loader and linker


A language that is acceptable to a computer system is called a computer language or
programming language and the process of creating a sequence of instructions in such a
language is called programming or coding.
A program is a set of instructions, written to perform a specific task by the computer. A set of
large program is called software. To develop software, one must have knowledge of a
programming language.
Before moving on to any programming language, it is important to know about the various
types of languages used by the computer.
COMPUTER LANGUAGES
• Languages are a means of communication. Normally people interact with each other through
a language. On the same pattern, communication with computers is carried out through a
language. This language is understood both by the user and the machine.
• Just as every language like English, Hindi has its own grammatical rules; every computer
language is also bounded by rules known as syntax of that language. The user is bound by that
syntax while communicating with the computer system.
Computer languages are broadly classified as:
• Low Level Language: The term low level highlights the fact that it is closer to a language
which the machine understands. The low-level languages are classified as:
• Machine Language: This is the language (in the form of 0‘s and 1‘s, called binary numbers)
understood directly by the computer. It is machine dependent. It is difficult to learn and even
more difficult to write programs.
• Assembly Language: This is the language where the machine codes comprising of 0‘sand
1‘s are substituted by symbolic codes (called mnemonics) to improve their understanding. It is
the first step to improve programming structure. Assembly language programming is simpler
and less time consuming than machine level programming, it is easier to locate and correct
errors in assembly language than in machine language programs. It is also machine dependent.
Programmers must have knowledge of the machine on which the program will run.
• High Level Language: Low level language requires extensive knowledge of the hardware
since it is machine dependent. To overcome this limitation, high level language has been
evolved which uses normal English, which is easy to understand to solve any problem. High
level languages are computer independent and programming becomes quite easy and simple.
Various high-level languages are given below:
• BASIC (Beginners All Purpose Symbolic Instruction Code): It is widely used, easy to learn
general purpose language. Mainly used in microcomputers in earlier days.
• COBOL (Common Business Oriented language): A standardized language used for
commercial applications.

LECTURE NOTES 11
C PROGRAM FOR ENGINEERS

• FORTRAN (Formula Translation): Developed for solving mathematical and scientific


problems. One of the most popular languages among scientific community.
• C: Structured Programming Language used for all purpose such as scientific application,
commercial application, developing games etc.

PROGRAMMING LANGUAGE TRANSLATORS


• As you know that high level language is machine independent and assembly language though
it is machine dependent yet mnemonics that are being used to represent instructions are not
directly understandable by the machine. Hence to make the machine understand the instructions
provided by both the languages, programming language instructors are used.
• They transform the instruction prepared by programmers into a form which can be interpreted
& executed by the computer. Flowing are the various tools to achieve this purpose:
Compiler: The software that reads a program written in high level language and translates it
into an equivalent program in machine language is called as compiler. The program written by
the programmer in high level language is called source program and the program generated by
the compiler after translation is called as object program.
Interpreter: it also executes instructions written in a high level language. Both complier &
interpreter have the same goal i.e. to convert high level language into binary instructions, but
their method of execution is different. The complier converts the entire source code into
machine level program, while the interpreter takes 1 statement, translates it, executes it & then
again takes the next statement.
Assembler: The software that reads a program written in assembly language and translates it
into an equivalent program in machine language is called as assembler.
Linker: A linker or link editor is a computer program that takes one or more object files
generated by a compiler and combines them into a single executable file, library file, or another
object file.
Loader
Loader is a part of operating system and is responsible for loading executable files into memory
and execute them. It calculates the size of a program (instructions and data) and creates memory
space for it. It initializes various registers to initiate execution.

LECTURE NOTES 12
C PROGRAM FOR ENGINEERS

Representation of algorithm and flowchart


Algorithm: The word algorithm means “A set of finite rules or instructions to be followed
in calculations or other problem-solving operations”.
Or
” A procedure for solving a mathematical problem in a finite number of steps that frequently
involves recursive operations”.

What is the need for algorithms?


1. Algorithms are necessary for solving complex problems efficiently and effectively.
2. They help to automate processes and make them more reliable, faster, and easier to perform.
3. Algorithms also enable computers to perform tasks that would be difficult or impossible for
humans to do manually.

LECTURE NOTES 13
C PROGRAM FOR ENGINEERS

4. They are used in various fields such as mathematics, computer science, engineering, finance,
and many others to optimize processes, analyze data, make predictions, and provide solutions
to problems.

Characteristics of an Algorithm

Flowchart:
Flowchart is a graphical representation of an algorithm. Programmers often use it as a program-planning
tool to solve a problem. It makes use of symbols which are connected among them to indicate the flow
of information and processing. The process of drawing a flowchart for an algorithm is known as
“flowcharting”.
Basic Symbols used in Flowchart Designs
 Terminal: The oval symbol indicates Start, Stop and Halt in a program’s logic flow. A
pause/halt is generally used in a program logic under some error conditions. Terminal is the
first and last symbols in the flowchart.

 Input/Output: A parallelogram denotes any function of input/output type. Program


instructions that take input from input devices and display output on output devices are
indicated with parallelogram in a flowchart.

 Processing: A box represents arithmetic instructions. All arithmetic processes such as adding,
subtracting, multiplication and division are indicated by action or process symbol.

LECTURE NOTES 14
C PROGRAM FOR ENGINEERS

 Decision Diamond symbol represents a decision point. Decision based operations such as
yes/no question or true/false are indicated by diamond in flowchart.

 Connectors: Whenever flowchart becomes complex or it spreads over more than one page, it
is useful to use connectors to avoid any confusions. It is represented by a circle.

 Flow lines: Flow lines indicate the exact sequence in which instructions are executed. Arrows
represent the direction of flow of control and relationship among different symbols of
flowchart.
Rules For Creating Flowchart:
A flowchart is a graphical representation of an algorithm.it should follow some rules while creating
a flowchart

Rule 1: Flowchart opening statement must be ‘start’ keyword.


Rule 2: Flowchart ending statement must be ‘end’ keyword.
Rule 3: All symbols in the flowchart must be connected with an arrow line.
Rule 4: The decision symbol in the flowchart is associated with the arrow line.

Advantages of Flowchart:
 Flowcharts are a better way of communicating the logic of the system.
 Flowcharts act as a guide for blueprint during program designed.
 Flowcharts help in debugging process.
 With the help of flowcharts programs can be easily analyzed.
 It provides better documentation.
 Flowcharts serve as a good proper documentation.
 Easy to trace errors in the software.
 Easy to understand.
 The flowchart can be reused for inconvenience in the future.
 It helps to provide correct logic.

LECTURE NOTES 15
C PROGRAM FOR ENGINEERS

Example 1: Algorithm and flowchart to perform addition of 2 numbers


Algorithm Flowchart

Example 2: Algorithm and flowchart to find greatest of 2 numbers


Algorithm Flowchart

LECTURE NOTES 16
C PROGRAM FOR ENGINEERS

Example 3: Algorithm and flowchart to find greatest of 3 numbers


Algorithm Flowchart

LECTURE NOTES 17
C PROGRAM FOR ENGINEERS

Example 4: Algorithm and flowchart to find if a number is even or odd


Algorithm Flowchart

Example 5: Algorithm and flowchart to check if a given number is positive, negative or equal to zero
Algorithm Flowchart

LECTURE NOTES 18
C PROGRAM FOR ENGINEERS

Example 6: Algorithm and flowchart to find if a number is even or odd


Algorithm Flowchart

Pseudo codes
A Pseudocode is defined as a step-by-step description of an algorithm. Pseudocode does not use any
programming language in its representation instead it uses the simple English language text as it is
intended for human understanding rather than machine reading.
Pseudocode is the intermediate state between an idea and its implementation(code) in a high-level
language.
What is the need for Pseudocode
Pseudocode is an important part of designing an algorithm, it helps the programmer in planning the
solution to the problem as well as the reader in understanding the approach to the problem. Pseudocode
is an intermediate state between algorithm and program that plays supports the transition of the
algorithm into the program.

Pseudocode is an intermediate state between algorithm and program

LECTURE NOTES 19
C PROGRAM FOR ENGINEERS

Example 1: Pseudo code for addition of 2 numbers

BEGIN
NUMBER s1, s2, sum
INPUT s1
INPUT s2
sum=s1+s2
OUTPUT sum
END

Example 2: Pseudo code to find greatest of 2 numbers


BEGIN
Read num1
Read num2
If (num1>num2)
Write number1 is the Greatest Number
else
Write number2 is the Greatest Number
END
Example 3: Pseudo code to find greatest of 3 numbers

Example 4: Pseudo code to find if a number is even or odd

LECTURE NOTES 20
C PROGRAM FOR ENGINEERS

Example 5: Pseudo code to check if a number is positive, negative or equal to zero


BEGIN
READ num
IF num>0 THEN
OUTPUT "Entered number is positive"
ELSE IF num <0 THEN
OUTPUT "Entered number is negative"
ELSE
OUTPUT "Entered number is zero"
ENDIF
END

Example 6: Pseudo code to check if a person is eligible for vote or not


BEGIN
READ age
IF age >= 18
DISPLAY "Eligible for Voting! "
ELSE
DISPLAY "NOT Eligible for Voting! "
END IF
END

Programming Basics
Structure of C program
The basic structure of a C program is divided into 6 parts which makes it easy to read, modify,
document, and understand in a particular format. C program must follow the below-mentioned outline
in order to successfully compile and execute. Debugging is easier in a well-structured C program.
Sections of the C Program
There are 6 basic sections responsible for the proper execution of a program. Sections are mentioned
below:
1. Documentation
2. Preprocessor Section

LECTURE NOTES 21
C PROGRAM FOR ENGINEERS

3. Definition
4. Global Declaration
5. main () Function
6. Sub Programs
1. Documentation
This section consists of the description of the program, the name of the program, and the creation date
and time of the program. It is specified at the start of the program in the form of comments.
Documentation can be represented as:
// description, name of the program, programmer name, date, time etc.
or
/*
description, name of the program, programmer name, date, time etc.
*/
Anything written as comments will be treated as documentation of the program and this will not
interfere with the given code. Basically, it gives an overview to the reader of the program.
2. Preprocessor Section
All the header files of the program will be declared in the preprocessor section of the program. Header
files help us to access other’s improved code into our code. A copy of these multiple files is inserted
into our program before the process of compilation.
Example:
#include<stdio.h> // stdio represents standard input/output
#include<math.h>
3. Definition
Preprocessors are the programs that process our source code before the process of compilation. There
are multiple steps which are involved in the writing and execution of the program. Preprocessor
directives start with the ‘#’ symbol. The #define preprocessor is used to create a constant throughout
the program. Whenever this name is encountered by the compiler, it is replaced by the actual piece of
defined code.
Example:
#define long long ll
4. Global Declaration
The global declaration section contains global variables, function declaration, and static variables.
Variables and functions which are declared in this scope can be used anywhere in the program.
Example:
int num = 18;

LECTURE NOTES 22
C PROGRAM FOR ENGINEERS

5. Main() Function
Every C program must have a main function. The main() function of the program is written in this
section. Operations like declaration and execution are performed inside the curly braces of the main
program. The return type of the main() function can be int as well as void too. void() main tells the
compiler that the program will not return any value. The int main() tells the compiler that the program
will return an integer value.
Example:
void main()
or
int main()
6. Sub Programs
User-defined functions are called in this section of the program. The control of the program is shifted
to the called function whenever they are called from the main or outside the main() function. These are
specified as per the requirements of the programmer.

Example:
int sum (int x, int y)
{
return x+y;
}

FILES USED IN A C PROGRAM


Source File- This file contains the source code of the program. The file extension of any c file is .c.
The file contains C source code that defines the main function & maybe other functions.
Header File- A header file is a file with extension .h which contains the C function declarations and
macro definitions and to be shared between several source files.
Object File- An object file is a file containing object code, with an extension.o, meaning relocatable
format machine code that is usually not directly executable. Object files are produced by an
assembler, compiler, or other language translator, and used as input to the linker, which in turn
typically generates an executable or library by combining parts of object files.
Executable File- The binary executable file is generated by the linker. The linker links the various
object files to produce a binary file that can be directly executed.

LECTURE NOTES 23
C PROGRAM FOR ENGINEERS

Writing and executing the first C program


The “Hello World” program is the first step towards learning any programming language and
also one of the simplest programs you will learn. To print the “Hello World”, we can use
the printf function from the stdio.h library that prints the given string on the screen.

C Program to Print “Hello World”


The following C program displays “Hello World” in the output screen:
C
// Simple C program to display "Hello World"

// Header file for input output functions


#include <stdio.h>

// Main function: entry point for execution


void main() {

// writing print statement to print hello world


printf("Hello World");

Output
Hello World
Explanation:
 #include <stdio.h> – This line includes the standard input-output library in the
program.
 void main() – The main function where the execution of the program begins.
 printf(“Hello, World!\n”); – This function call prints “Hello, World!” followed
by a new line.

Types of Errors
Here we will see different types of errors using a C program. In any programming language errors are
common. If we miss any syntax like parenthesis or semicolon then we get syntax errors. Apart from
this we also get run time errors during the execution of code.
There are 5 types of error in C:
1. Syntax Errors
2. Runtime Errors
3. Logical Errors
4. Linked Errors
5. Semantic Errors

Let’s discuss each of these in detail.

1. Syntax Errors

LECTURE NOTES 24
C PROGRAM FOR ENGINEERS

These are also referred to as compile-time errors. These errors have occurred when the rule of C writing
techniques or syntaxes has been broken. These types of errors are typically flagged by the compiler
prior to compilation.
Example 1: In the below program we are getting an error because of a missing semicolon at the end of
the output statement (printf()) called syntax error.

Output

2.Runtime Errors
This type of error occurs while the program is running. Because this is not a compilation error, the
compilation will be completed successfully. These errors occur due to segmentation fault when a
number is divided by division operator or modulo division operator.
Example: Let us consider an array of length 5 i.e. array[5], but during runtime, if we try to access 10
elements i.e array[10] then we get segmentation fault errors called runtime errors. Giving only an array
length of 5

But in output trying to access more than 5 i.e if we try to access array[10] during runtime then the
program will throw an error or will show an abnormal behavior and print any garbage value.

3.Logical Errors

LECTURE NOTES 25
C PROGRAM FOR ENGINEERS

Even if the syntax and other factors are correct, we may not get the desired results due to logical issues.
These are referred to as logical errors. We sometimes put a semicolon after a loop, which is syntactically
correct but results in one blank loop. In that case, it will display the desired output.
Example: In the below example, the for loop iterates 5 times but the output will be displayed only one
time due to the semicolon at the end of for loop. This kind of error is called a logical error.

4. Linker Errors
When the program is successfully compiled and attempting to link the different object files with the
main object file, errors will occur. When this error occurs, the executable is not generated. This could
be due to incorrect function prototyping, an incorrect header file, or other factors. If main() is written
as Main(), a linked error will be generated.
Example: Below is the C program to show the linker error.

5. Semantic Errors
When a sentence is syntactically correct but has no meaning, semantic errors occur. This is similar to
grammatical errors. If an expression is entered on the left side of the assignment operator, a semantic
error may occur.

LECTURE NOTES 26
C PROGRAM FOR ENGINEERS

Example: Below is the C program to show semantic error.

Object and Executable Code


Source code is the C program that you write in your editor and save with a ‘ .C ‘ extension.
Which is un-compiled (when written for the first time or whenever a change is made in it and
saved).

Object code is the output of a compiler after it processes the source code. The object code is
usually a machine code, also called a machine language, which can be understood directly
by a specific type of CPU (central processing unit), such as x86 (i.e., Intel-compatible) or
PowerPC. However, some compilers are designed to convert source code into an assembly
language or some other another programming language. An assembly language is a human-
readable notation using the mnemonics (mnemonicis a symbolic name for a single executable
machine language instruction called an opcode) in the ISA (Instruction Set Architecture) of
that particular CPU .

Executable (also called the Binary) is the output of a linker after it processes the object
code. A machine code file can be immediately executable (i.e., runnable as a program), or it
might require linking with other object code files (e.g. libraries) to produce a complete
executable program.

LECTURE NOTES 27
C PROGRAM FOR ENGINEERS

ELEMENTS OF C
Every language has some basic elements & grammatical rules. Before starting with
programming, we should be acquainted with the basic elements that build the language.
1.Character Set
Communicating with a computer involves speaking the language the computer understands. In
C, various characters have been given to communicate. Character set in C consists of;
Types

2.Keywords
Keywords are the words whose meaning has already been explained to the C compiler. The
keywords cannot be used as variable names because if we do so we are trying to assign a
new meaning to the keyword, which is not allowed by the computer. There are only 32
keywords available in C. Below figure gives a list of these keywords for your ready
reference.

3.Identifier (Can refer below)


4. Datatypes (Can refer below)

LECTURE NOTES 28
C PROGRAM FOR ENGINEERS

Variables
What is a variable in C?
A variable in C is a memory location with some name that helps store some form of data and
retrieves it when required. We can store different types of data in the variable and reuse the
same variable for storing some other data any number of times.
They can be viewed as the names given to the memory location so that we can refer to it without
having to memorize the memory address. The size of the variable depends upon the data type
it stores.

C Variable Syntax
The syntax to declare a variable in C specifies the name and the type of the variable.
data_type variable_name = value; // defining single variable
or
data_type variable_name1, variable_name2; // defining multiple variable
Here,
 data_type: Type of data that a variable can store.
 variable_name: Name of the variable given by the user.
 value: value assigned to the variable by the user.
There are 3 aspects of defining a variable:
1. Variable Declaration
2. Variable Definition
3. Variable Initialization
1. C Variable Declaration
Variable declaration in C tells the compiler about the existence of the variable with the given
name and data type. When the variable is declared, an entry in symbol table is created and
memory will be allocated at the time of initialization of the variable.
2. C Variable Definition
In the definition of a C variable, the compiler allocates some memory and some value to it. A
defined variable will contain some random garbage value till it is not initialized.
Example
int var;
char var2;

LECTURE NOTES 29
C PROGRAM FOR ENGINEERS

Note: Most of the modern C compilers declare and define the variable in single step. Although
we can declare a variable in C by using extern keyword, it is not required in most of the cases.
3. C Variable Initialization
Initialization of a variable is the process where the user assigns some meaningful value to the
variable when creating the variable.
Example
int var = 10; // variable declaration and definition (i.e. Vairable Initialization)
Difference between Variable Initialization and Assignment
Initialization occurs when a variable is first declared and assigned an initial value. This usually
happens during the declaration of the variable. On the other hand, assignment involves setting
or updating the value of an already declared variable, and this can happen multiple times after
the initial initialization.
Example
int a=10; //Variable initialization
a=10; //assignment

Rules for defining variables


• A variable can have alphabets, digits, and underscore.
• A variable name can start with the alphabet, and underscore only. It can't start with a
digit.
• No whitespace is allowed within the variable name.
• A variable name must not be any reserved word or keyword, e.g. int, float, etc.

Valid variable names Invalid variable names


int a; int 2;
int _ab; int a b;
int a30; int long;

Difference between Identifier and Variable?


• The identifier is just the name given to the variable, while a variable represents a
memory field where some data is stored based on its data type.
• It's just like what is the difference between you and your name. Your name is just a
word that people call you with, while you are a human being.

LECTURE NOTES 30
C PROGRAM FOR ENGINEERS

Basic C program to print an integer

Output : 5
Data types
Each variable in C has an associated data type. It specifies the type of data that the variable can
store like integer, character, floating, double, etc. Each data type requires different amounts of
memory and has some specific operations which can be performed over it.

LECTURE NOTES 31
C PROGRAM FOR ENGINEERS

Different data types also have different ranges upto which they can store numbers. These ranges
may vary from compiler to compiler. Below is a list of ranges along with the memory
requirement and format specifiers on 32- bit GCC compiler.
We can use 2 qualifiers with these primitive data types to get more types as shown in below
table: They are 2 types of Qualifiers
Sign Qualifier- Signed and Unsigned
Size Qualifier – short and long
Data type Size Range Format Specifier
(Bytes)
short int 2 -32,768 to 32767 %hd
unsigned short int 2 0 to 65535 %hu
unsigned int 4 0 to 4,294,967,295 %u
int 4 -2,147,483,648 to 2,147,483,647 %d
long int 4 -2,147,483,648 to 2,147,483,647 %ld
unsigned long int 4 0 to 4,294,967,295 %lu
long long int 8 -(2^63) to (2^63)-1 %lld
unsigned long 8 0 to 18,446,744,073,709,551,615 %llu
long int
signed char 1 -128 to 127 %c
unsigned char 1 0 to 255 %c
float 4 1.2E-38 to 3.4E+38 %f
double 8 1.7E-308 to 1.7E+308 %lf
long double 16 3.4E-4932 to 1.1E+4932 %Lf

Sizeof() operator
Sizeof() is a much-used operator in the C. It is a compile-time unary operator which can be
used to compute the size of its operand. The result of sizeof is of the unsigned integral type
which is usually denoted by size_t. sizeof can be applied to any data type, including primitive
types such as integer and floating-point types, pointer types, or compound datatypes such as
Structure, union, etc.

LECTURE NOTES 32
C PROGRAM FOR ENGINEERS

Constants
A constant value is the one which does not change during the execution of a program. C
supports several types of constants.
1. Integer Constants
2. Real Constants
3. Single Character Constants
4. String Constants
Integer Constants:
An integer constant is a sequence of digits. There are 3 types of integer namely decimal
integer, octal integers and hexadecimal integer.
Decimal Integers consists of a set of digits 0 to 9 preceded by an optional + or -
sign. Spaces, commas and non-digit characters are not permitted between digits.
Example for valid decimal integer constants is

LECTURE NOTES 33
C PROGRAM FOR ENGINEERS

123, -31, 0, 562321, + 78


Octal Integers constant consists of any combination of digits from 0 through 7 with
a O at the beginning. Some examples of octal integers are
O26, O, O347, O676
Hexadecimal integer constant is preceded by OX or Ox, they may contain alphabets from A
to F or a to f. The alphabets A to F refers to 10 to 15 in decimal digits.
Example of valid hexadecimal integers are
OX2, OX8C, OXbcd, Ox
Real Constants: Real Constants consists of a fractional part in their representation. Integer
constants are inadequate to represent quantities that vary continuously. These quantities are
represented by numbers containing fractional parts like 26.082.
Example of real constants are
0.0026, -0.97, 435.29, +487.0
Single Character Constants: A Single Character constant represent a single character which
is enclosed in a pair of quotation symbols.
Example for character constants are
‘5’ , ‘x’ , ‘;’ , ‘ ‘
All character constants have an equivalent integer value which is called ASCII Values.
String Constants: A string constant is a set of characters enclosed in double quotation marks.
The characters in a string constant sequence may be a alphabet, number, special character and
blank space. Example of string constants are
“VISHAL” ,”1234” , ”God Bless” , ”! ?”

There are two simple ways in C to declare constants –


#define is a keyword used to declare constants. Data defined by the #define are preprocessed,
so that your entire code can use it. This can free up space and increase compilation times. This
is written above the main function.

Using #define preprocessor.


Syntax: # define identifier value
Example: # define pi 3.14

LECTURE NOTES 34
C PROGRAM FOR ENGINEERS

Output:

Using const Keyword:


const is a keyword used to declare constants. Data defined by the const are constant so that
your entire code can use it. This is written in the main function.
Using const keyword
Syntax: const datatype variable_name = value;
Example: const float pi =3.14;

LECTURE NOTES 35
C PROGRAM FOR ENGINEERS

Output

Storage Classes
• Storage classes in C are used to determine the lifetime, visibility, memory location, and
initial value of a variable.
• Any variable declared in C can have any one of the four classes.
1. Automatic variables.
2. External variables.
3. Static variables.
4. Register variables.

Automatic
• This is the default storage class for all the variables declared inside a function or a
block. Hence, the keyword auto is rarely used while writing programs in C language.
• Auto variables can be only accessed within the block/function they have been declared
and not outside them (which defines their scope).

LECTURE NOTES 36
C PROGRAM FOR ENGINEERS

Output:

Register
• The compiler tries to store these variables in the register of the microprocessor if a free
registration is available. This makes the use of register variables to be much faster than
that of the variables stored in the memory during the runtime of the program.

LECTURE NOTES 37
C PROGRAM FOR ENGINEERS

Extern
• Also, a normal global variable can be made extern as well by placing the ‘extern’
keyword before its declaration/definition in any function/block.

Static
• Static variables have the property of preserving their value even after they are out of
their scope!
• Hence, static variables preserve the value of their last use in their scope.
• So we can say that they are initialized only once and exist till the termination of the
program.

LECTURE NOTES 38
C PROGRAM FOR ENGINEERS

Unit II
Expressions and Statements
In C language, operators are symbols that represent operations to be performed on one or more
operands. They are the basic components of the C programming. In this article, we will learn
about all the built-in operators in C with examples.
What is a C Operator?
An operator in C can be defined as the symbol that helps us to perform some specific
mathematical, relational, bitwise, conditional, or logical computations on values and variables.
The values and variables used with operators are called operands. So we can say that the
operators are the symbols that perform operations on operands.
Operator: A symbol or function that performs an operation on an operand. Operators can be
represented by keywords or special characters. There are several types of operators such as
 Arithmetic Operators
 Relational (or) Comparison operators
 Assignment operators
 Bitwise Operators
 Logical Operators
Operand: A value or expression that is used as input for an operator. Operands can be constants,
variables, array elements, functions, structured record fields and expressions.

Arithmetic Operations in C
The arithmetic operators are used to perform arithmetic/mathematical operations on operands.

LECTURE NOTES 39
C PROGRAM FOR ENGINEERS

Sample programs on Arithmetic operators

Increment: It increases the value by 1. There are two types of increments


Pre- Increment: The value gets incremented before the operation is performed
Post-Increment: The value gets incremented after the operation is performed

LECTURE NOTES 40
C PROGRAM FOR ENGINEERS

Decrement: It decreases the value by 1. There are two types of decrements


Pre- Decrement: The value gets decremented before the operation is performed
Post-Decrement: The value gets decremented after the operation is performed
Post-Decrement

Output:
Pre-Decrement

Output:

LECTURE NOTES 41
C PROGRAM FOR ENGINEERS

Relational Operators:
The relational operators in C are used for the comparison of the two operands. All these
operators are binary operators that return true or false values as the result of comparison.

Sample program on relational operators

LECTURE NOTES 42
C PROGRAM FOR ENGINEERS

Assignment Operators:
Assignment operators are used to assign value to a variable. The left side operand of the
assignment operator is a variable and the right-side operand of the assignment operator is a
value. The value on the right side must be of the same data type as the variable on the left side
otherwise the compiler will raise an error.
The assignment operators can be combined with some other operators in C to provide multiple
operations using single operator. These operators are called compound operators.
In C, there are 11 assignment operators :

LECTURE NOTES 43
C PROGRAM FOR ENGINEERS

Sample program on Assignment operators

Bitwise Operators:
The Bitwise operators are used to perform bit-level operations on the operands. The operators
are first converted to bit-level and then the calculation is performed on the operands.
Mathematical operations such as addition, subtraction, multiplication, etc. can be performed at
the bit level for faster processing.

LECTURE NOTES 44
C PROGRAM FOR ENGINEERS

Note : ~a= -(a+1)


Sample program on Bitwise operators

LECTURE NOTES 45
C PROGRAM FOR ENGINEERS

Logical Operators:
Logical Operators are used to combine two or more conditions/constraints or to complement
the evaluation of the original condition in consideration. The result of the operation of a logical
operator is a Boolean value either true or false.

Sample program on Logical operators

LECTURE NOTES 46
C PROGRAM FOR ENGINEERS

Misc (Miscellaneous Operators)

Sizeof() =Refer Datatypes topic


Ternary operator (?)
 The conditional operator is the only ternary operator in C++.
 Here, Expression1 is the condition to be evaluated. If the condition(Expression1)
is True then we will execute and return the result of Expression2 otherwise if the
condition(Expression1) is false then we will execute and return the result of
Expression3.
 We may replace the use of if..else statements with conditional operators.
Syntax
operand1 ? operand2 : operand3;

&, * =Refer pointers topic in Unit 4

LECTURE NOTES 47
C PROGRAM FOR ENGINEERS

Precedence and Associativity of Operators

LECTURE NOTES 48
C PROGRAM FOR ENGINEERS

Data type Conversions (or) Type Casting


Type conversion in C is the process of converting one data type to another. The type conversion
is only performed to those data types where conversion is possible. Type conversion is
performed by a compiler. In type conversion, the destination data type can’t be smaller than
the source data type. Type conversion is done at compile time and it is also called widening
conversion because the destination data type can’t be smaller than the source data type. There
are two types of Conversion:
1.Implicit Type Conversion (or) Automatic type conversion
A.Done by the compiler on its own, without any external trigger from the user.
B. Generally takes place when in an expression more than one data type is present. In such
conditions type conversion (type promotion) takes place to avoid loss of data.
C. All the data types of the variables are upgraded to the data type of the variable with the
largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
D. It is possible for implicit conversions to lose information, signs can be lost (when signed is
implicitly converted to unsigned), and overflow can occur (when long is implicitly converted
to float).

LECTURE NOTES 49
C PROGRAM FOR ENGINEERS

Example of Implicit Conversion

Output:

Explicit Type Conversion

LECTURE NOTES 50
C PROGRAM FOR ENGINEERS

This process is also called type casting and it is user-defined. Here the user can typecast the
result to make it of a particular data type. The syntax in C Programming:
(type) expression
Type indicated the data type to which the final result is converted.
Example of Explicit Conversion

Output

LECTURE NOTES 51
C PROGRAM FOR ENGINEERS

Statements
Control Flow statements
Control flow statements are fundamental components of programming languages that allow
developers to control the order in which instructions are executed in a program. They enable
execution of a block of code multiple times, execute a block of code based on conditions,
terminate or skip the execution of certain lines of code, etc.

Decision Making Statements


1.if
Syntax Flowchart

LECTURE NOTES 52
C PROGRAM FOR ENGINEERS

Here, the condition after evaluation will be either true or false. C if statement accepts boolean
values – if the value is true then it will execute the block of statements below it otherwise not.
If we do not provide the curly braces ‘{‘ and ‘}’ after if(condition) then by default if statement
will consider the first immediately below statement to be inside its block.
Example of if statement

Output:

2.If-else
The if statement alone tells us that if a condition is true it will execute a block of statements
and if the condition is false it won’t. But what if we want to do something else when the
condition is false? Here comes the C else statement. We can use the else statement with
the if statement to execute a block of code when the condition is false. The if-else
statement consists of two blocks, one for false expression and one for true expression.
Syntax Flowchart

LECTURE NOTES 53
C PROGRAM FOR ENGINEERS

Example of if-else statements:

LECTURE NOTES 54
C PROGRAM FOR ENGINEERS

3.if-else if Ladder
The if-else if statements are used when the user has to decide among multiple options. The C
if statements are executed from the top down. As soon as one of the conditions controlling the
if is true, the statement associated with that if is executed, and the rest of the C else-if ladder is
bypassed. If none of the conditions is true, then the final else statement will be executed. if-
else-if ladder is similar to the switch statement.
Syntax Flowchart

Example of if-else if statement

LECTURE NOTES 55
C PROGRAM FOR ENGINEERS

4.Nested if-else in C
A nested if in C is an if statement that is the target of another if statement. Nested if statements
mean an if statement inside another if statement. Yes, C allow us to nested if statements within
if statements, i.e, we can place an if statement inside another if statement.
Syntax

Flowchart

LECTURE NOTES 56
C PROGRAM FOR ENGINEERS

Example of Nested -if Statement

Output:

5.Switch statement:
Switch statement is a fundamental building block in many programming languages. It allows
us to efficiently handle situations where the program needs to perform different actions based
on different values of a variable.
A switch statement typically consists of the following elements.
 Switch expression: This is an expression that is evaluated to determine which case to
execute. Commonly, it's an integer or a character variable.
 Case Statement: These statements define the different possible values the switch
expression can take and the corresponding code to be executed if there's a match.
 Case block: This block contains the code to be executed based on the value of the
switch expression.

LECTURE NOTES 57
C PROGRAM FOR ENGINEERS

 Break statement: This statement terminates the execution of the case block once a
matching case is found. Without a break, the program might continue executing code
from subsequent cases.
Syntax

Flowchart

LECTURE NOTES 58
C PROGRAM FOR ENGINEERS

Example of Switch Statement

LECTURE NOTES 59
C PROGRAM FOR ENGINEERS

Iterative Statements
Loops in programming are used to repeat a block of code until the specified condition is met.
A loop statement allows programmers to execute a statement or group of statements multiple
times without repetition of code.
Sample Program that repeats a block of code

There are mainly two types of loops in C Programming:


1. Entry Controlled loops: In Entry controlled loops the test condition is checked before
entering the main body of the loop. For Loop and While Loop is Entry-controlled
loops.
2. Exit Controlled loops: In Exit controlled loops the test condition is evaluated at the
end of the loop body. The loop body will execute at least once, irrespective of whether
the condition is true or false. do-while Loop is Exit Controlled loop.

LECTURE NOTES 60
C PROGRAM FOR ENGINEERS

For Loop
for loop in C programming is a repetition control structure that allows programmers to write a
loop that will be executed a specific number of times. for loop enables programmers to perform
n number of steps together in a single line.
Syntax

In for loop, a loop variable is used to control the loop. Firstly we initialize the loop variable
with some value, then check its test condition. If the statement is true then control will move
to the body and the body of for loop will be executed. Steps will be repeated till the exit
condition becomes true. If the test condition will be false then it will stop.
 Initialization Expression: In this expression, we assign a loop variable or loop counter
to some value. for example: int i=1;
 Test Expression: In this expression, test conditions are performed. If the condition
evaluates to true then the loop body will be executed and then an update of the loop
variable is done. If the test expression becomes false then the control will exit from the
loop. for example, i<=9;
 Update Expression: After execution of the loop body loop variable is updated by some
value it could be incremented, decremented, multiplied, or divided by any value.

LECTURE NOTES 61
C PROGRAM FOR ENGINEERS

Flowchart

Sample program to print hello world 10 times using for loop

While Loop
While loop does not depend upon the number of iterations. In for loop the number of iterations
was previously known to us but in the While loop, the execution is terminated on the basis of
the test condition. If the test condition will become false then it will break from the while loop
else body will be executed.

LECTURE NOTES 62
C PROGRAM FOR ENGINEERS

Syntax Flowchart

Sample program to print hello world 10 times using while loop

LECTURE NOTES 63
C PROGRAM FOR ENGINEERS

do-while Loop
The do-while loop is similar to a while loop but the only difference lies in the do-while loop
test condition which is tested at the end of the body. In the do-while loop, the loop body
will execute at least once irrespective of the test condition.
Syntax Flowchart

Sample program to print hello world 10 times using do-while loop

LECTURE NOTES 64
C PROGRAM FOR ENGINEERS

Jump Statements in C
In C, jump statements are used to jump from one part of the code to another altering the normal
flow of the program. They are used to transfer the program control to somewhere else in the
program.
In this article, we will discuss the jump statements in C and how to use them.
Types of Jump Statements in C
There are 4 types of jump statements in C:
1. break
2. continue
3. goto
4. return

break in C
The break statement exits or terminates the loop or switch statement based on a certain
condition, without executing the remaining code.
Syntax

Flowchart

LECTURE NOTES 65
C PROGRAM FOR ENGINEERS

Uses of break in C
The break statement is used in C for the following purposes:
1. To come out of the loop.
2. To come out from the nested loops.
3. To come out of the switch case.
Sample program to demonstrate break statement

Explanation:
 Loop Execution Starts and goes normally till i = 5.
 When i = 6, the condition for the break statement becomes true and the program control
immediately exits the loop.
 The control continues with the remaining statements outside the loop.

LECTURE NOTES 66
C PROGRAM FOR ENGINEERS

Continue in C
The continue statement in C is used to skip the remaining code after the continue statement
within a loop and jump to the next iteration of the loop. When the continue statement is
encountered, the loop control immediately jumps to the next iteration, by skipping the lines of
code written after it within the loop body.
Syntax

Flowchart

Sample program to demonstrate continue statement

LECTURE NOTES 67
C PROGRAM FOR ENGINEERS

Explanation: The for loop iterates from 0 to 5. Inside the loop, we check if i is equal to 2. If
the condition is true, the continue statement is executed, and it skips the remaining code within
the loop for that iteration. If the condition is false, the code proceeds normally.

Goto Statement in C
The goto statement is used to jump to a specific point from anywhere in a function. It is used
to transfer the program control to a labeled statement within the same function.
Syntax

Flowchart

LECTURE NOTES 68
C PROGRAM FOR ENGINEERS

Sample program to explain goto statement

LECTURE NOTES 69

You might also like