You are on page 1of 209

CS8251 – Programming in C

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 –

C programming: Data Types –Storage classes – Constants

–Enumeration Constants – Keywords –Operators: Precedence and

Associativity – Expressions – Input/Output statements, Assignment

statements –Decision making statements – Switch statement –

Looping statements –pre-processor directives - compilation process

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

Step 3: Display C // instruction 3

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

semantic rules, which define the meaning of each of the

programming language constructs.

Types

• There are three common types of programming languages includes,

– Machine Level Languages

– Assembly Level Languages

– High Level Languages


8
Programming Languages
Machine Level Languages
• Machine language, or machine code, is a low-level language
comprised of binary digits (0s and 1s). It is the only language that
a computer can understand.
• Since a computer is capable of recognizing electric signals, it
understands machine language. The symbol 0 stands for the
absence of an electric pulse and the 1 stands for the presence of
an electric pulse.
• Example: machine language (binary) for the text "Hello World“
– 01001000 01100101 01101100 01101100 01101111 00100000
01010111 01101111 01110010 01101100 01100100
9
Programming Languages
Machine Level Languages
Advantages
• Machine language makes fast and efficient use of the computer.
• It requires no translator to translate the code. It is directly
understood by the computer.
Disadvantages
• All operation codes have to be remembered.
• All memory addresses have to be remembered.
• It is hard to amend or find errors in a program written in the
machine language.
• Machine dependent
10
Programming Languages
Assembly Level Languages
• Assembly language was developed to overcome some of the
inconveniences of machine language.
• This is another low-level but very important language in which
operation codes and operands are given in the form of
alphanumeric symbols or mnemonic codes instead of 0’s and l’s.
• Example: ADD for addition, SUB for subtraction, START, LABEL
etc. 
• The instructions of the assembly language are converted to machine
codes by a language translator is called as assembler and then
they are executed by the computer. 11
Programming Languages
Assembly Level Languages
Advantages
• Easy to understand than machine language
• Modification and fix error is easy than machine language
• Very good support for hardware
Disadvantages
• Like machine language, it is also machine dependent/specific
• Very difficult to remember lots of mnemonic codes
• Need translator to convert assembly language into machine
language

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

• Main consists of a sequence of commands or statements which


modify data which is global throughout the whole program.
• Example: BASIC,COBOL

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?

a) Machine code b) Low Level languages

c) High Level languages d) Algorithm

Answer : Option a)
2) Before a computer can understand a program it must be

a) Translate to High Level b) Translate to Low Level

c) Translate to Algorithm d) Translate into machine code

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

c) Binary Code d) Algorithm

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

c) High Level Language d) Algorithm

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

Developed by Martin Richards to


write system software

Basic Combined
Programming Language

Developed by Ken Thomson. It is


used to create early versions of
B Language UNIX OS
29
C Programming : History
Developed by Dennis Ritchie, it
contains features of ALGOL,
‘C’ Language
BCPL, B

First edition of C was published


by Kernighan and Dennis Ritchie

Kernighan & Ritchie


‘C’

ANSI defined a standard for C.

American National Standard


Institute ‘C’ 30
C Programming : History
Approved by ISO committee.
During this period some advanced
International Standard
languages(C++,Java) are
Organization ‘C’ developed

Here some of the new features are


added and some unwanted
features are removed based on
ISO/IEC 9899:1999
feature languages(C++,Java)

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

Mobile Operating System


Web Development
Operating system Kernel

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/

• Extract downloaded “Turbo C++ 3.2.zip file.


• Run setup.exe file
• Accept the license agreement and click install.

• After successful installation select finish and start using Turbo C


software.

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

• Run the program using Ctrl + F9 or select Run > Run

43
How to run a simple C Program??
• Alt+F5 to view the output of the program at the output screen.

Running C Program in Ubuntu Linux using gcc compiler:


• Open text editor and type your program.

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 :

To execute your C program


• Start Terminal  Set Path  to compile type  gcc hello.c 
to run type  ./a.out

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

1) Single line comment

2) Multi line comment

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:

int a=10; // global variable declaration


