0% found this document useful (0 votes)
26 views127 pages

Unit I C

Uploaded by

shanthisree2486
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)
26 views127 pages

Unit I C

Uploaded by

shanthisree2486
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/ 127

UNIT I

BASICS OF C PROGRAMMING

Computer Centre - Madras Institute of


9/20/2023 1
Technology
UNIT I
Topics to be Covered:
 Introduction to programming paradigms
 Structure of C program
 C programming:
 Data Types
 Constants
 Keywords
 Operators
 Operator Precedence and Associativity
 Expressions
 Input/Output statements
 Assignment statements
 Decision making statements
 Switch statement
Computer Centre - Madras Institute of
9/20/2023 2
Technology
Topic of Discussion
Introduction to programming paradigms
Structure of C program
C programming:
Data Types
Constants
Keywords
Operators
Operator Precedence and Associativity
 Expressions
Input/Output statements
Assignment statements
Decision making statements
Switch statement

Computer Centre - Madras Institute of


9/20/2023 3
Technology
What is a Programming Paradigm?
• Programming paradigm is defined as a set of principles,
ideas, design concepts and norms that defines the
manner in which the program code is written and
organized.
• It is all about the writing style and organizing the
program code in a specific way.
• It does not specify the programming language syntax, it
simply defines the program structure and set of principles
that the programming language compiler should enforce.
• Each paradigm advocates a specific way to organize the
program code.
• For example, the OOP paradigm represents everything in
the form of objects, whereas the function programming
represents the program as set of functions and in logic
programming , a logic is created by series of symbols .
Computer Centre - Madras Institute of
9/20/2023 4
Technology
Programming Paradigm – Cont’d
• Each programming language has unique programming style
that implements a specific programming paradigm
• If a programming language support or falls under a certain
paradigm then this means it has some unique feature or it
follows a certain approach that makes it best to solve a
certain kind of problem.
• For example:
– Object-oriented programming is best suited for implementing real-
world entities by hiding important data and finding methods with
the entities. Example C++, Java, Python, etc.
– Logical programming is best for creating logic by a complex
structure of symbols. Example Prolog, F-logic, etc.
• A good programming language should support multiple
paradigms because different programming problems require a
different way to approach.
• Most modern languages like C++, C#, Python, Go, etc. support
multi-paradigm languages
Computer Centre - Madras Institute of
9/20/2023 5
Technology
Types of Programming Paradigm

• The programming paradigms are categorized in multiple


categories yet most significant are only two:
– Imperative programming paradigm
– Declarative programming paradigm
Computer Centre - Madras Institute of
9/20/2023 6
Technology
Imperative programming paradigm
• The word “imperative” comes from
the Latin “impero” meaning “I
command”.
bake a cake • The imperative paradigm is said to
be command driven.
• In Imperative programming, the
programmer has to elaborate each
statement in detail.
• Each statement directs what is to be
done and how it is to be done.
• In an imperative programming
paradigm, the order of the steps is
crucial
• Fortran, Java , c++, c programming
languages are examples of
9/20/2023
imperative
Computer programming.
Centre - Madras Institute of
7
Technology
Imperative programming paradigm –Cont’d
Find the sum of first ten natural numbers in the imperative paradigm approach.
Example in C:
#include <stdio.h>
int main()
{
• In this example, we are
int sum = 0; commanding the
sum += 1;
sum += 2; computer what to do line
sum += 3;
sum += 4; by line.
sum += 5;
sum += 6; • Finally, we are storing the
sum += 7;
sum += 8; value and printing it.
sum += 9;
sum += 10;
printf("The sum is: %d\n", sum);
return 0;
}
Output:
Computer Centre - Madras Institute of
The sum is: 55
9/20/2023
Technology
8
Types of imperative programming
paradigms
• Procedural Programming
• Object-oriented Programming
• Parallel Processing Approach

Computer Centre - Madras Institute of


9/20/2023 9
Technology
Imperative programming paradigm
Procedural Programming
bake a cake
• It is a programming paradigm
based upon the concept of
procedure calls.
• Here, statements are structured
into procedures (also known as
subroutines or functions).
• Procedures contain a series of
computational commands that
should be carried out to achieve a
certain outcome.
• Procedure call that lets to reuse
the code.
• Procedural programming
languages are known as top-down
languages.
Computer Centre - Madras Institute of
9/20/2023 10
Technology
Imperative programming paradigm
Procedural Programming –Cont’d
#include <stdio.h> • simplification and
int add(int n1,int n2){
int s; abstraction is one of
s=n1+n2;
return s;
the benefits of
} procedural
int main()
{
programming. But
int a=10; within the functions,
int b=20;
int sum1=add(a,b); we still got same old
printf("The sum is of %d + %d= %d\n", a,b,sum1); imperative code.
int p=56;
int q=78; • Example of procedural
int sum2=add(p,q);
printf("The sum is of %d + %d= %d\n", p,q,sum2); programming is BASIC
return 0; C, and Pascal.
}
Computer Centre - Madras Institute of
9/20/2023 11
Technology
Imperative programming paradigm
Object-oriented Programming
• It is the most popular programming
paradigm because of its unique
advantages like the modularity of the
code and the ability to directly associate
real-world business problems in terms of
code.
• The key characteristics of object-oriented
programming include Class, Abstraction,
Encapsulation, Inheritance and
Polymorphism.
• A class is a template or blueprint from
which objects are created.
• An object contains data in the form of
fields that are known as attributes
and the procedures are known
as methods.
• Examples of Object Oriented
programming paradigm: Simula, Java, C++,
ComputerPython, Ruby,
Centre - Madras Smalltalk , etc
Institute of
9/20/2023 12
Technology
Object-oriented Programming- Cont’d

OOP facilitates the


understanding of a program,
by the clear separation of
concerns and responsibilities.
Computer Centre - Madras Institute of
9/20/2023 13
Technology
Imperative programming paradigm
Parallel Processing Approach
• The parallel programming paradigm breaks the problem
or task into chunks that are distributed among multiple
processors.
• These chunks work on the same problem, simultaneously.
• It reduces the total time to solve a problem.
• It connects multiple processors to the memory.
• It is either pooled across all processors or distributed over
a network.
• There are several programming languages that support
parallel processing.
• Example of parallel programming paradigm is SISAL,
Parallel Haskell, SequenceL, System C (for FPGAs),
Mitrion-C, VHDL, and Verilog, MPI.
Computer Centre - Madras Institute of
9/20/2023 14
Technology
Declarative programming paradigm
• A declarative programming paradigm are those
paradigms in which the programmer describes the
property of the result without focusing on how to
achieve it (imperative programming focuses on how to
achieve the task by changing the state of the program).
• The main focus in this kind of programming is what is
to be done rather than how it should be done.
• Declarative programming is used in programming
languages used in a database query, regular expression,
functional programming, logical programming, etc.
• Some of the programming languages that support the
declarative paradigm are:Prolog, javascript, Scala, Lisp,
SQL, XQuery, Clojure
Computer Centre - Madras Institute of
9/20/2023 15
Technology
Types of Declarative Programming
Paradigms
• Functional Programming
• Logical Programming
• Database Processing Approach

