Notes of UNIT1,2
Notes of UNIT1,2
C PROGRAMMING FOR
ENGINEERS
N.Haripriya (Ph.D)
Assistant Professor
ECE
C PROGRAM FOR ENGINEERS
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.
LECTURE NOTES 3
C PROGRAM FOR ENGINEERS
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
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
LECTURE NOTES 10
C PROGRAM FOR ENGINEERS
LECTURE NOTES 11
C PROGRAM FOR ENGINEERS
LECTURE NOTES 12
C PROGRAM FOR ENGINEERS
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.
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
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
LECTURE NOTES 16
C PROGRAM FOR ENGINEERS
LECTURE NOTES 17
C PROGRAM FOR ENGINEERS
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
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.
LECTURE NOTES 19
C PROGRAM FOR ENGINEERS
BEGIN
NUMBER s1, s2, sum
INPUT s1
INPUT s2
sum=s1+s2
OUTPUT sum
END
LECTURE NOTES 20
C PROGRAM FOR ENGINEERS
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;
}
LECTURE NOTES 23
C PROGRAM FOR ENGINEERS
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
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
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.
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
LECTURE NOTES 30
C PROGRAM FOR ENGINEERS
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
LECTURE NOTES 34
C PROGRAM FOR ENGINEERS
Output:
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
LECTURE NOTES 40
C PROGRAM FOR ENGINEERS
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.
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
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
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.
LECTURE NOTES 46
C PROGRAM FOR ENGINEERS
LECTURE NOTES 47
C PROGRAM FOR ENGINEERS
LECTURE NOTES 48
C PROGRAM FOR ENGINEERS
LECTURE NOTES 49
C PROGRAM FOR ENGINEERS
Output:
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.
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
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
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
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
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
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
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
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
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
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
LECTURE NOTES 69