Unit 1
Unit 1
Unit 1
Basics of C Programming
MS.A.MAHALAKSHMI, AP/IT
Karpagam Institute of Technology
1
Unit I: Syllabus
Introduction to programming paradigms – Structure of C program –
2
Computer Programming
• Computer Programming is a set of instructions to perform a
particular task
• A computer program is usually written by a computer programmer
in a programming language.
• It is somewhat similar to the one person gives commands /
instructions / orders to other in order to carried out a specific
work/task.
• Example: Rice Cooking
• “Does this, then do that, then take the two results, mix them up
this way, and repeat until you get a rice out of it…”
3
Computer Programming
Example: Rice Cooking step by step instructions
4
Computer Programming
Example: Addition of two numbers
Step 1: Read two numbers A=10 & B=20 //instruction 1
Step 2: Add A, B and assign result to C //instruction 2
C=A+B
5
Programming Languages
• For people to people communication natural language is used
similarly if human want to communicate with computer then he
communicates with the help of programming languages.
Through Programming
Through Natural Language
Language
6
Programming Languages
Programming Languages
• Programming languages enable human to interact with
machines.
• The Programmer provide the computer a set of instructions that
are written in a language that the computer can understand.
• It is used for developing computer programs, which enable a
computer to perform some operations.
• The structure of these languages is based on some syntactic and
semantic rules.
• Example: C, C++, Java, Python, PHP, etc.,
7
Programming Languages
• Programming Languages are based on certain syntactic and
Types
12
Programming Languages
High Level Languages
• High Level Languages was developed to overcome some of the
inconveniences of low level language.
• It is consist of English like statements and mathematical symbols.
• High level language provides higher level of abstraction from
machine language.
• They do not interact directly with the hardware. Rather, they focus
more on the complex arithmetic operations, optimal program
efficiency and easiness in coding.
• Example: Pascal, C, C++, Java, Python , etc.,
13
Programming Languages
High Level Languages
Advantages
• It provide higher level of abstraction from machine languages.
• It is machine independent language.
• Easy to learn.
• Less error prone, easy to find and debug errors.
Disadvantages
• It takes additional translation times to translate the source to
machine code.
• High level programs are comparatively slower than low level
programs.
• Compared to low level programs, they are generally less memory
efficient.
• Cannot communicate directly with the hardware.
14
Programming Paradigm: Overview
• A Programming paradigm is a style, or “way,” of programming.
• A programming paradigm defines the methodology of
designing and implementing programs using the key features
and building blocks of a programming language.
15
Programming Paradigm: Overview
The two primary types of Programming Paradigm are as
follows:
• Unstructured Programming
– It generally executes in sequential order
– Code is repeated through out the program
• Structured Programming or Procedural Oriented
Programming
– Has non-sequentially flow of control.
– Use of functions allows for re-use of code.
16
Programming Paradigm: Overview
Unstructured Programming
• The program consists of only one section i.e.., main
Advantages
• Simple and easy to practice by novice programmer
• Good for small program; no lengthy planning needed.
17
Programming Paradigm: Overview
Unstructured Programming
Disadvantages
• Repetition of code
• If the same statement sequence is needed at the different
locations within the program, the sequence must be copied.
• Cumbersome Maintenance
• When a certain statement is changed, all subsequent affected
statements must be adjusted accordingly.
18
Programming Paradigm: Overview
Procedural or Structured programming
• This programming paradigm aimed at improving the clarity,
quality, and development time of a computer program by making
extensive use of the structured control flow constructs of selection
(if/then/else) and repetition (while and for), block structures,
and subroutines.
• In Procedural Programming, the problem is divided into number
of small problems known as procedures.
• Each of these procedures provide solution to part of the problem.
19
Programming Paradigm: Overview
Procedural or Structured programming
• Use top down approach (General to Specific)
– In top-down approach the total system is divided into number of
sub systems and those sub systems are again divided into number
of other sub systems. It goes until the base level elements are
defined properly.
20
Programming Paradigm: Overview
Procedural or Structured programming
Advantages
• Complexity can be reduced using the concepts of divide and
conquer.
• Logical structures ensure clear flow of control.
• Increase in productivity by allowing multiple programmers to
work on different parts of the project independently at the same
time.
• Modules can be re-used many times, thus it saves time, reduces
complexity and increase reliability.
• Easier to update/fix the program by replacing individual modules
rather than larger amount of code. 21
Quiz
1) What is the only thing that computers understand?
Answer : Option a)
2) Before a computer can understand a program it must be
Answer : Option d) 22
Quiz
3) A list of instructions that enable a computer to perform a
specific task is a
a) Machine code b) Computer Program
Answer : Option b)
23
Quiz
4) A language that requires no knowledge of the hardware or the
instruction set of the computer is called.
a) Machine code b) Low Level Language
Answer : Option c)
24
Quiz
5) Which of the following is not a high level programming
language?
a) Assembly b) C
c) Java d) Python
Answer : Option a)
25
Quiz
6) What is the name for the software used to convert an assembly
language program into machine code?
a) Assembler b) Interpreter
c) Compiler d) Converter
Answer : Option a)
26
C Programming : Introduction
• C is a general purpose, High level and Structured
Programming Language.
• General Purpose: C Program has ability to create any type of
applications.
• High Level: it means that the syntax of the code is easier to
interpret by humans. Namely, if you have to display something
on the screen, the built-in function is called print.
• Structured Programming Language: The whole program is
divided into small modules so that the program becomes easy to
understand.
27
C Programming : History
• C programming language was developed in 1972 by Dennis
Ritchie at bell laboratories of AT&T (American Telephone &
Telegraph), located in the U.S.A.
• C Programming was created from 'ALGOL', 'BCPL' and 'B'
programming languages. 'C' programming language contains all
the features of these languages and many more additional
concepts that make it unique from other languages.
28
C Programming : History
First Structured Programming
developed by International group
Algorithmic Language
Basic Combined
Programming Language
31
Why to learn C Programming in 2021?
• In IIT’s, NIT’s and any other reputed institutions, the prime
language thought was C programming Language because it is the
mother language for all other modern programming languages.
• Example:
− IIT Madras http://www.cse.iitm.ac.in/pages.php?pages=MzA=
− NIT, Trichy https://
www.nitt.edu/home/academics/departments /cse/programmes/
btech/curriculum/
32
Why to learn C Programming in 2021?
• C is used to build core logics in algorithms and business layers.
• C programming language plays a vital role in technical rounds of
top MNC companies(Amazon, IBM, Intel, AMD, Yahoo, Google
etc..) hiring process.
• Almost every top MNC’s still hiring C programmers because
what ever the software you are using is coded in C as its base.
• Once you are good in C Programming, then you can easily adopt
any programming languages and software development
process.
33
Why to learn C Programming in 2021?
• Most of the popular software was implemented using C
programming Language
C Coding
Programming Languages
Databases
34
Gaming Applications
Features of C Programming
• The Features of C Programming are:
35
Features of C Programming
• Simple - C is a simple language in the sense that it provides
structured approach (to break the problem into parts), rich set
of library functions, data types etc.
• Machine Independent or Portable - Unlike assembly language,
c programs can be executed on many machines with a little bit
or no change. But it is not platform-independent.
• Mid-level programming language –C supports both high level
and low level language features. It means, it is used to develop
both system oriented softwares (kernel, drivers) and application
oriented softwares (gaming applications, web applications).
36
Features of C Programming
• Structured programming language - C is a structured
programming language in the sense that we can break the
program into parts using functions. So, it is easy to understand
and modify.
• Rich Library - C provides a lot of inbuilt functions that make
the development fast.
• Memory Management - It supports the feature of dynamic
memory allocation. In C language, we can free the allocated
memory at any time.
37
Features of C Programming
• Speed - The compilation and execution time of C language is
fast.
• Pointer - Programmer can directly interact with the memory by
using the pointers.
• Recursion - In c, we can call the function within the function. It
provides code reusability for every function.
• Extensible - C language is extensible because it can easily adopt
new features.
38
Environmental Setup
• There are lots of C compiler available like GCC, MinGW, Tiny
C compiler, MS DOS (Turbo C++) etc..
• Lets learn C Programming using MS DOS( Turbo C++)
compiler.
• Install C (Turbo C++) in stand alone computer by downloading
the file from the following link.
− https
://developerinsider.co/download-turbo-c-for-windows-7-8-8-1-and-
windows-10-32-64-bit-full-screen
/
• For online environment
− https://www.onlinegdb.com/online_c_compiler
39
Environmental Setup
Steps for installing Turbo C in Windows:
• Download Turbo C software from
https://developerinsider.co/download-turbo-c-for-windows-7-8-8-1-and
-windows-10-32-64-bit-full-screen/
40
How to run a simple C Program??
Running C Program in windows:
• After successful installation, turbo C++ software shortcut will be
available in your desktop, open it.
• Select File > New and then write your C program.
41
How to run a simple C Program??
• Save the program using F2 (OR File > Save), remember the
extension should be “.c”. For Example: helloworld.c
42
How to run a simple C Program??
• Compile the program using Alt + F9 or Compile > Compile
43
How to run a simple C Program??
• Alt+F5 to view the output of the program at the output screen.
44
How to run a simple C Program??
Running C Program in Ubuntu Linux using gcc compiler :
• After completion, save your program with .c extension. For
Example: hello.c
• Open terminal to compile and run your C program.
45
How to run a simple C Program??
Running C Program in Ubuntu Linux using gcc compiler :
46
Comments in C
• A comment is an explanation or description of the source code
of the program.
• It helps a developer explain logic of the code and improves
program readability.
• At run-time, a comment is ignored by the compiler.
• Types of comments
47
Comments in C
• Single-line Comments which uses a double slash //
dedicated to comment single lines
• Example:
// My First C Program
#include <stdio.h>
int main()
{
// This is a single line comment
printf(“My first C Program");
return 0; // return zero
}
48
Comments in C
• A Multi-line comment that starts with a slash asterisk /* and
finishes with an asterisk slash */ and you can place it anywhere
in your code, on the same line or several lines.
• Example:
/* *File Name: sample.c
* Author: Manthan Naik
* description: a program to display the
inputed integer
*/
#include <stdio.h>
int main() {
/* This is body of the main function which
collects a
integer value from user and displays the
collected integer value*/
int x = 42; //x is a integer variable
printf("%d", x);
return 0;} 49
Structure of C Program
50
Structure of C Programming
Documentation Section:
• The documentation section consists of a set of comment lines
giving the name of the program, the author, and other details,
which the programmer would like to use later.
• The documentation section is the part of the program where the
programmer gives the details associated with the program.
Example:
/**
* File Name: Helloworld.c
* Author: Manthan Naik
* date: 09/08/2019
* description: a program to display hello world
no input needed 51
Structure of C Programming
Link Section
• This part of the code is used to declare all the header files that
will be used in the program.
• This leads to the compiler being told to link the header files to
the system libraries.
• Example : #include<stdio.h>
Header Files:
• A header file is a file with .h extension which contains C
declarations and macro definitions to be shared between
several source files. User can include header file in his program
with the help of preprocessor directive #include.
52
• For Example: #include<math.h>, #include<string.h> etc..
Structure of C Programming
Definition Section
• In this section, we define different constants. The keyword define is
used in this part. Example: #define PI=3.14
Global Declaration Section
• This part of the code is the part where the global variables are declared.
• The scope and lifetime of global variable is throughout the program.
• Example:
Main
Function
Sub Function1 Sub Function 4
add() divide()
55
Structure of C Programming: Example
/* This program is to add two numbers*/
//documentation Section
#include<stdio.h> // Link Section
#define a 10
int b=20; // Global Declaration Section
void main() // Main Function
{
int c; // declaration part
c=sum(a,b);
printf("the sum of two numbers:%d",c);
}
int sum(int d,int e) // Sub Program
Section
{
return d+e;
Output:
}
the sum of two numbers: 30
the sum of two numbers: 30 56
Compilation process in C
• The compilation is a process of converting the source code into
object code.
• It is done with the help of the compiler.
• The compiler checks the source code for the syntactical or
structural errors, and if the source code is error-free, then it
generates the object code.
57
Compilation process in C
58
Compilation process in C
Preprocessor:
• The preprocessor takes the source code as an input, and it
removes all the comments from the source code.
• It expands macro and included header files.
• The result is another file typically with .i suffix.
cpp hello.c > hello.i
C Pre Processor
• hello.i contains the source code with all macros expanded.
• Live Demo
59
Compilation process in C
Compiler:
• The C compiler converts the pre-processed code into assembly
code for a specific processor.
• The compiler translates hello.i (output from Preprocessor) to
hello.s. It contains assembly code.
gcc –S hello.i
• -S – is a command line option tell the compiler to convert the
preprocessed code to assembly language without creating an
object file
60
Compilation process in C
Assembler:
• The assembly code is converted into partial object code by
using an assembler.
• The Assembler (as) translates hello.s into machine language
instructions and generates object file hello.o.
• The name of the object file generated by the assembler is the
same as the source file.
• Assembler is invoked by executing the following command
as hello.s –o hello.o
61
Compilation process in C
Linker:
• The main working of the linker is to combine the object code of
library files with the object code of our program.
• The output of the linker is the executable file.
• An executable file requires many external resources (system
functions, C run-time libraries etc ).
• In our program there is a printf() function to print hello world in
the console.
• So the object file of the printf (built-in function) is combined
with the partial object file created (hello.o)
62
Compilation process in C
Linker:
• This is done with the help of ld linker command
• The ld command, also called the linkage editor or binder,
combines object files, archives, and import files into one output
object file, resolving external references.
• It produces an executable object file that can be run.
• By default, the ld command creates and places its output in the
a.out file.
• Final executable file : gcc hello.o
• To run final executable file : ./a.out
• The path ./ refers to current directory, so ./a.out loads and
runs the default executable file’ a.out’ in the current directory.
63
C Introduction : Character Set
• Set of Characters used in writing any C program is called C
‘character set’
• In C language both the small and capital letters are treated as
separate characters because C is Case Sensitive language.
64
C Tokens
• The smallest individual unit in a program is known as a Token.
• C has the following tokens:
65
C Tokens : Keywords
• Keywords are predefined, reserved words in C language and
each of which is associated with specific features.
• They have special meaning to the compiler.
• There are 32 keywords based on ANSI C Standards.
66
C Tokens : Keywords
• Keywords added by C99 are
Bool
Complex
Imaginary
inline
restrict
• Keywords added by C11 are
Alignas
Alignof
Atomic
Genric
Noreturn
Static_assert
Thread_local 67
C Tokens : Identifiers
• Identifiers are names of entities in a C program, such as
variables, arrays, functions, structures, unions, and labels
• An identifier is a string of alphanumeric characters.
• C Programming is case sensitive as it traits upper and lower case
characters differently.
• Rules for naming an identifier:
− Can have letters, digits or underscores
− First character must be a letter or an underscore but can’t
be a digit
− No special character except underscore can be used
− Keywords or reserved words cannot be a identifier name.68
C Tokens : Identifiers
Example:
Valid Description In-Valid Description
Identifiers Identifiers
• rollNo A valid identifier is a • roll No It should be only one
• NewDelhi single sequence of • New Delhi word consisting of one
characters. or more characters
• roll4No It should start with a • 4rollNo It should not start with a
• _rollNo letter or underscore(_) • $rollno digit or symbols
69
C Tokens : Identifiers
Variables:
• Variables are nothing but reserved memory locations to store
values.
Syntax: int a=10;
Declaration
• This is the process of allocating sufficient memory space for
the data in term of variable .
• Syntax: data_type variable_name ;
70
• Example: int a;
C Tokens : Identifiers
Initialization
• Assigning initial values to the variable during variable
declaration.
• If no input values are assigned by the user than system will gives
a default value called garbage value.
• Example: int a = 100;
Assignment
• It is a process of assigning a value to a variable after declaration.
• Example:
int a= 20; //initialization
int b; // declaration
b = 25; // --> direct assigned variable
71
b = a; // --> assigned value in term of variable
C Tokens : Literals
• Literals (often referred to as constants) are data items that never
change their value during a program run.
Types of literals
• There are four types of literals that exist in C programming:
72
C Tokens : Literals
Integer Literal:
• It is a numeric literal that represents only integer type values. It
represents the value neither in fractional nor exponential part.
• It can be specified either in decimal, octal or hexadecimal
number.
Decimal number (base 10)
• It is defined by representing the digits between 0 to 9.
• Example: 45, 67, etc.
Octal number (base 8)
• It is defined as a number in which 0 is followed by digits such as
0,1,2,3,4,5,6,7.
• Example: 012, 034, 055, etc. 73
C Tokens : Literals
• Hexadecimal number (base 16)
• It is defined as a number in which 0x or 0X is followed by the
hexadecimal digits (i.e., digits from 0 to 9, alphabetical characters
from (a-z) or (A-Z)).
• Example: 0x3b24, 0xf96,0X21, etc.
Floating Point Literal
• These are used to represent real numbers. The real number has
an integer part, a decimal point, a fractional part, and an
exponent part.
• Floating point literals are represented either in decimal form or
in exponential form.
74
C Tokens : Literals
Decimal form
• While representing decimal form, you must include the integer part,
decimal point, and fractional part.
• The decimal notation can be prefixed either by '+‘ (by default) or '-'
symbol that specifies the positive and negative numbers.
• Example: 1.2, +9.0, -4.5, 3.14159, etc.
Exponential Form
• The exponential form is useful when we want to represent the
number, which is having a big magnitude.
• It contains two parts, i.e., mantissa and exponent.
75
C Tokens : Literals
Rules for creating an exponential notation
• In exponential notation, the mantissa can be specified either in
decimal or fractional form.
• An exponent can be written in both uppercase and lowercase,
i.e., e and E.
• We can use both the signs, i.e., positive and negative, before
the mantissa and exponent.
• Spaces are not allowed.
− Example, the number is 2340000000000, and it can be
expressed as 2.34e10 in an exponential form.
76
C Tokens : Literals
Character Literals
• A character literal contains a single character enclosed within
single quotes. Example: ‘a’.
Representation of character literal
• We can specify the escape sequence character within single
quotes to represent a character literal. Example, '\n', '\a', '\b'.
• We can also use the ASCII in integer to represent a character
literal. Example, the ascii value of ‘A’ is 65.
• The octal and hexadecimal notation can be used as an escape
sequence to represent a character literal. Example, '\023', '\0x12'.
77
C Tokens : Literals
Escape Sequence:
• An escape sequence is a sequence of characters that does not
represent itself when used inside a character or string literal,
but is translated into another character or
a sequence of characters that may be difficult or impossible to
represent directly.
Escape Meaning
Sequence
\b Backspace
\n New Line
\t Tab (Horizontal)
\\ Backslash
\0 Null
78
C Tokens : Literals
String Literals
• A string literal represents multiple characters enclosed within
double-quotes.
• It contains an additional character, i.e., '\0' (null character),
which gets automatically inserted. “welcome \0”
• This null character specifies the termination of the string.
• Example:
– String1= “hello"; “hello@123.com”;
– String2= “world123";
79
C Tokens : Literals
Defining Constants
• There are two simple ways in C to define constants −
− Using #define preprocessor.
− Using const keyword.
Using #define preprocessor:
• The #define preprocessor directive is used to define constant or
micro substitution.
• Example: #define PI=3.14
Using const keyword:
• The constant variables can be initialized once only.
• The default value of constant variables are zero
• Example: const int a=10;
80
C Data Types
• Data types define the type of data a variable can hold, for
example an integer variable can hold integer data.
• Every value in C Programming has a data type.
81
C Data Types
• Primitive Data type: It is a fundamental data type that cannot
be broken down into a more simple data type. Example int, float,
char are primitive data type.
• Derived Data type: A derived type is formed by using one or
more primitive types in combination. Using derived types, an
infinite variety of new types can be formed. Example: arrays,
functions, pointers.
• User Defined Data type: A user-defined data type (UDT) is a
data type that derived from an existing data type. Example:
structure, Union, enum
82
C Data Types
• Example:
83
C Data Types
• Type Modifiers: These are keywords in C to modify the default
properties of data types. There are 4 modifiers in C as follows.
84
C Data Types
• An integer literal is suffixed by following two qualifiers:
– L or l: It is a size qualifier that specifies the size of the
integer type as long.
– U or u: It is a sign qualifier that represents the type of the
integer as unsigned. An unsigned qualifier contains only
positive values.
– For example:215u, 032u,30ul,0xFeeL, etc
85
C Data Types
86
C Token -Exercise
Exercise 1
90
C Tokens - Operators
• Operator is a symbol that tells the computer to perform some action
on constants and variables called operands
• The operator that uses a single operand is called an Unary
operator(+,-,++,--)
• The operator that uses two operands is known as binary
operator(+,-,*,/,<,>) and,
• The operator that uses three operands is known as ternary
operator( (a>b)?a:b).
91
C Tokens - Operators
Types of Operators
• C operators can be classified into number of categories.
– Arithmetic operators
– Relational operators
– Logical operators
– Assignment operators
– Increment And Decrement operators
– Conditional operators
– Bitwise operators
– Special operators 92
Operators – Arithmetic operators
Arithmetic Operators:
• Used to perform common mathematical operations like addition,
subtraction, etc between two operands.
• Input: Numerical values (either literals or variables)
• Output: Numerical value (single)
Let's assume, 'a' is 8 and 'b' is 4
Operator Description Example Category
+ Adds operands a+b=12 Unary / Binary
- Subtracts second operand from the a-b=4 Unary / Binary
first
* Multiplies both operands a*b=32 Binary
/ Divides numerator by denominator. a/b=2 Binary
% Modulus Operator returns the a%b=0 Binary
remainder after an integer division. 93
Operators – Arithmetic operators
• These can operate in any built-in data type allowed in C
• Integer Division truncates any fractional part (i.e. it produces the
quotient)
• The modulo division operation produces the remainder of an integer
division.
• Example:
Note:
• For modulo(%) operator
– If we apply two integers, the result will be a remainder.
5%2=1 2%5 = 2 [If Numerator is smaller]
– To get signature in output, modulo takes sign of numerator
-5%2=-1 or 5%-2= 1 or -5%-2=-1
*Modulo will not take floating-point value as an input operand*
95
Operators – Arithmetic operators
Real Arithmetic:
• An arithmetic operation involving only real operands is called real
arithmetic.
• Example:
x=6.0/7.0 = 0.857143
15/10.0 = 1.5 96
Operators – Arithmetic operators
Character Arithmetic
• Here both the operand is character.
• Example:
ch1=’A’
ch2=‘a’
x=ch1+ch2
97
Operators – Relational operators
Relational Operators:
• Relational operators are used to compare two values.
• Tests numerical equalities and inequalities between two operands.
• Input: Numerical values (either literals or variables)
• Output: Boolean value(either true[1] or false[0])
Output:
1 99
Operators –Logical operators
Logical Operators:
• Logical operators are used to combine conditional statements and
returns Boolean value.
• Input: Boolean value(either directly through condition or value]
• Output: Boolean value(either true[1] or false[0])
101
Operators –Logical operators
• Example:
int a = 0;
int a=5,b=-1,c=0; int a=5; printf(“%d”, !a);
printf(“%d”, (a>b)||(c=5); printf(“%d”, !a); a=!a;
printf(“%d”,c); printf(“%d”,a); printf(“%d”, a);
104
Operators –Bitwise operators
• Example:
5 00000101 5 00000101
105
Operators –Bitwise operators
• Example:
>>2 0 0 0 0 0 0 0 1 0 1
Filled bits
108
Operators –Bitwise operators
• Example: Right shift – (signed)
-20>>2
20 00010100
11101011 (1’s complement)
1 (2’s complement) steps to calculate -20
-20 1 1 1 0 1 1 0 0
Vacated bits
-20>>2 0 0 1 1 1 0 1 1 0 0
Filled bits
i.e. -20>>2 00111011
109
Operators –Bitwise operators
• Example:
Left shift
The left operands value is moved left by the number of bits specified
by the right operand.
5<<2
0 0 0 0 0 1 0 1 Filled bits
5
>>2 0 0 0 0 0 0 0 1 0 0
Vacated bits
110
Operators –Bitwise operators
• Example: Left Shift (signed)
-70<<1
70 01000110
10111001 (1’s complement of 70) steps to calculate -70
Vacated bits
115
Operators –Increment & Decrement
operators
Increment and Decrement Operators
• Both increment and decrement operators are special unary
operators variable in C.
• Increment operator is denoted as ++ and decrement operator is
denoted as --.
• The operator++ adds 1 to the operand while -- subtracts 1 from the
operand.
Rules:
• The operand must be a variable, but not a constant or an
expression.
116
Operators –Increment & Decrement
operators
Pre-Increment and Pre-Decrement Operators
• Here the operator ++ precedes the operand, the operand is
incremented by 1 before it is used.
• Example:
main()
Consider a=10 {
b=++a int a=10;
a int b=++a;
10 printf(“%d”,b);
++
}
a b
11 11
Output:
11
117
Operators –Increment & Decrement
operators
Pre-Increment and Pre-Decrement Operators
Pre – Decrement Operator
• Here the operator -- precedes the operand, the operand is
decremented by 1 before it is used.
main()
• Example: {
Consider a=10 int a=10;
int b=--a;
b=--a printf(“%d”,b);
a
}
10
--
Output:
a b
10
9 9
118
operators
Post-Increment and Post-Decrement Operators
Post – Increment Operator
• Here the operator ++ follows the operand, the operand is
incremented by 1 after it is used. main()
• Example: {
int a=10;
Consider a=10 int b=a++;
b=a++ printf(“%d”,b);
a
b=a;
10
printf(“%d”,b);
a }
a b
++ Output:
10 11 10
11 119
operators
Post-Increment and Post-Decrement Operators
Post – Decrement Operator
• Here the operator -- follows the operand, the operand is
decremented by 1 after it is used. main()
• Example: {
int a=10;
Consider a=10 int b=a--;
b=a-- printf(“%d”,b);
a
b=a;
10
printf(“%d”,b);
a }
a b
-- Output:
10 9 10
9 120
Operators –Conditional Operators
Conditional Operator
• The ternary operator ?: is used to form a conditional expression.
• It uses three operands and hence it is called as a ternary operator.
Syntax:
121
Operators –Conditional Operators
• A conditional expression is evaluated as follows
– the expression 1 is evaluated to find the logical value true or
false.
– if the expression 1 is true, then the expression 2 is evaluated.
122
Operators –Special Operators
Special Operators
Operator Description
sizeof( ) used to compute the size of its
operand
& returns the address of the
variable
* Pointer
. direct member selection via
object name
, the value of the right most
expression is the value of the
combined expression.
used to refer to members of
structures, unions.
123
Operators –Special Operators
• Example:
124
C Operators -Exercise
Exercise 2
125
C Operators -Exercise
Exercise 2
127
C Operators -Exercise
Exercise 2
128
C Operators -Exercise
Exercise 2
129
Expression
• Any valid combination of constants, variables and operators
constitute an expression.
• Example: x2-3xy+2y2
130
Expression
Evaluation of Expressions
• Expressions are evaluated using an assignment statement of the
form.
• Syntax: Variable = expression;
131
Expression
Rules for evaluation of expression
• First parenthesized sub expression left to right are evaluated.
• If parenthesis are nested, the evaluation begins with the innermost
sub expression.
• The precedence rule is applied in determining the order of
application of operators in evaluating sub expressions.
• The associability rule is applied when two or more operators of
the same precedence level appear in the sub expression.
• Arithmetic expressions are evaluated from left to right using the
rules of precedence.
• When Parenthesis are used, the expressions within parenthesis
assume highest priority. 132
Expression
Precedence of operators:
133
Operators Precedence and Associativity
Operator Precedence and Associativity Table
134
Operators Precedence and Associativity
135
Expression
• Example
34+12/4-45 Here / operator has higher
precedence hence 12/4 is
evaluated first. The
operators + and - have
same precedence because
they are un the same group,
and its associativity is from
left to right therefore
addition (+) is performed
before subtraction (-)
136
Expression
• Example : Arithmetic Expression
a+b*a/b-a%b; Let a=10 and b=2
Here *,/,% operator has
higher precedence, so
associativity rule is applied.
i.e. left to right. hence 2*20
is evaluated first and 20/2 is
evaluated next and 10%2 is
evaluated. The operators +
and - have same
precedence because they
are in the same group, and its
associativity is from left to
right therefore addition (+)
is performed before
subtraction (-) 137
Expression
• Example : Relational Expression
a<b||a<=b||a>=b||a>b||a!=b let a=10, b=20
138
Expression
• Example : Logical Expression
a||b&&a , let a=10, b=25
139
Expression
• Example : Conditional Expression
(a>b && a>b)? a: (b>a && b>c)? b:c let a=10, b=20, c=5
conditional expression values
evaluated based on precedence as
First ? and:. Since there are two
conditional operators, the
expression is evaluated based on
associativity rule. the
associativity of conditional
operator is right to left.
140
Expression
• Example : increment and decrement operators
i++ + ++i + i++ + ++i +i, let i be 10
141
Expression
• Example :Expression evaluation
main ()
{
float a, b, c x, y, z;
a = 9;
b = 12;
c = 3;
x = 11– 1; Output:
y = a – b / (3 + c) * (2 – 1); x=10.00
z = a – ( b / (3 + c) * 2) – 1; y=7.00
printf ("x = %f",x); z=4.00
printf ("y = %f",y);
printf ("z = %f",z);
}
144
Technical Aptitude Questions
11 -6 10 0
int a = 50;
printf(“%d”,sizeof(++a)); int a=10;
printf(“%d”,a); printf(“%d %d”,++a,+
+a);//12
4 50 12 12
145
C Expressions -Exercise
Exercise 3
printf(“%d%d%d”,z,x,y);
3.6 What is the output for the following code.
int b=15, c=5, d=8, e=8, a;
void main(){
int c= - -2;
printf(“c=%d”,c)}
149
C Type Conversion
Type conversion:
• Type conversion refers to changing an variable of one data type
into another.
• The compiler will automatically change one type of data into
another if it makes sense.
• For instance, if you assign an integer value to a floating-point
variable, the compiler will convert int to float.
• Casting allows you to make this type conversion explicit, or to
force it when it wouldn’t normally happen.
• Types:
− Implicit Conversion:
− Explicit Conversion
150
C Data Types
Implicit Conversion:
• Implicit type casting means conversion of data types without
losing its original meaning.
• Implicit type conversion happens automatically when a value is
copied to its compatible data type.
• During conversion, strict rules for type conversion are applied.
• If the operands are of two different data types, then an operand
having lower data type is automatically converted into a
higher data type.
151
C Type Conversion
bool -> char -> short int -> int -> unsigned int -> long ->
unsigned -> long long -> float -> double -> long double
152
C Type Conversion
• Implicit Conversion:
#include<stdio.h>
void main()
{
int num =1;
char c=‘d’; // asci value of d is 100
int sum;
sum=num+c; //1+100
printf(“%d”,sum);
}
Output:
101
153
C Type Conversion
• Implicit Conversion:
#include<stdio.h>
void main()
{
int num =1;
char c=‘d’; // asci value of d is 100
float sum;
sum=num+c; //1+100
printf(“%f”,sum);
}
Output:
101.00
154
C Type Conversion
• Explicit Conversion: The type conversion performed by the
programmer by posing the data type of the expression of
specific type is known as explicit type conversion.
155
C Type Conversion
• The Syntax for explicit conversion is
(data-type) expression;
Example:
int main()
{
double x= 1.2;
int sum= (int)x+1; // explicit conversion
printf(“sum=%d”,sum);
return 0;
}
Output:
2
156
Input / Output Statements
• C programming language provides many built-in functions to read
any given input and to display data on screen when there is a need
to output the result.
• There are two types input/output functions namely:
– Formatted input/output functions
– Un-formatted input/output functions
157
Input / Output Statements
Formatted Input function:
scanf( )
• scanf( ) is responsible to input values for variables from keyboard
• It is to used to input numeric, string and character data type
Syntax:
scanf(“format string”, &input data list);
159
Input / Output Statements
Formatted Output function
printf( )
• It is responsible to write output to the computer monitor
• It is to used to print numeric, string and character data type
Syntax: printf(“format string”, output data list);
printf(“ “);
Example:
Output:
int x;
Enter a number: 20
printf(“Enter a number:”); Entered number is :
20
scanf(“%d”, &x); // Run-time Input
printf(“Entered number is : %d”, x); 160
Input / Output Statements
Technical Aptitude
int a, b, c;
printf(“Enter the two values:”); Output
c = scanf(“%d %d”, &a, &b); 2
printf(“Count is : %d”, c);
int a=34,b=3,c;
Output printf(“%d ”,printf(“CSE”));
CSE3335 c = a + printf(“%d”,b);
printf(“%d”,c);
161
Input / Output Statements
Technical Apptitude
Output: Output:
CSE3 CSEDepartmentCSE
Output:
Output:
MorningMorning
4
162
Input / Output Statements
Un-formatted Input/Output functions:
• Unformatted input and output functions will work only with
character data type
• These functions do not require any format specifiers
1.getchar( )
• It reads one character at a time from keyboard
Example:
char c; Output:
Enter a character : T
printf("Enter a character : ");
Entered character : T
c = getchar();
printf("\n Entered character : %c ", c); 163
Input / Output Statements
Un-formatted Input/Output functions:
2.getch ( )
• It reads the alphanumeric character input from the user
• The entered character will not be displayed
Example:
164
Input / Output Statements
Un-formatted Input/Output functions:
4.putchar ( )
Output:
• It prints only one character at a time Output character : K
• It takes one argument
Example: char c = 'K';
putchar(c);
printf("Output character : %c ", c);
5.putch ( )
Output:
• It prints only alphanumeric character Output character : K
Example:
char c = 'K';
printf("Output character : %c ", c);
putch(c);
165
Input / Output Statements
Un-formatted Input/Output functions:
6.gets( ) and puts ( )
gets( ) function is useful to get input characters and puts( ) function
will display the characters in the output screen
Example:
char a[50];
printf(“Enter a string:”); Output:
Enter a string: Hai
gets(a); Output string: Hai
printf("Output string :);
puts(a);
166
Input / Output Statements
Exercise 5
167
Input / Output Statements
Exercise 5
168
Input / Output Statements
Exercise 5
169
Input / Output Statements
Exercise 5
171
Control statements - Selection
• Conditional Statements in C programming are used to make
decisions based on the conditions.
• Conditional statements execute sequentially when there is no
condition around the statements.
• If you put some condition for a block of statements, the execution
flow may change based on the result evaluated by the condition.
• This process is called Selection or decision making in 'C.‘
172
Control statements - Selection
If statement:
• It has block of statements which is executed if the condition is
true.
• It must have condition within a brackets after the keyword ‘if’
173
Control statements - Selection
Example: Program for if statement
int main()
{
int a;
printf(“Enter a number:”);
scanf(“%d”,&a);
if(a<100)
printf(“The number %d is lesser than 100”,a);
return 0;
}
Output:
Enter a number: 65
The number 65 is lesser that 100
174
Control statements - Selection
if – else statement
• If the condition is true, then the block will be executed, otherwise
the else block will be executed
• else block is not mandatory & if it’s not present, it becomes simple
if
175
Control statements - Selection
Example: Program for if else statement
int main()
{
int a;
printf(“Enter a number:”);
scanf(“%d”,&a);
if(a<100)
printf(“The number %d is lesser than 100”,a);
else
printf(“The number %d is not lesser than 100”,a);
return 0;
}
Output:
Enter a number: 25
the number 25 is lesser than 100 176
Control statements - Selection
if(-1) int a=0; int a=-1;
{ if(a) { if(a<0 && a>-2) {
printf(“Hi U”); printf(“Hi U”); printf(“Hi U”);
} } }
if(printf(“CSE”)) If(10>5);
{ {
printf(“ Hi U”); printf(“ Hi U”);
} }
Output: Output:
CSEHi U Hi U
177
Control statements - Selection
if-else-if ladder statement
• The if-else-if ladder statement executes one condition from
multiple statements.
• The execution starts from top and checks for each if condition.
178
Control statements - Selection
179
Control statements - Selection
Example: Program for if else ladder
#include<stdio.h>
int main(){ If e
int number=0; lse
l ad
printf("enter a number:"); der
scanf("%d",&number);
if(number==10){
printf("number is equals to 10");
}
else if(number==50){ Output:
printf("number is equal to 50"); enter a number:25
} number is not equal to 10, 50 or 100
else if(number==100){
printf("number is equal to 100");
}
else{
printf("number is not equal to 10, 50 or 100");
}
return 0;
} 180
Control statements - Selection
Nested if-else Statement
• The nested if-else statement is used when a program requires more
than one test expression.
• We can write if-else statements within another if statement or in
the body of else, this is called nested if-else.
181
Control statements - Selection
Example: Program for nested if
else
#include <stdio.h>
int main()
{
int var1, var2;
printf("Input the value of
var1:"); Output:
scanf("%d", &var1); Input the value of var1:10
printf("Input the value of Input the value of var1:12
var2:"); var2 is greater than var1
scanf("%d",&var2);
if (var1 != var2)
{
printf("var1 is not equal to
var2\n"); 182
if (var1 > var2)
Control statements - Selection
switch statements:
• Used when a choice is to be made from a number of alternatives.
183
Control statements - Selection
Facts about switch statements:
• It is a multi way decision statement, so it is an alternative to long
if-else chain.
• If break is not used, then case "falls through" to the next.
• Case labels must be an integer or character .
• Case labels must be unique and must end with colon.
break; } 185
Control statements - Looping
Looping:
• A Loop executes the sequence of statements many times until the
stated condition becomes false.
• Loop consists of two parts:
– Body of Loop: consists of a set of statements that need to be
continuously executed
– Conditional Statement: is a condition. If it is true, then the
next iteration is executed else the execution flow exits the loop.
Types of loop
1. for : Entry level check
2. while : Entry level check
186
3. do-while : Exit level check
Control statements - Looping
‘while’ loop
• Condition is checked at the beginning of the loop, i.e. Entry
Check
• The body of while loop is executed till the condition becomes false
• The body of while loop is executed zero or more times, depending
on the condition
187
Control statements - Looping
188
Control statements - Looping
Example:
Program to print numbers from 1 to 10 Output:
int i =1; 12345678910
while(i<=10){
printf(“%d “,i);
i++;
}
190
Control statements - Looping
191
Control statements - Looping
Example:
Program to print numbers from 1 to 10 Output:
int i =1; 12345678910
do{
printf(“%d “,i);
i++;
}while(i<=10);
193
Control statements - Looping
194
Control statements - Looping
Example:
196
Control statements – Jumping Statements
Jump statements
• Jump statements are used when we want to skip some
statements inside loop or terminate the loop immediately
when some condition becomes true.
Jumping Description
Statement
continue The continue statement is used for skipping part of
loop's body
break The break statement is used to stop the execution of
loop and switch case statements
goto The goto statement is used for jumping from front
statement to another within a function
197
Control statements – Jumping Statements
break command:
• Terminates the current loop / switch
• Used only in the context of a loop or a switch, and not for any
other types of statements
198
Control statements – Jumping Statements
Syntax:
199
Control statements – Jumping Statements
Example: Program to take input from the user until he/she enters
zero
int main ()
{
int a;
while (1)
{
printf("enter the number:");
scanf("%d", &a);
Enter the number:10
if ( a == 0 )
Enter the number:-2
break;
Enter the number:0
}
return 0;
}
200
Control statements – Jumping Statements
Continue statement:
• It skips the remaining statements in the body of that loop and
performs the next iteration of the loop.
201
Control statements – Jumping Statements
Syntax:
202
Control statements – Jumping Statements
Example: program to print sum of numbers divisible by 3 below
100
int main ()
{
int i, sum=0;
for(i=1;i<=100;i++)
{
if ( i%3 != 0 )
continue; Sum is : 1683
sum = sum + i;
}
printf(“Sum is :%d",sum);
return 0;
}
203
Control statements – Jumping Statements
goto statement:
• ‘goto’ statement is used for transferring control to some other
part of the program.
• Syntax:
204
Control statements – Jumping Statements
Print the numbers from 1 to 10
int main ()
{
int i=1;
count: //This is Label
printf("%d ",i);
i++; 1 2 3 4 5 6 7 8 9 10
if(i<=10) {
goto count; //jumps to label "count:"
}
return 0; }
205
Input / Output Statements
Exercise 6
206
Input / Output Statements
Exercise 6
207
Input / Output Statements
Exercise 6
208
Input / Output Statements
Exercise 6
209