Computer Centre - Madras Institute of


9/20/2023 16
Technology
Declarative Programming Paradigms
Functional Programming
• It is the programming in which a
program is constructed by
creating and using functions.
• The functions we refer to here
are pure functions only.
• Pure functions are
representations of mathematical
functions.
• This means functions just do one
thing.
• They don’t depend on anything
else but their arguments, and
always produce the same result.

Computer Centre - Madras Institute of


9/20/2023 17
Technology
Declarative Programming Paradigms
Functional Programming – Cont’d
• Rather than a series of statements functional
programming use function to map and change one value
to another value.
• The other important note is, there are no loops in
functional programming, all we have is implementing
pure functions which have zero side effects.
Example,

Computer Centre - Madras Institute of


9/20/2023 18
Technology
Declarative Programming Paradigms
Logical Programming
• It's based on formal logic.
• The logic programming paradigm isn't made up of instructions - rather
it's made up of facts and clauses.
• Logic programming uses sentences in logical form and creates an
expression by using symbols.
• In machine learning and artificial intelligence, there are many models
that use these programs..
• The programs are executed very much like some mathematical
statement. It is mainly based on forming logic.
• For instance, Socrates is a man, all men are mortal, and therefore
Socrates is mortal.
• The following is a simple Prolog program which explains the above
instance:
man(Socrates).
mortal(X) :- man(X)
Computer Centre - Madras Institute of
9/20/2023 19
Technology
Declarative Programming Paradigms
Logical Programming – Cont’d
man(Socrates).
mortal(X) :- man(X)
• The first line can be read, "Socrates is a man.'' It is a base
clause, which represents a simple fact.
• The second line can be read, "X is mortal if X is a man;''
in other words, "All men are mortal.'' This is a clause, or
rule, for determining when its input X is "mortal.
• The symbol ":-'', sometimes called a turnstile, is
pronounced "if'‘.
• We can test the program by asking the question:
?- mortal(Socrates).
• that is, "Is Socrates mortal?'' (The "?-'' is the computer's
prompt for a question). Prolog will respond "yes''.
Computer Centre - Madras Institute of
9/20/2023 20
Technology
Declarative Programming Paradigms
Database Processing Approach
• This programming methodology is based on data and
its movement.
• Program statements are defined by data rather than
hard-coding a series of steps.
• A database is an organized collection of structured
information, or data, typically stored electronically in a
computer system.
• A database is usually controlled by a database
management system (DBMS)
• To process the data and querying them, databases
use tables.
• Data can then be easily accessed, managed, modified,
updated, controlled and organized.
Computer Centre - Madras Institute of
9/20/2023 21
Technology
Declarative Programming Paradigms
Database Processing Approach – Cont’d
• A good database processing approach is crucial to any
company or organization. This is because the database stores
all the pertinent details about the company such as employee
records, transaction records and salary details.
• Most databases use Structured Query Language (SQL) for
writing and querying data.
• Here’s an example in database processing approach (SQL):

Computer Centre - Madras Institute of


9/20/2023 22
Technology
Topic of Discussion
Introduction to programming paradigms
Structure of C program
C programming:
Data Types
Constants
Keywords
Operators
Operator Precedence and Associativity
 Expressions
Input/Output statements
Assignment statements
Decision making statements
Switch statement
Computer Centre - Madras Institute of
9/20/2023 23
Technology
C programming Introduction
• In 1960’s  Horde of computer languages, each for
specific purpose.
• Example,
– COBOL(Common Business Oriented Language)
Commercial Applications
– FORTRAN (FORMula TRANslator )
 Engineering & Scientific Applications
• Instead of learning and using so many languages, each
for a different purpose, why not use only one language
which can program all possible applications?
– Therefore an International committee was set up to develop
such a language called ALGOL 60
Computer Centre - Madras Institute of
9/20/2023 24
Technology
C programming Introduction – Cont’d
Year Language Developed by Remarks
1960 ALGOL International committee Too general, Too abstract
1963 CPL Cambridge University Hard to learn, difficult to
implement
1967 BCPL Martin Richards at Could deal with only specific
Cambridge University problems
1970 B Ken Thomson at AT & T Could deal with only specific
problems

1972 C Dennis Ritchie at AT & T Inherited the features of B &


BCPL and added some more
features

Computer Centre - Madras Institute of


9/20/2023 25
Technology
C programming Introduction – Cont’d
Where C Stands?
Machine Oriented / Problem Oriented /
Low Level Languages High Level Languages
Give a better programming
Give a better machine efficiency, i.e. Faster program
efficiency, i.e. Faster development
program execution C Eg.
Eg. FORTRAN
Assembly language, BASIC
Machine language PASCAL

• C stands in between High level and Low level, therefore it


is often called as MIDDLE LEVEL LANGUAGE
Computer Centre - Madras Institute of
9/20/2023 26
Technology
C programming Introduction – Cont’d
Importance of C
• C Programs are efficient, fast and highly portable
• Portable: C program written for one computer can be run
on another computer
• Middle-Level Language: C compiler combines the
capabilities of an assembly language with the features of
high level language and therefore it is suited for writing
both system software and application software (business
package)
• Structured Language: Programming with structured
languages is efficient and fast due to modular approach
and it is easy for debugging, testing, and maintenance
• Robust: Rich set of built-in functions and operators can be
used to write any complex programs
• Ability to extend: New functions can be added to the C
library (Collection of Functions)
Computer Centre - Madras Institute of
9/20/2023 27
Technology
C programming Introduction – Cont’d
Why should we learn C?
• Helps to understand the fundamentals of Computer
Theories, Most of the theories related to computers
like Computer Networks, Compiler Designing, Computer
Architecture, Operating Systems are based on C
programming language
• C programming language has fewer libraries and
implementing them on our own will help us to build our
analytical skills
• C is very fast in terms of execution time
• C is extensively used in Embedded Programming also
referred as micro-controller programming. (
Microcontrollers and embedded programming is widely
used in auto-motives, Robotics, Hardware etc)
Computer Centre - Madras Institute of
9/20/2023 28
Technology
C programming Introduction – Cont’d
• Communicating with a computer involves speaking the language the computer
understands
• There is a close analogy between leaning any human language and learning C language
Alphabets Words Sentence Paragraph

English

Tamil

Character Set Keywords (Special Statement


a..z words) Program
printf("Welcome to MIT")
A...Z if, and, or...
C 0..9 int num=10
Identifiers/Variables float val=56.789
+,-,#,!,~,... num, val, name
Computer Centre - Madras Institute of
9/20/2023
Technology
char name[]="Sanjay" 29
Alphabets in C
( Character set in C)
Type of Character Description Characters