int main(){
int b; // local variable declaration
return 0;}
53
Structure of C Programming
Main Function:
• Every C-programs needs to have the main function because it is
the entry point of the C programming.
• Each main function contains 2 parts - A declaration part and an
Execution part.
• The declaration part is the part where all the variables are
declared.
• The execution part begins with the curly brackets and ends
with the curly close brackets.
• Example:
int main(){
int a; //declaration part
a=10;
printf(“%d”,a); // execution part
return 0;}
54
Structure of C Programming
Sub Program Section
• All the user-defined functions are defined in this section of the
program.
• Example:

Main
Function
Sub Function1 Sub Function 4
add() divide()

Sub Function 2 Sub Function 3


sub() multiply()

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

• roll_no No special character • ROLLNO& It should not have any


• NewDelhi2 except underscore can be • NewDelhi-2 other symbol except
used alphabets, digits, and
underscore symbol.
• TRUE Any user define • int It must not be a
• FALSE identifier is allowed • float keyword of C language.

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.

• In C language, data types are broadly classified as:

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:

char ----- ‘a’ or ‘A’ or ‘+’ [ Single character]


int ----- 56 [Any number without fraction]
float ----- 56.5f [Any number with fraction]
double ----- 56.25 [Any number with fraction]

void ----- No values available


array ----- char[ ], int [ ], etc., int a[10]
pointer ----- char *, int *, etc.,

function----- int (int, int), float(int), etc.,

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.

− signed – Applicable for int, char [+ve and –ve value]


− unsigned – Applicable for int, char [+ve value]
− short – Applicable for int [+ve and –ve value]
− long – Applicable for int, double [+ve and –ve value

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

1.1 What is the output for the following code


int main()
{
int a=010;
printf(“%d”, a);
}
1.2 What is the output for the following code
int main()
{
int a=0x10;
printf(“%d”, a);
}
87
C Token -Exercise
Exercise 1

1.3 What is the output for the following code


int main()
{
char a=’d’;
printf(“%d”, a);
}
1.4 What is the output for the following code
int main()
{
float a=234.25634f;
printf(“%0.2f”, a);
}
88
C Token -Exercise
Exercise 1

1.5 What is the output for the following code


int main()
{
float a=234e2;
printf(“%f”, a); 23400.000000
}
1.6 What is the output for the following code
int main()
{
float a=234e-2;
printf(“%f”, a);
}
89
C Token -Exercise
Exercise 1

1.7 What is the output for the following code


#include<stdio.h>
int X=40;
int main()
{
int X=20;
printf("%d\n", X);
return 0;
}

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:

int a = 5; int a = -5; int a = 5;


printf(“%d”, a); printf(“%d”, -a); printf(“%d”, a+10);

Output: Output: Output:


5 5 15
94
Operators – Arithmetic operators
• Example:
int a = 15,b=2; int a = 15,b=2; int a = 5,b=-3;
printf(“%d”, a/b); printf(“%d”, a%b); printf(“%d”, a*b);

Output: Output: Output:


7 1 -15

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

Mixed Mode Arithmetic


• If either operand is of the real type, then only the real operation
performed and the result is always a real number.
• Example:

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

which means- x= ASCII value of ‘A’+ ASCII value of ‘a’


x=65+97
x=162

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])

Let's assume, 'a' is 8 and 'b' is 4


Operator Description Example Category
< Less than a<b False
> Greater than a>b True
<= Less than or equal to a <= b False
>= Greater than or equal to a >=b True
== Equal to a ==b False
!= Not Equal to a !=b True 98
Operators – Relational operators
• Example:
int a = 5, b=10; int a = -5; int a=5,b=-1,c=0;
printf(“%d”, a<b); printf(“%d”, a!=-5); printf(“%d”, a>b>c);

Output: Output: Output:


1 0 1

int a=5,b=-1,c=0; char a = ‘A’, b=‘a’;


printf(“%d”, a==b!=c); printf(“%d”, a<b);

Output: int a=5,b=-1,c=6; Output:


0 1
printf(“%d”, a==b+c);

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])

Let's assume, 'a' is 8 and 'b' is 4


Operator Description Example Category

&& Logical AND – If both operands are a && b True


non-zero
|| Logical OR – If any one of the a<10 || b>0 True
operand are non-zero
! Logical NOT – If operand is true, !a False 100
then false. Vice-versa
Operators –Logical operators
• Truth Table:

Condition 1 Condition 2 A&&B A||B !A


(A) (B)

True True True True False


True False False True False
False True False True True
False False False False True

101
Operators –Logical operators
• Example:

int a = 5, b=0; int a = -5,b=5; int a=5,b=-1,c=0;


printf(“%d”, a&&b); printf(“%d”, a&&b); printf(“%d”, a>b || c);

Output: Output: Output:


0 1 1

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);

Output: Output: Output:


1 05 11
102
Operators –Bitwise operators
Bitwise Operators:
• Bitwise operators are used for manipulating a data at the bit level,
also called as bit level programming. Bit-level programming mainly
consists of 0 and 1.
• Input: Numeric value(either positive or negative]
• Output: Numeric value(either positive or negative]
Let's assume, 'a' is 8 and 'b' is 4
Operator Description Example Output
& Bitwise AND a&b 0
| Bitwise OR a|b 12
^ Bitwise X-OR a^b 12
~ Negation or Tilde ~a -9
<< Left shift a<<2 32 103
Operators –Bitwise operators
• A bitwise operator which operates on each bit of data.
• Bitwise operators only operates on integer operands such as int,
char, short int, long int.
• Truth table:

104
Operators –Bitwise operators
• Example:

Bitwise AND (unsigned) Bitwise AND (signed)

a=5 ,b=3 a= -5 ,b=3

5 00000101 5 00000101

3 00000011 -5 11111010 (1’s complement)

00000001 1(2’s complement)


11111011
If MSB is 0  Positive number 3 00000011
if MSB is 1  Negative number MSB
00000011

105
Operators –Bitwise operators
• Example:

Bitwise OR (unsigned) Bitwise OR (signed)

a=5 ,b=3 a= -5 ,b=3


5 00000101
5 00000101
-5 11111010 (1’s complement)
3 00000011 1(2’s complement)
00000111 11111011
3 00000011
if the result is negative MSB
11111011
number, then it should be
00000100
converted into positive
number by taking one’s and 1
two’s complement of the 00000101
result. 106
Operators –Bitwise operators
• Example:

Bitwise XOR (unsigned) Bitwise XOR (signed)

a=5 ,b=3 a= -5 ,b=3


5 00000101
5 00000101
-5 11111010 (1’s complement)
3 00000011 1(2’s complement)
00000110 11111011
3 00000011
MSB
11111000
00000111
1
00001000
107
Operators –Bitwise operators
• Example:
Right shift The left operands value is moved right by the number of
bits specified by the right operand.
5>>2
Vacated bits
5 0 0 0 0 0 1 0 1

>>2 0 0 0 0 0 0 0 1 0 1

Filled bits

i.e. 5>>2  00000001

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

i.e. 5<<2  00000100

110
Operators –Bitwise operators
• Example: Left Shift (signed)
-70<<1
70  01000110
10111001 (1’s complement of 70) steps to calculate -70

1 (2’s complement of 70)


1 0 1 1 1 0 1 0 Filled bits
-70
-70<<1 1 0 1 1 1 0 1 0 0

Vacated bits

i.e. -70<<1 is 01110100


111
Operators –Bitwise operators
• Example:

int a = 5, b=-5; int a = 0,b=5; int a=5,b=-5;


printf(“%d”, a&b); printf(“%d”, a|b); printf(“%d”, a^b);

Output: Output: Output:


1 5 -2

int a=-5; int a=-5; int a = 0;


printf(“%d”, a<<3) printf(“%d”, ~a); int b = a | ~a;
printf(“%d %d”,a,b);

Output: Output: Output:


-40 4 0-1
112
Operators –Assignment operators
Assignment Operators:
• It is used to assign values of the operand on the right to the
operand on the left and not vice versa.
– Example : A=10
• Normally used Assignment operator is “=“ , but C has set of
shorthand assignment operator “op=“.
• Syntax for Normal Assignment
Variable = expression;
• Syntax for Short Hand Assignment
Variable op = expression;

• a+=10  a=a+10 113


Operators –Assignment operators
• Example:

Operators Short Hand Equivalent