Lowercase a to z a, b, c, d, e, f, g, h, i, j, k, l, m, n,
Alphabets o, p, q, r, s, t, u, v, w, x, y, z

Uppercase A to Z A, B, C, D, E, F, G, H, I, J, K, L, M,
Alphabets N, O, P, Q, R, S, T, U, V, W, X, Y, Z

Digits 0 to 9 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special – `~@!$#^*%&()[]{}<>+
Characters =_–|/\;:‘“,.?

White Spaces – Blank Spaces, Carriage Return,


Computer Centre -Tab,
Madras New
Institute ofLine
9/20/2023 30
Technology
Words in C
( Keywords & Identifiers)
• Keywords: • Identifiers / variable
predefined or name:
reserved words that  represent the names of
have special various entities such as
meanings to the variables ,arrays,
compiler functions, user-defined
data types, labels, etc.

Computer Centre - Madras Institute of


9/20/2023 31
Technology
Topic of Discussion
Introduction to programming paradigms
Structure of C program
C programming:
Data Types
Constants
Keywords
Operators
Operator Precedence and Associativity
 Expressions
Input/Output statements
Assignment statements
Decision making statements
Switch statement
Computer Centre - Madras Institute of
9/20/2023 32
Technology
Keywords
•As C is a case sensitive language, all keywords must be written in
lowercase.
•Here is a list of all keywords allowed in ANSI C.

Computer Centre - Madras Institute of


9/20/2023 33
Technology
Variables in C Program
• For every computer application, we must store the information at
a particular location
– For example, name, register number of students stored for student
application
• Every machine has memory 128, 572, 1024, 5098,
locations, and every memory etc. are one-one
location is identified by an memory addresses
address.

• Generally, if we want to store some


information, for example a value 10 in
the memory locations, the value will
go and be stored randomly at a
particular memory location.
Computer Centre - Madras Institute of
9/20/2023 34
Technology
Variables in C Program – Cont’d
• Since it is stored in random memory location, How to
access the data stored?
– Accessing will be very difficult
– So, we need to set the identity to the memory location before
storing information is first,.
• How we can set Identity to Memory Locations?
– Before storing the information, first, we need to set
the identity to the memory location.
– Example: int a; //Here integer is the data type and
identifier can be any name and here we set it as a.
• So, whenever we declare a variable, it gets memory
allocated.
Computer Centre - Madras Institute of
9/20/2023 35
Technology
Variables in C Program – Cont’d
Here “a” is a named memory location to the
location 10344

• Later when we are storing an element into a location that is identified by the
identifier “a” as follows.
• a = 10; //Here, the value is 10 and we are setting this value into a memory
location which is identified by “a” as shown in the below image.

Computer Centre - Madras Institute of


9/20/2023 36
Technology
What is a Variable in C Language?
• A name that is given for any computer memory location is called as
variable name or Identifier in C.
• The purpose of the variable is to store some data.
• The user will access it by the variable name and the compiler will access it
by the address.
• The value of the variable may get changed in the program, hence called
variable
• Variables should be declared in the C program before use.
• Declaration tells the compiler about the data type and size of the
variable.
• Syntax: data_type variable_name;
• For example,
int x=10; //Initial value of x is 10
x=55; // Value of x changed to 55
• C variable might be belonging to any of the data types like int, float, char,
etc. (discussed later)

Computer Centre - Madras Institute of


9/20/2023 37
Technology
Identifiers / Variable name
• Rules For Naming Identifiers in C:
– We can not use any keyword as an identifier.
– All the identifiers should have a unique name in the same scope.
– Identifiers can not start with a digit.
– The first character of an identifier should always start with an
alphabet or underscore, and then it can be followed by any of the
characters, digit, or underscore.
– The special characters such as '*','#','@','$' are not allowed within
an identifier.
– All the identifiers are case sensitive means the identifiers “sum”,
“Sum” and “SUM” will be treated differently.
– Length of an identifier should not exceed 31 characters.
– Any blank spaces or commas are not allowed within an identifier.
• Examples of Valid C identifier:
– length , total_sum, _size, len_ -, num1, num_2
• Example of Invalid C identifier:
– 5size, \@hello, int, m n, m+n
Computer Centre - Madras Institute of
9/20/2023 38
Technology
Topic of Discussion
Introduction to programming paradigms
Structure of C program
C programming:
Data Types
Constants
Keywords
Operators
Operator Precedence and Associativity
 Expressions
Input/Output statements
Assignment statements
Decision making statements
Switch statement
Computer Centre - Madras Institute of
9/20/2023 39
Technology
Data types
• As the name suggests, data types represent the kind of data that can be
stored in a variable
• It determines the amount of memory the variable takes up and the
range of values that can be stored in that memory.
• Three main categories of data types:
– Basic/Primitive
– Derived
– User-Defined

Will be
discussed in
detail now

•char is used to define characters


•int is used to define integer numbers Will be discussed
•float is used to define floating-point numbers in detail later
•double is used to define BIG floating-point numbers
• void is a special data type thatComputer
9/20/2023
Centre - Madras Institute of
represents the absence of a value
Technology
40
Basic/Primitive data types

•signed data type can store both positive or negative values (default)
•unsigned type strictly accepts only positive values (Negative values will not be
accepted)
9/20/2023
Computer Centre - Madras Institute of
41
Technology
Basic/Primitive data types Cont’d
Size and Range of Data Types in C Language
• The size of data types in C depends on the implementation and the system architecture.
• However, the following table provides the standard minimum and maximum sizes and range
of each data type as defined by the C standard:

Note: The sizes and ranges of data


types in C listed in the table are
minimums and can vary
depending on the implementation
and architecture.

Computer Centre - Madras Institute of


9/20/2023 42
Technology
Basic/Primitive data types Cont’d
Format Specifiers in C

Computer Centre - Madras Institute of


9/20/2023 43
Technology
Topic of Discussion
Introduction to programming paradigms
Structure of C program
C programming:
Data Types
Constants
Keywords
Operators
Operator Precedence and Associativity
 Expressions
Input/Output statements
Assignment statements
Decision making statements
Switch statement
Computer Centre - Madras Institute of
9/20/2023 44
Technology
Constants
• Constants in C are the read-only variables whose values cannot be
modified once they are declared in the C program.
• Constants are also called as Literals

•We can define constants in a C program using


const keyword and by #define
preprocessor directive.
•If we try to change constant values after defining
in C program, it will throw an error.
Computer Centre - Madras Institute of
9/20/2023 45
Technology
Primary Constants
Numeric constant
• integer constants:
– It is the numeric constant (constant associated with numbers)
without any fractional part or exponential part.
– These constants are always positive until we specify a negative (-)
sign.
– It must have at least one digit.
– It must NOT have any decimal point.
– In between the integer constant we do not have any separators
including comma (,).
– There are three types of integer constants in the C language:
• Decimal constant (base 10)
Decimal Digits: 0 1 2 3 4 5 6 7 8 9
Example: 0, -23, 456 etc.
• Octal constant (base 8)
Octal Digits: 0 1 2 3 4 5 6 7
Example: 021, 077, 033 etc.
• Hexadecimal constant (base 16)
Hexadecimal Digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F
9/20/2023
Example: 0x7f, 0x2a,Computer
0x521Centre
etc. - Madras Institute of 46
Technology
Primary Constants
Numeric constant –Cont’d
• We can use small caps a, b, and c instead of uppercase
letters while writing a hexadecimal constant.
• Every Octal constant stars with 0 and hexadecimal
constant starts with 0x
• Larger integer constants can be stored by appending
qualifiers such as U, L and UL to the constants
56789U or 56789u (unsigned integer)
987612347UL or 987612347ul (unsigned long integer)
9876543L or 9876543l (long integer)

Computer Centre - Madras Institute of


9/20/2023 47
Technology
Primary Constants
• Real constants:
Numeric constant
– Any signed or unsigned number with the fractional part is called a real constant or
Floating-Point constant.
– These are the numeric constants that have either fractional form or exponential form.
– It can be positive or negative but by default it is positive.
– The real constant must have at least one digit.
– It MUST have a decimal point.
– No comma and blank space are allowed within a real constant.
• Decimal floating-point constants are written using the digits 0 through 9, a
decimal point.
Example: 3.14, 6.022, 6.0, etc.
• Exponential floating-point constants are written using the letter e or E to indicate
the exponent.
• General form: mantissa e exponent
• The mantissa is either a real number expressed in decimal notation or an integer
• The exponent is an integer number with an optional plus or minus sign
• Example: 6.022e23, 6.67E12etc.
• In exponential form, theComputer
letter Centre
"e" or "E" isInstitute
- Madras usedofto indicate the value multiplied
9/20/2023 48
3.14e2 means that 3.14x102 and equals 314.
by the power of 10. For example,Technology
Primary Constants
Character constants
• A character constant is a constant value that represents a single character
• Regular characters are enclosed in single quotes (' ') and can represent
alphanumeric characters, space characters, and special characters
• Examples:
– 'A' (represents the character 'A')
– 'a' (represents the character 'a')
– '3' (represents the character '3')
– ' ' (represents a whitespace character)
– '\n' (represents a newline character)
• The value of a character constant is the numerical value of a character in the
matching character set .
– for example in the ASCII character set, character zero has a numerical value of 48
which is not at all related to the numerical value 0.

Computer Centre - Madras Institute of


9/20/2023 49
Technology
Primary Constants
String constants
• The string constant is a sequence of characters enclosed in
double quotes (" ")
• It can represent text, including regular strings,
alphanumeric characters, space characters, and special
characters.
• Examples :
– "Hello, world!" (represents the string "Hello, world!")
– "12345" (represents the string "12345")
– " " (represents a string with a single whitespace character)
– "A\nB" (represents the string "A" followed by a newline
character and then "B")
• A single character string constant does not have an
equivalent integer value while a character constant has an
integer value
Computer Centre - Madras Institute of
9/20/2023 50
Technology
Primary Constants
Backslash Character constants
• Used in output functions
• They are known as escape sequences

Computer Centre - Madras Institute of


9/20/2023 51
Technology
Topic of Discussion
Introduction to programming paradigms
Structure of C program
C programming:
Data Types
Constants
Keywords
Operators
Operator Precedence and Associativity
 Expressions
Input/Output statements
Assignment statements
Decision making statements
Switch statement
Computer Centre - Madras Institute of
9/20/2023 52
Technology
Operators
• Operators in C Language are the special kind of
symbols that performs certain operations on the
data.
• Based on the number of operands, the operators
are classified as,
– Unary Operator
• Operates only on one operand
• Example: -5, ++x
– Binary Operator
• Operates on two operands
• Example: 3*6, 5/2
– Ternary Operator:
• Operates on three operands
• Example: ?:
Computer Centre - Madras Institute of
9/20/2023 53
Technology
Operators – Cont’d
• Based upon the type of operation, operators in C
can be classified as,
– Arithmetic Operators
– Increment and Decrement Operators
– Relational Operators
– Logical Operators
– Assignment Operators
– Bitwise Operators
– Ternary or Conditional Operators
– Miscellaneous Operators
Computer Centre - Madras Institute of
9/20/2023 54
Technology
Operators – Cont’d
(Arithmetic Operators)
• These operators are used to perform simple arithmetic operations like
addition, subtraction, product, quotient, remainder, etc.
Operator Name of Operator How it is used What it does
+ Unary Plus or addition a+b Add two Operands
Unary Minus or Subtracts the second operand
- a-b
subtraction from the first.
* Multiplication a*b Multiplies both operands.
Divides numerator by de-
/ Division a/b
numerator.
return remainder, after an integer
% Modulus a%b
division.

•Integer division truncates any fractional part


•Modulo division produces remainder of an integer division
•The unary minus operator, multiplies its single operand by -1
Computer Centre - Madras Institute of
9/20/2023 55
Technology
Operators – Cont’d
(Arithmetic Operators)
• Integer Arithmetic
– When both the operands in a single arithmetic expression
such as a + b are integers, then the expression is called an
integer expression
– The operation is called integer arithmetic
– Example: If a and b are integers and a=14 & b=4 then,
a – b =10
a / b = 3 (decimal part truncated)
• Real Arithmetic
– An arithmetic operation involving only real operands is called
real arithmetic
– Example: If x, y and z are floats, we have
x = 6.0/7.0 = 0.857143
z = -2.0/3.0 = -0.666667
• The operator % cannot be used with real operands
Computer Centre - Madras Institute of
9/20/2023 56
Technology
Operators – Cont’d
(Arithmetic Operators)
• Mixed-mode Arithmetic:
– When one of the operands is real and the other is
integer, the expression is called a mixed mode
arithmetic expression
– If either operand is of real type, then only the real
operation is performed and the result is always a
real number
• 15/10.0 = 1.5
• 15/10 = 1

Computer Centre - Madras Institute of


9/20/2023 57
Technology
Operators – Cont’d
(Arithmetic Operators - Example)
Output:

Computer Centre - Madras Institute of


9/20/2023 58
Technology
Operators – Cont’d
(Increment and Decrement Operators)
Operator Name of Operator How it is used What it does
a++ (postfix)
++ Increment Operator a=a+1
++a (prefix)
a-- (postfix)
-- Decrement Operator a=a-1
--a (prefix)

 While ++m and m++ mean the same thing when they form statements
independently
 They behave differently when they are used in expressions on the right-hand
side of an assignment statement
m=5;
y=++m;
 The value of y and m would be 6
m=5;
y=m++;
 The value of y would be 5 and m would be 6
 A prefix operator first adds 1 to the operand and then the result is assigned to
the variable on left
 A postfix operator first assigns the value to the variable on left and then
increments the operand
Computer Centre - Madras Institute of
9/20/2023 59
Technology
Operators – Cont’d
(Relational Operators)
• These Operators are used to check the relationship between the two
operands.
– If the relation is true, it returns 1
– if the relation is false, it returns the value 0.
• Relational operators are used in decision-making and loops.

Operator Name of Operator What it does Return value


== Equality Operator checks if a == b Boolean
!= Not equal to checks if a != b Boolean
< Less than checks if a < b Boolean
> Greater than checks if a > b Boolean
<= Less than or equal to checks if a<=b Boolean
>= Greater than or equal to checks if a>=b Boolean

Computer Centre - Madras Institute of


9/20/2023 60
Technology
Operators – Cont’d
(Relational Operators - Example)
Output:

Computer Centre - Madras Institute of


9/20/2023 61
Technology
Operators – Cont’d
(Logical Operators)
• The logical operators are used when we want to check
or test more than one condition and make decisions.
Name of the
Operator What it does How it is used/output
operator
returns true if both side operands
&& logical AND value is true otherwise returns Boolean
false

returns true if one of the


operand's value is true or both of
|| logical OR Boolean
the operand's values is true
otherwise returns false

If the operand is true, it returns


! logical Not false (zero), and if the operand is Boolean
false, it returns true (nonzero).
Computer Centre - Madras Institute of
9/20/2023 62
Technology
Operators – Cont’d
(Logical Operators Example)

Output:

Computer Centre - Madras Institute of


9/20/2023 63
Technology
Operators – Cont’d
(Assignment Operators)
• Assignment Operators are used to assign a new value to a variable
• We can also combine the assignment operation (=) with an arithmetic,
bitwise, or other operation.
Operator Name of Operator How it is used Equivalent to
= assignment a=b a=b

+= plus assign a += b a= a + b

-= minus assign a -= b a=a-b

*= times assign a *= b a = a* b

/= div assign a /= b a =a / b

%= Mod assign a %= b a= a % b
Computer Centre - Madras Institute of
9/20/2023 64
Technology
Operators – Cont’d
(Assignment Operators - Example)

Output:

Computer Centre - Madras Institute of


9/20/2023 65
Technology
Operators – Cont’d
(Bitwise Operators)
• An Bitwise operator is used for the manipulation of
data at the bit level.
• These operators are not applied for the float and
double datatype.
• Bitwise operator first converts the integer into its binary
representation then performs its operation.
• Bitwise operators subsist of two digits, either 0 or 1.

Computer Centre - Madras Institute of


9/20/2023 66
Technology
Binary System
• Before moving on, take a moment to brush up your
knowledge of the binary system, which is essential to
understanding bitwise operators.
• A notable feature of any positional system is its base,
which represents the number of digits available.
• People naturally favor the base-ten numeral system,
also known as the decimal system, because it plays
nicely with counting on fingers.
• Computers, on the other hand, treat data as a bunch of
numbers expressed in the base-two numeral system,
more commonly known as the binary system. Such
numbers are composed of only two digits, zero and one.

Computer Centre - Madras Institute of


9/20/2023 67
Technology
How to Convert Decimal Numbers to
Binary Numbers?
• To convert decimal to binary
numbers, proceed the steps given
below:
LSB  Divide the given decimal number by
“2” where it gives the result along
with the remainder.
 If the given decimal number is even,
then the result will be whole and it
gives the remainder “0”
MSB  If the given decimal number is odd,
then the result is not divided properly
and it gives the remainder “1”.
 By placing all the remainders in order
in such a way, the Least Significant Bit
(LSB) at the top and Most Significant
Bit (MSB) at the bottom, the required
binary number will obtain.

Computer Centre - Madras Institute of


9/20/2023 68
Technology
Few More Examples

(105)10 = (1101001)2
(78)10=(100 1110)2

Computer Centre - Madras Institute of


9/20/2023 69
Technology
How to Convert Binary Numbers to
Decimal Numbers?
• The decimal number is equal to the sum of binary digits (dn)
times their power of 2 (2n):
• decimal = d0×20 + d1×21 + d2×22 + ...

Computer Centre - Madras Institute of


9/20/2023 70
Technology
Few More Examples

Computer Centre - Madras Institute of


9/20/2023 71
Technology
Operators – Cont’d
(Bitwise Operators – Cont’d)
Name of
Operator How it is used What it does
Operator
bitwise AND operator do AND of every corresponding
bitwise
& a&b bits of both operands and output 1 (true) if both
AND
operands have 1 at that position otherwise 0(false).
bitwise OR operator do OR operation of every
corresponding bits of both operands and output 0
| bitwise OR a|b
(false) if both operands have 0 at that position
otherwise 1(true).
bitwise
performs complement operation on an operand and
~ compleme ~a
bitwise complement changes 1 to 0 and 0 to 1
nt
bitwise
returns 1 if the corresponding bits of two operands are
^ exclusive a^b
opposite else 0
OR
<< shift left a << 1 shifts the number of bits to the left side
>> shift right a >> 1 shifts the number of bits to the right side
Computer Centre - Madras Institute of
9/20/2023 72
Technology
(Bitwise Operators – Cont’d)
x y x & y x|y x^y x ~x
0 0 0 0 0 0 1
0 1 0 1 1 1 0
1 0 0 1 1 Ones’ complement of a
number ‘A’ is equal to
1 1 1 1 0
-(A+1).
Bitwise AND Bitwise OR operator Bitwise XOR operator Bitwise not operator
operator Example: Example: Example: Example:

Computer Centre - Madras Institute of


9/20/2023 Technology 73
Bitwise Operators Cont’d
• Bitwise Left Shift Operator
 The bitwise left shift operator (<<) moves the bits of its first
operand to the left by the number of places specified in its second
operand.
 It also takes care of inserting enough zero bits to fill the gap that
arises on the right edge of the new bit pattern
 shifting bits to the left corresponds to multiplying the number by
a power of two, with an exponent equal to the number of places
shifted:

Computer Centre - Madras Institute of


9/20/2023 74
Technology
Bitwise Operators Cont’d
• Bitwise Right Shift Operator
 The bitwise right shift operator (>>) is analogous to the left one, but
instead of moving bits to the left, it pushes them to the right by the
specified number of places.
 The rightmost bits always get dropped
 The right shift operator automatically floors the result.
 It’s virtually the same as a floor division by a power of two:

a= 32 = 0010 0000
a>>1 = 0001 0000 =16
a>>2 = 0000 1000 = 8

Computer Centre - Madras Institute of


9/20/2023 75
Technology
Operators – Cont’d
(Bitwise Operators)

Output:

Computer Centre - Madras Institute of


9/20/2023 76
Technology
Operators – Cont’d
(Ternary or Conditional Operator)
• The conditional operator in C is a ternary operator that is
used to evaluate a boolean expression and return one of
two values depending on whether the expression is true or
false.
• Syntax:
exp1 ? exp2 : exp3
• Here exp1, exp2, exp3 are expressions.
• The Operator ?: works as follows,
– exp1 is evaluated first.
– If it is true, then the expression exp2 is evaluated and becomes
the value of the expression.
– If exp1 is false, then exp3 is evaluated and its value becomes
the value of the expression.

Computer Centre - Madras Institute of


9/20/2023 77
Technology
Operators – Cont’d
(Ternary Operator -Example)

Output:

Computer Centre - Madras Institute of


9/20/2023 78
Technology
Operators – Cont’d
(Miscellaneous Operators)
Name of
Operator How it is used What it does
Operator
if variable a is an integer
It returns the size of
sizeof() sizeof variable the sizeof(a) will
variable
return 4
it converts one datatype
cast type cast int(5.260) would return 5
to another datatype
Used to link the related
, comma operator a = (1,2,3) would return 3
expressions together
returns the address of the
& Address Operator &a
variable.
* pointer operator *a pointer to a variable

Computer Centre - Madras Institute of


9/20/2023 79
Technology
Operators – Cont’d
(Miscellaneous Operators Example)

Output:

Computer Centre - Madras Institute of


9/20/2023 80
Technology
Topic of Discussion
Introduction to programming paradigms
Structure of C program
C programming:
Data Types
Constants
Keywords
Operators
Operator Precedence and Associativity
 Expressions
Input/Output statements
Assignment statements
Decision making statements
Switch statement Computer Centre - Madras Institute of
9/20/2023 81
Technology
Expression
• It is a combination of symbols (or single symbol) that evaluates to a
value
• Expressions, most commonly, consist of a combination of operators and
operands, Example:4 + (3 * k)
• An expression can also consist of a single literal or variable. Thus, 4, 3,
and k are each expressions.
• A subexpression is any expression that is part of a larger expression
• The above expression has two subexpressions, 4 and (3 * k)
• Subexpression (3 * k) itself has two subexpressions, 3 and k.
• Thus, for the expression 4 + (3 * 2), the two operands of the addition
operator are 4 and (3 * 2), and thus the result it equal to 10.
• If the expression were instead written as (4 + 3) * 2, then it would
evaluate to 14.
• Expressions that evaluate to a numeric type are called arithmetic
expressions.
• If no parentheses are used, then an expression is evaluated according to
the rules of operator precedence in C

Computer Centre - Madras Institute of


9/20/2023 82
Technology
Topic of Discussion
Introduction to programming paradigms
Structure of C program
C programming:
Data Types
Constants
Keywords
Operators
Operator Precedence and Associativity
 Expressions
Input/Output statements
Assignment statements
Decision making statements
Switch statement Computer Centre - Madras Institute of
9/20/2023 83
Technology
Operator Precedence
• Consider the expression 4 + (3 * 5) ,It contains two operators, + and *.
• The parentheses denote that (3 * 5) is a subexpression.
• Therefore, 4 and (3 * 5) are the operands of the addition operator, and
thus the overall expression evaluates to 19.
• What if the parentheses were omitted, as given below? 4 + 3 * 5
• How would this be evaluated?
• These are two possibilities,
4 + 3 * 5 ➝ 4 + 15 ➝ 19
4 + 3 * 5 ➝ 7 * 5 ➝ 35
• Some might say that the first version is the correct one by the
conventions of mathematics.
• However, each programming language has its own rules for the order
that operators are applied, called operator precedence, defined in an
operator precedence table.
• This may or may not be the same as in mathematics, although it typically
is.

Computer Centre - Madras Institute of


9/20/2023 84
Technology
Operator Associativity
• What if two operators have the same level of
precedence, which one is applied first?
Associativity helps to determine the order of operations.
Associativity is the order in which an expression is
evaluated that has multiple operators of the same
precedence.
Almost all the operators have left-to-right Associativity.
For example, multiplication and floor division have the
same precedence.
Hence, if both of them are present in an expression, the
left one is evaluated first.
5 * 2 // 33

Computer Centre - Madras Institute of


9/20/2023 85
Technology
Operator Precedence and Associativity
– Cont’d

Computer Centre - Madras Institute of


9/20/2023 86
Technology
Computer Centre - Madras Institute of
9/20/2023 87
Technology
C Tokens
• Tokens in C language are the smallest elements or
the building blocks used to construct a C program.
• C Tokens are of 6 types, and they are classified as:
Identifiers
Keywords
Constants
Operators
Special Characters
Strings

Computer Centre - Madras Institute of


9/20/2023 88
Technology
Topic of Discussion
Introduction to programming paradigms
Structure of C program
C programming:
Data Types
Constants
Keywords
Operators
Operator Precedence and Associativity
 Expressions
Input/Output statements
Assignment statements
Decision making statements
Switch statement
Computer Centre - Madras Institute of
9/20/2023 89
Technology
A simple ‘C’ program
Sample Program

Output: WELCOME TO MIT


• main():
 Execution begins at this line
 It tells the compiler where the program starts
 Every program must have one main function
 Empty pair of parentheses indicates that the function main has no
arguments or parameters
• Function Body:
 The opening brace ‘{‘ indicates the beginning of the function main
and closing brace ‘}’ indicates the end of the function
Computer Centre - Madras Institute of
9/20/2023 90
Technology
A simple ‘C’ program – Cont’d
• Comment Statement:
Line beginning with /* and ending with */ or starting
with // are comment lines
Not an executable statement
Comment line is ignored by the compiler
Comment can be inserted anywhere in the program
• Header file (#include directives)
It is a compiler directive that instructs the compiler to
link the specified functions from the library
#include <stdio.h> refers to standard I/O header file
containing input and output functions
Standard mathematical functions are defined in C math
library
To use mathematical functions in our program we add
#include <math.h> in the program
Computer Centre - Madras Institute of
9/20/2023 91
Technology
A simple ‘C’ program – Cont’d
• printf() function:
 Predefined, standard C function for printing output
(Predefined: function already been written, compiled and
linked together with our program at the time of linking)
 Everything between the starting and the ending quotation
marks will be printed out
 The information contained between the parentheses is called
arguments of the function
• Every statement in C should end with a
semicolon (;)

Computer Centre - Madras Institute of


9/20/2023 92
Technology
Sample Program-2
//Program to add 2 values • Declaration statements:
– All variables in C must be
declared before they are
used and Must appear at
the beginning of the
function
– Here number and amount
are variable names that
Store the numeric data
• number is an integer data
(int abbreviation of
integer) and amount is
Output:
floating (float) number
• Assignment Statements:
100
– Data is stored in a
106.10 variable by assigning a
data value to it

Computer Centre - Madras Institute of


9/20/2023 93
Technology
Sample Program-2 – Cont’d
• Output Statement:
printf(“%d\n”, number);
– The first argument “%d” tells the compiler that the value of
the second argument number should be printed as decimal
integer
– Two arguments are separated by a comma
printf(“%5.2f”, amount);
– “%5.2f” tells the compiler that the output must be in floating
point, with 5 places in all and 2 places to the right of the
decimal point

Computer Centre - Madras Institute of


9/20/2023 94
Technology
//Program to find the area of the circle
Sample Program-3

• Symbolic Constants:
 #define instruction defines value of a symbolic constant
 Symbolic constant values remain constant throughout the execution of
the program
 #define is a compiler directive and not a statement
 #define line should not end with a semicolon
 #define instructions are placed at the beginning before main() function
 Symbolic constants are written in uppercase
 Symbolic constants are not declared in declaration section
Computer Centre - Madras Institute of
9/20/2023 95
Technology
Input and Output Statements
• Input means to feed some data INTO a program
• Output means to display data on the screen or write the data
to a printer or a file.
• C language offers us several built-in functions for performing
input/output operations

*To use printf and scanf, we need


to include the stdio.h header file in
our program
9/20/2023
Computer Centre - Madras Institute of
96
Technology
Input and Output Statements Cont’d
• scanf() :
Formatted I/O Functions
– It is the input function that gets the formatted input from the
file stdin that is the keyboard.
– It reads all types of data values given by the user and these
values are assigned to the variables.
– It requires the conversion specification (such as %s and %d )
to identify the type of data to be read during the program
execution.
– We need to pass the address of the variable to
the scanf function along with other arguments so that the
read values can be assigned to the correct destination.
– Syntax:– scanf(“control string”, &arg);
– Example:
int n, num; float avg;
scanf(“%d”,&n); //read a single integer from the user
Scanf(“%d%f”,&num,&avg) //read a integer and float value from the user
Computer Centre - Madras Institute of
9/20/2023 97
Technology
Input and Output Statements Cont’d
Formatted I/O Functions – Cont’d
• printf():
– It prints all types of data value to the standard
output(typically the screen)
– It requires a conversion symbol and variable name to print
the data.
– This function is used to print a simple text
sentence or value of any variable which can be
of int, char, float, or any other datatype.
– Syntax:–printf(“control string”, arg1, arg2,….,argn);
– Example:
int num=10;float f=56.67;
printf("Welcome"); //Print a sentence
printf("Value of num is: %d", num); //Print an Integer value
printf("\nnum=%d \nf=%f",num,f); //Print an Integer and float
Computer Centre - Madras Institute of
// value
9/20/2023 98
Technology
Input and Output Statements Cont’d
Unformatted I/O Functions
getc() getchar() getch() getche()

getc() getchar() getch() getche()


Reads a character Reads from the Reads a single Reads a character from
from any input and standard input, character from the the keyboard and displays
returns the making it keyboard. It doesn’t it immediately on the
corresponding equivalent to use any buffer, so the output screen, without
integer value on getc(stdin). entered character is waiting for the enter key.
success. If it fails, it returned immediately
returns EOF. without waiting for the
enter key.

conio.h stdio.h conio.h conio.h

•The gets() is used to read string from standard input file stdin
Computer Centre - Madras Institute of
9/20/2023 99
Technology
Input and Output Statements Cont’d
Unformatted I/O Functions –Cont’d
• While calling any of the unformatted console output
functions, we do not have to use any format specifiers in
them, to display a value on the console.
• Hence, these functions are named as unformatted console
output functions.

Computer Centre - Madras Institute of


9/20/2023 100
Technology
Topic of Discussion
Introduction to programming paradigms
Structure of C program
C programming:
Data Types
Constants
Keywords
Operators
Operator Precedence and Associativity
 Expressions
Input/Output statements
Assignment statements
Decision making statements
Switch statement
Computer Centre - Madras Institute of
9/20/2023 101
Technology
Structure of C program
DOCUMENTATION SECTION
LINK / PREPROCESSOR SECTION
DEFINITION SECTION

GLOBAL DECLARATION SECTION

main() function Section


{
Declaration part;
Executable Part;
}
sub program section (user defined functions)
{
Body of the subprogram;
}
Computer Centre - Madras Institute of
9/20/2023 102
Technology
Structure of C program – Cont’d
• C program can be viewed as a group of building
blocks called functions
• A function is a subroutine that may include one or
more statements designed to perform a specific
task
• To write a C program, we create functions and them
put them together
• Documentation Section:
– Consists of a set of comments lines giving the name of the
program, the author and other details for programmer for later
use.
• Link Section:
– Provides instructions to the compiler to link functions from the
system library
• Definition Section:
– Defines all symbolic constants
Computer Centre - Madras Institute of
9/20/2023 103
Technology
Structure of C program – Cont’d
• Global Declaration Section:
– Some variables are used in more than one functions and such
variables are called as global variables
• main() function section:
– Has 2 parts
• Declaration part - Declaration part declares all variables used in
executable part
• Executable part - Executable part contains at least one statement
• Subprogram section:
– Contains all user defined functions that can be called in the
main functions
– Placed immediately after main function

• All section, except main function are optional


Computer Centre - Madras Institute of
9/20/2023 104
Technology
Structure of C program - Sample

Computer Centre - Madras Institute of


9/20/2023 105
Technology
Programming Rules
• C makes distinction between uppercase and lowercase:
– In C, everything is written in lowercase letters.
– Uppercase letters are only used for symbolic constants
• Blank spaces may be inserted between the words. This improves the
readability of the statements. However, it is not used while declaring a
variable, keyword, constant and function
• Free-Form Language:
– It is not necessary to fix the position of statement in the program, i.e., the
programmer can write the statement anywhere between the two braces
following the declaration part.
– The user can also write one or more statements in one line separating
them with a semicolon(;)

• The opening and closing braces should be balanced, for example, if opening
braces are four, then closing braces should also be four
Computer Centre - Madras Institute of
9/20/2023 106
Technology
Translators and their needs in
Programming Languages
• User’s give instructions in C program code (high level
language) which is also called as source code.
• But the computer ‘s wont understand the source code
• Computer’s only understandable code is binary / machine.
• To convert this source code into binary code we are using the
interface software called translators.
• Translators are system software that converts programming
language code into binary format.
• The translators are classified into three types:
– Compiler
– Interpreter
– Assembler

Computer Centre - Madras Institute of


9/20/2023 107
Technology
Translators and their needs in
Programming Languages
Compiler • Compiler and interpreter are
both used to convert high-level
programs to machine code.
• Assembler is used to convert
interpreter
low-level programs (assembly
language code) to machine
code.
• A loader is a program that loads
the machine codes of a
Assembler program into system memory.
• A linker is a program that links
smaller programs to form a
single program. The linker links
the machine codes of the
program.
Computer Centre - Madras Institute of
9/20/2023 108
Technology
Executing a ‘C’ Program

• Steps involved in executing C program,


1. Creating the program
2. Compiling the program
3. Linking the program with functions that are
needed from the C library
4. Executing the program

Computer Centre - Madras Institute of


9/20/2023 109
Technology
Steps for entering, compiling, and executing C program

Computer Centre - Madras Institute of


9/20/2023 110
Technology
Executing a ‘C’ Program – Cont’d
• Creation of program:
– Programs should be written in C editor.
– File extension is .c
• Compilation:
– The source program statements should be translated into object programs
which is suitable for execution by the computer.
– The translation is done after correcting each statement.
– If there is no error, compilation proceeds and translated program are stored
in another file with the same filename with extension “.obj”.
– If any errors are there the programmer should correct them.
• Linking:
– The object code of the function should be brought from the library of the
system and linked to the main() program.
– Example: program using pow() function, the object code of this function is
brought from math.h library of the system and linked to the main() program
• Executing the program:
– After the compilation the executable object code will be loaded in the
computer’s main memory and the program is executed
Computer Centre - Madras Institute of
9/20/2023 111
Technology
Executing a ‘C’ Program – Cont’d
(In UNIX OS)
• Creating the file
– Text editor is used, either ed or vi
• vi filename.c
– The program must be entered in a file
– File name consists of letters, digits and special characters, followed by a dot and a
letter c
• Example : Hello.c
– File is known as source program
• Compiling and Linking
– Compilation command is cc filename.c, Example :Hello.c
– The program is translated into another file with name Hello.o.
– This program is called object code
– Linking is the process of putting together other program files and functions that
are required by the program
• Compiled and linked program is called the executable object code and is
stored automatically in another file named a.out
• Executing the Program
– The command is a.out
Computer Centre - Madras Institute of
9/20/2023 112
Technology
Topic of Discussion
Introduction to programming paradigms
Structure of C program
C programming:
Data Types
Constants
Keywords
Operators
Operator Precedence and Associativity
 Expressions
Input/Output statements
Assignment statements
Decision making statements
Switch statement
Computer Centre - Madras Institute of
9/20/2023 113
Technology
Control statements
• Control flow is the order that instructions are executed in a program.
• A control statement is a statement that determines the control flow of a set
of instructions.
• There are three fundamental forms of control that programming languages
provide
 sequential control
 selection control
 iterative control

Sequential control is an implicit form of control in which instructions are executed
in the order that they are written. A program consisting of only sequential control is
referred to as a “straight-line program.”
Selection control is provided by a control statement that selectively executes instructions
Iterative control is provided by an iterative control statement that repeatedly
executes instructions
Computer Centre - Madras Institute of
9/20/2023 114
Technology
Control Statements –Cont’d

UNIT 1 UNIT 2

Computer Centre - Madras Institute of


9/20/2023 115
Technology
Decision making statements
(if statement)
• In C, if statement is used for decision making .
• It will test a condition and based on the validity of
the condition, control flow will be transferred.
• There are four types of If statement they are:
if statement
if-else statement
if-else if ladder
nested if statement
• switch statement is used for executing one
statement from multiple conditions and it is similar
to an if-else ladder.

Computer Centre - Madras Institute of


9/20/2023 116
Technology
Decision making statements -Cont’d
if Statement (if statement – Cont’d)
The if statement is a single conditional based statement that executes only if the
provided condition is true.
Syntax:
if(condition)
{
//code
}

if-else Statement
•The if-else statement is used for testing Syntax:
condition. If the condition is true, if block if(condition)
executes otherwise else block executes. {
//code for true
•It is useful in the scenario when we want to
}
perform some operation based on the false else
result. {
•The else block execute only when condition is //code for false
false. }
Computer Centre - Madras Institute of
9/20/2023 117
Technology
If Example

Output 1:

Output 2:

Computer Centre - Madras Institute of


9/20/2023 118
Technology
If else Example
//Program to check whether the given number is even or odd

Output 1:

Output 2:

Computer Centre - Madras Institute of


9/20/2023 119
Technology
Decision making statements -Cont’d
(if statement – Cont’d)
Syntax:
if(condition1) if-else if ladder Statement
{ •When we have multiple conditions to
//code for if condition1 is true execute then it is recommend to use if-
} else-if ladder.
else if(condition2) •It contains multiple conditions and
{ execute if any condition is true
//code for if condition2 is true otherwise executes else block.
}
else if(condition3)
{
//code for if condition3 is true
}
...
else
{
//code for all the false conditions
} 9/20/2023 Computer Centre - Madras Institute of
120
Technology
if-else if ladder Example
//Program to check whether the given number is +Ve, -Ve or Zero

Output 1:

Output 2:

Output 3:

Computer Centre - Madras Institute of


9/20/2023 121
Technology
Decision making statements -Cont’d
(if statement – Cont’d)
Nested if statement
In this, one if block is created inside another if block when the
outer block is true then only the inner block is executed.
Syntax:
if(condition)
{
//statement
if(condition)
{
//statement
}
}

Computer Centre - Madras Institute of


9/20/2023 122
Technology
Nested if statement -Example
//Program to check whether the given number is +Ve, -Ve or Zero

Output 1:

Output 2:

Output 3:

Computer Centre - Madras Institute of


9/20/2023 123
Technology
Topic of Discussion
Introduction to programming paradigms
Structure of C program
C programming:
Data Types
Constants
Keywords
Operators
Operator Precedence and Associativity
 Expressions
Input/Output statements
Assignment statements
Decision making statements
Switch statement
Computer Centre - Madras Institute of
9/20/2023 124
Technology
Decision making statements -Cont’d
Syntax:
(switch statement )
switch(expression)
{ •The switch statement is used for
case value1: executing one statement from
//code for execution; multiple conditions.
break; //optional •It is similar to an if-else-if ladder
case value2:
// code for execution
•We cannot use logical operators
break; //optional in Switch statement.
...... •Even we cannot use the float data
...... type.
case value n: •Switch only supports integer and
// code for execution
break; //optional
characters..

default:
code for execution when none of the case is true;
} 9/20/2023
Computer Centre - Madras Institute of
125
Technology
//Program to check whether the entered character is vowel or not

Output 1:

Output 2:

Output 3:

Computer Centre - Madras Institute of


9/20/2023 126
Technology
//Program to check whether the entered character is vowel or not

Output 1:

Output 2:

Output 3:

Computer Centre - Madras Institute of


9/20/2023 127
Technology

You might also like