Assignment Simple
Assignment
= a =10 0
+= a+=2 a= a + 2
-= a-=2 a = a -2
*= a*=2 a = a *2
/= a/=2 a = a/2
%= a%=2 a = a%2
&= a&=2 a = a&2
|= a|=2 a = a|2
^= a^=2 a = a^2
<<= a<<=2 a = a<<2
>>= a>>=2 a = a>>2
114
Operators –Assignment operators
• Example:

int x,y,z; int a = 0,b=5;


int a=5,b=3,c=2;
x=y=z=10; a+b = 10;
c<<= a&b;
printf("%d %d %d", printf(“%d %d”, a,b);
printf(“%d”, c);
x,y,z);

Output: Output: Output:


10 10 10 Error: lvalue 4
required as left
operand of
assignment

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.

– if the expression 1 is false, then the expression 3 is evaluated.


• Example:
a=10;
b=15; Here x will be assigned the value of b
x=(a>b)?a:b; since the condition is false.

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:

double a=10; printf(“%d”, sizeof(5.6));


double *p; int a=(10,20,30); printf(“%d”, sizeof(65));
p=&a; printf(“%d”, a); printf(“%d”, sizeof(‘A’));
printf(“%d”,*p);

Output: Output: Output:


10 30 421

124
C Operators -Exercise
Exercise 2

2.1 What would be the output of:


void main()
{
printf("%d\n",1==5==5);
}
2.2 If a is 15, then what would be the value of:
printf("%d",++a);
printf("%d",a++);
printf("%d",--a);
printf("%d",a--);

125
C Operators -Exercise
Exercise 2

2.3 What will be the output for the following code?


int main()
{
int i;
i = 1, 2, 3;
printf("%d", i);
return 0;
}
2.4 What will be the output for the following code?
int main()
{
int i;
i = (1, 2, 3);
printf("%d", i);
return 0;
} 126
C Operators -Exercise
Exercise 2

2.5 What is the value of d?


int main()
{
int a=15,b=20, c=8,d;
d=((a<b)&&(a>c)) (1)&&(1)
printf(“%d”,d);//1
}
2.6 What will be the output for the following code?
int main()
{
int a=8,b=0;
printf(“%d”,!a); !-logical not
printf(“%d”,!b); ~
}- bitwise not

127
C Operators -Exercise
Exercise 2

2.7 What is the output of this program?


void main()
{
int a=42;
printf(“%d”,a>>4);
}
2.8 What will be the output for the following code?
#include <stdio.h>
int main()
{
int d, a = 1, b = 2;
d = a++ + ++b;
printf("%d %d %d", d, a, b);
}

128
C Operators -Exercise
Exercise 2

2.9 What is the output of this program?


void main()
{
printf(“%x”,-1<<4);
}

2.10 What will be the output for the following code?


void main()
{
int a=10, b=11, c=13, d;
d=(a=c, b+=a, c=a+b+c)
printf(“%d %d %d %d”,d,a,b,c);
}

129
Expression
• Any valid combination of constants, variables and operators
constitute an expression.
• Example: x2-3xy+2y2

Algebraic Expression C Expression


axb–c a*b–c
(m + n) (x + y) (m + n) * (x + y)
(ab / c) a*b/c
3x2 +2x + 1 3*x*x+2*x+1
(x / y) + c x/y+c

130
Expression
Evaluation of Expressions
• Expressions are evaluated using an assignment statement of the
form.
• Syntax: Variable = expression;

– Variable is any valid C variable name.


– When the statement is encountered, the expression is evaluated
first and then result is assigned to the variable.
– All variables used in the expression must be assigned values
before evaluation is attempted.

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:

• The precedence of operators determines which operator is executed


first if there is more than one operator in an expression.
Associativity of operators:
• If two operators of the same precedence (priority) are present,
associativity determines the direction in which they execute. The
associativity of operators determines the direction in which an
expression is evaluated.

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

Here <,<=,>,>= has same


precedence so according to
associativity rule left to right is
evaluated. Then the next highest
precedence level is != is executed
then || operator is evaluated

138
Expression
• Example : Logical Expression
a||b&&a , let a=10, b=25

Logical expression values


evaluated based on precedence as
the First &&, followed by || and !.

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

Postfix increment operator has


highest precedence and its
associativity rule is from left to
right and then prefix increment
operator is executed and its
associativity rule is from right to
left and then addition operation is
performed.

141
Expression
• Example :Expression evaluation

According to precedence and


associativity rule, increment
operator is evaluated first, but
|| operator needs two operands
to evaluate so first ++a is
evaluated, then ++b is
evaluated.
In logical OR if any one
operand is true then the
result is true. So the compiler
will neglect to evaluate ++c.
Finally,
m=1, a=0, b=3, c=0 142
Expression
• Example :Expression evaluation

According to precedence and


associativity rule, increment
operator is evaluated first, but
&& operator needs two
operands to evaluate so first +
+a is evaluated.
In logical AND if any one
operand is false then the
result is false. So the compiler
will neglect to evaluate ++b
and ++c.
Finally,
m=0, a=0, b=2, c=0 143
Expression
• Example: The effect of presence of parenthesis in expressions

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

int a = 10,b=2,c; int a = -5,b=0; int a=5, b=2,c=1,d;


c = a/b - ++a; printf(“%d”, a ||++b); d = a <b && c &d;
printf(“%d”, a); printf(“%d”, b); printf(“%d”, d);
printf(“%d”, c);

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

3.1 What would be the output of:


#include<stdio.h>
void main(){
int i=5,j=10,num;
num=(++i,++j,i+j);
printf("%d %d %d",num,i,j);
}
3.2 What is the value of i?
void main(){
int i =10;
i=!i>14;
printf(“%d”,i); }
146
C Expressions -Exercise
Exercise 3

3.3 What would be the value of 'a':


a. int a = 10/45*23%45/(45%4*21)
b. float a = 10+45.0*23-45+(4*21.0)

3.4 What is the output for the following code.


int x=5, y=0, a,b;
a= ++y || ++x;

b= --y && ++x;


printf(“ x=%d , y=%d, a=%d, b=%d”, x,y,a,b);
147
C Expressions -Exercise
Exercise 3

3.5 What is the output for the following code.


int z,x=5,y=-10, a=4,b=2;
z=x++ - --y*b/a;

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;

a= b>c ? c>d ? 12 : d > e ? 13 : 14 : 15


printf(“%d”,a);
148
C Expressions -Exercise
Exercise 3

3.7 What is the output for the following code.


void main(){
int a, b=7;
a=b<4 ? b<<1 : ++b>4 ? 7>>1 : a;
printf(“%d %d”, a, b);}
3.8 What is the output for the following code.

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);

-- format string should starts with %

-- input data list must have &(address) symbol for any


variable
Example: int a;
scanf(“%d”,&a);
158
Input / Output Statements
Formatted String:

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

int x = printf(“CSE”); printf(“CSE” “Department”);


printf(“%d”, x); printf(“CSE”, ”Department”);

Output: Output:
CSE3 CSEDepartmentCSE

printf(5+”Good Morning”); int x = sizeof(printf(“EEE Dept”));


printf(“Good Morning”+5); printf(“%d”, x);

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:

printf(“Enter a character: ");


Output:
char c= getch(); Enter a character :
Entered character : T
printf("\n Entered character : %c ", c);

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

Exercise 5.1 What is the output for this program?


#include <stdio.h>
int main(){
int i;
i = printf("letsfindcourse");// letsfindcourse14
i = printf("%d ", i);
printf("%d ", i);
return 0;}

Exerise 5.2 Output of this statement is:


printf ( "%d" , printf ( "hello" ) );//hello5

167
Input / Output Statements
Exercise 5

Exercise 5.3 What is the output for this program?


#include <stdio.h>
void main ()
{
char line [80];// character array that has atmost 80
gets (line);
puts (line);
}
Exerise 5.4 Answer the question
if i,j,k are integers, the scanf function to enter i,j,k such that i is
decimal,j is octal and k is hexadecimal. Write the correct scanf
statement. Scanf(“%d%o%x”,&i,&j,&k);

168
Input / Output Statements
Exercise 5

Exercise 5.5 What is the output for this program?


#include <stdio.h>
void main (){
char line [80];
gets (line);
puts (line);}
Exerise 5.6 What would be the output of the following C program
if input to the program is 'e'?
#include <stdio.h>
void main (){
char lower, upper;
lower = getchar(); //e
upper= toupper (e);//E
putchar (upper);}//E

169
Input / Output Statements
Exercise 5

Exercise 5.7 Answer the question


float x, y, z;
scanf ("%f %f", &x, &y);
If input stream contains "4.2 3 2.3 ..."
What will x and y contain after scanf? X=4.2 y=3.0

Exercise 5.8 What will be the output?


#include <stdio.h>
// Assume base address of "Welcome" to be 1000
int main()
{
printf(5 + "Welocme");
return 0;
}
170
Control statements
• The statements that are used to control the flow of execution of
statements are known as conditional control statements.
• Conditional statements are divided into three types:-

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”);
} } }

Output: Output: Output:


Hi U 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.

• The statement of if block will be executed which evaluates to be


true.
• If none of the if condition evaluates to be true then the last else
block is evaluated.

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.

• The default label is optional. It can be used anywhere within


switch.
• The break statement transfers the control out of the switch.
• Case labels should not be float value
184
Control statements - Selection
Example:Program using Switch case: case 2: printf("Number is two\n");
#include<stdio.h>
break;
Void main()
case 3: printf("Number is
{
Output:
int i; three\n"); Enter a number:6
something else
printf("Enter a number: \n"); break;
scanf("%d", &i); case 4: printf("Number is four\n");
switch(i)
break;
{
default:
case 1: printf("Number is
one\n"); printf("something else\n");

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++;
}

Program to print numbers from 10 to 1


Output: int i =10;
10987654321 while(i>0) {
printf(“%d “,i);
i--;
}
189
Control statements - Looping
‘do-while’ loop
• Condition is checked at the end of the loop, i.e. Exit Check

• The body of do-while loop is executed continuously, till the


condition becomes false
• The body of loop is executed at least once, irrespective of
condition being true or false, since the condition is checked at the
end of loop.

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);

Program to print numbers from 10 to 1


Output: int i =10;
10987654321 do{
printf(“%d “,i);
i--;
}while(i>0);
192
Control statements - Looping
‘for’ loop
• Provides a compact syntax for iteration
• Allows you to specify the following, all on one line:
1. Initialization statement
2. Boolean expression for continuing loop
3. Statements to be executed after loop
• Condition is checked at the starting of loop, i.e. Entry Check

193
Control statements - Looping

194
Control statements - Looping
Example:

Program to print numbers from 1 to 10


int i ;
Output:
for (i=1 ; i <=10 ; i++) 12345678910
{
printf(“%d “,i);
}

Program to print numbers from 10 to 1


Output: int i ;
10987654321 for (i=10 ; i >0 ; i--)
{
printf(“%d “,i);
}
195
Control statements - Looping
Format -1 Format -2
int i =1; int i =1;
for (; i <=10 ; i++) for (; i <=10 ; ) {
{ printf(“%d “,i);
printf(“%d “,i); i++;
} }

Format – 3 [ Infinite loop]


int i =1;
for (; ; ) {
printf(“%d “,i);
i++;
}

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

Exercise 6.1 Answer the question


int main()
{
int i;
printf(“enter the value of i:”);
scanf(“%d”,&i);
if(i%5==0)
{
printf(“Number entererd is divisible by 5”);
}
}

206
Input / Output Statements
Exercise 6

Exercise 6.2 Answer the question


int main(){
float age, ageinsec;
int val;
printf(“Enter your age:”);
value=scanf(“%f”,&age);
if(value==0){
printf(“your age is invalid”);}
else{
ageinsec=365*24*60*60*age;
printf(“you have lived for %f seconds”,ageinsec);}}

207
Input / Output Statements
Exercise 6

Exercise 6.3 Answer the question


int main(){
int a=11,b=5;
if(a=5) b++;
printf(“%d%d”, ++a,b++);
}
Exercise 6.4 What will be the output?
int main(){
int value1,value2=100,num=100;
if(value1=value2%5) num=5;
printf(“%d%d %d”, num,value1,value2);
}

208
Input / Output Statements
Exercise 6

Exercise 6.5 Answer the question


int main(){
int i;
for(i=0;i<10;i++);
printf("%d",i);
return 0;}

209

You might also like