0% found this document useful (0 votes)
167 views94 pages

PPSC Unit 1&2 Lesson Notes

The document provides an overview of the "Programming for Problem Solving using C" course offered at Pragati Engineering College. It includes the course objectives, outcomes, topics to be covered in each unit, textbooks and other reference materials. The key topics covered are introduction to computers, C programming language fundamentals, operators, selection and repetition statements, arrays, strings, pointers, functions, and file input/output. The course aims to teach students how to apply C programming concepts to solve problems.

Uploaded by

Hermione Granger
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
167 views94 pages

PPSC Unit 1&2 Lesson Notes

The document provides an overview of the "Programming for Problem Solving using C" course offered at Pragati Engineering College. It includes the course objectives, outcomes, topics to be covered in each unit, textbooks and other reference materials. The key topics covered are introduction to computers, C programming language fundamentals, operators, selection and repetition statements, arrays, strings, pointers, functions, and file input/output. The course aims to teach students how to apply C programming concepts to solve problems.

Uploaded by

Hermione Granger
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 94

PROGRAMMING FOR PROBLEM

SOLVING USING C

DIGITAL NOTES

I YEAR B.TECH – I SEMESTER


A.Y. 2022-23

Pragati Engineering College


(Autonomous)
Permanently Affiliated to JNTUK, Kakinada, Accredited by NAAC with “A” Grade Recognized by
UGC 2(f) and 12(b) under UGC act, 1956
# 1-378, ADB Road, Surampalem – 533 437 Near Peddapuram, E.G.Dist, Andhra Pradesh
Programming for Problem Solving using C (R20)
Programming for Problem solving using C
(Common to CE, ME, EEE, ECE, CSE, CSE (AI&ML),CSE(DS), IT)

Course Category Engineering Science Course Code


Course Type Theory L-T-P-C 3-0-0-3
Prerequisites Internal Assessment 30
Semester End Examination 70
Total Marks 100

COURSE OBJECTIVES
To learn about the computer systems, computing environments, developing of a computer
1
program and Structure of a C Program
2 To gain knowledge of the operators, selection, control statements and repetition in C
To learn about the design concepts of arrays, strings, enumerated structure and union types
3
and their usage.
To assimilate about pointers, dynamic memory allocation and know the significance of
4
Preprocessor.
5 To assimilate about File I/O and significance of functions

COURSE OUTCOMES
BTL
Upon successful completion of the course, the student will be able to:

CO1 Apply the fundamentals of C Programming for Problem solving. K3


CO2 Identify the appropriate Decision statement and Loops for a given Problem. K2
Make use of Arrays and Strings to solve the problems in C.
CO3 K3
CO4 design and implement programs to analyze the different pointer applications K3
CO5 Develop solutions for problems using Files and Functions. K3

Note: K1- Remembering, K2-Understanding, K3-Applying, K4-Analyzing, K5-Evaluating,


K6-Creating

Contribution of Course Outcomes towards achievement of Program


Outcomes (1 – Low, 2 - Medium, 3 – High)
PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
CO1 3 3 3 3 1 0 0 0 0 0 0 0 1 1 0
CO2 3 3 3 3 1 0 0 0 0 0 0 0 1 1 0
CO3 3 3 3 2 1 0 0 0 0 0 0 0 2 1 0
CO4 2 3 3 3 1 0 0 0 0 0 0 0 2 2 0
CO5 3 3 3 3 1 0 0 0 0 0 0 0 2 2 0

COURSE CONTENT
Introduction to Computers: Creating and running Programs, Computer Numbering
UNIT I System, Storing Integers, Storing Real Numbers
Introduction to the C Language: Background, C Programs, Identifiers, Types,

Pragati Engineering College (Autonomous) Page 2


Programming for Problem Solving using C (R20)
Variable, Constants, Input/output, Programming Examples, Scope, Storage Classes and
Type Qualifiers.
Structure of a C Program: Expressions Precedence and Associativity, Side Effects,
Evaluating Expressions, Type Conversion Statements, Simple Programs, Command Line
Arguments.
Bitwise Operators: Exact Size Integer Types, Logical Bitwise Operators, Shift Operators.
Selection & Making Decisions: Logical Data and Operators, Two Way Selection,
UNIT II Multiway Selection, More Standard Functions.
Repetition: Concept of Loop, Pretest and Post-test Loops, Initialization and Updating,
Event and Counter Controlled Loops, Loops in C, Other Statements Related to Looping,
Looping Applications, Programming Examples.
Arrays: Concepts, Using Array in C, Array Application, Two Dimensional Arrays,
Multidimensional Arrays, Programming Example – Calculate Averages
UNIT III Strings: String Concepts, C String, String Input / Output Functions, Arrays of Strings,
String Manipulation Functions String/ Data Conversion, A Programming Example – Morse
Code Enumerated, Structure, and Union: The Type Definition (Type def), Enumerated
Types, Structure, Unions, and Programming Application.
Pointers: Introduction, Pointers to pointers, Compatibility, L value and R value Pointer
UNIT IV Applications: Arrays, and Pointers, Pointer Arithmetic and Arrays, Memory Allocation
Function, Array of Pointers, Programming Application.
Processor Commands: Processor Commands.
Functions: Designing, Structured Programs, Function in C, User Defined Functions, Inter-
Function Communication, Standard Functions, Passing Array to Functions, Passing Pointers
to Functions, Recursion
UNIT V Text Input / Output: Files, Streams, Standard Library Input / Output Functions,
Formatting Input / Output Functions, Character Input / Output Functions
Binary Input / Output: Text versus Binary Streams, Standard Library, Functions for Files,
Converting File Type.

TEXT BOOKS
1. Programming for Problem Solving, Beerhouse A. Forouzan, Richard F.Gilberg, CENGAGE.
2. The C Programming Language, Brian W.Kernighan, Dennis M. Ritchie, 2e, Pearson.
REFERENCE BOOKS
1. Computer Fundamentals and Programming, Sumithabha Das, Mc Graw Hill.
2. Programming in C, Ashok N. Kamthane, Amit Kamthane, Pearson.
Computer Fundamentals and Programming in C, Pradip Dey, Manas Ghosh,
3.
OXFORD.
WEB RESOURCES
1. http://nptel.ac.in/courses/106104128/
2. http://students.iitk.ac.in/programmingclub/course/#notes
3. http://c-faq.com/~scs/cclass/cclass.html
4. http://www.youtube.com/watch?v=b00HsZvg-V0&feature=relmfu
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-087-practical-
5. programming-in-c-january-iap-2010/

Pragati Engineering College (Autonomous) Page 3


Programming for Problem Solving using C (R20)
UNIT - I
INTRODUCTION TO COMPUTERS
A computer is an electronic device, operating under the control of instructions stored in its own
memory that can accept data (input), process the data according to specified rules, produce
information (output), and store the information for future use
Functionalities of a Computer
Any digital computer carries out five functions in gross terms
1. Takes data as input.
2. Stores the data/instructions in its memory and use them when required.
3. Processes the data and converts it into useful information.
4. Generates the output
5. Controls all the above four steps.

CREATING AND RUNNING PROGRAMS


Program consists of set of instructions written in a High-level language like English. The computer
only understands Low-level language. We need a translator to convert high-level language to low-
level language and vice versa. We have two translators known as compiler and interpreter.
Many of the popular programming languages use the compiler as a translator. The job of compile is
to translate the set of instructions to low-level language, while translating it checks the syntax of the
instruction if any error (Wrong syntax) it will list all the errors.
There are 4 steps Creating and Running a Program
1. Writing and Editing
2. Compiling
3. Linkers
4. Executing
Writing and Editing
To write and edit a program we use Text editors. First we open the text editor and write program
(set of instructions) and save the file to disk. The file is known as source file. Every C program, source
file is saved with extension of '.C' example "filename.c"
Compiling
“Compiler” is a software that translates the source code written in a high-level language into the
corresponding object code of the low-level language. Once the compilation is successful (without any
errors) then system will generate an object file (.obj). Command for compiling the file is
'gccfilename.c'.
Linkers
Many of the high-level languages allow splitting the complex program into multiple modules. The
Linker arranges the object code of all the modules that have been generated and combines with
specified header file code that generates an Executable (.exe) file.
Executing

Pragati Engineering College (Autonomous) Page 4


Programming for Problem Solving using C (R20)
Once the executable file is created, we have to execute the program. Command for executing the file
is './a.out'. The command submits the executable file to CPU; the processor performs the task specified
in the source file and generates results.

COMPUTER NUMBER SYSTEM


Number systems are the technique to represent numbers in the computer system architecture, every
value that you are saving or getting into/from computer memory has a defined number system.
Computer architecture supports following number systems.
1. Binary number system
2. Octal number system
3. Decimal number system
4. Hexadecimal (hex) number system

Decimal Number System: Decimal number system is a base 10 number system having 10 digits
from 0 to 9. This means that any numerical quantity can be represented using these 10 digits. Decimal
number system is also a positional value system. This means that the value of digits will depend on
its position. Let us take an example to understand this.
For three numbers – 734, 971 and 207. The value of 7 in all three numbers is different −
 In 734, value of 7 is 7 hundreds or 700 or 7 × 100 or 7 × 102
 In 971, value of 7 is 7 tens or 70 or 7 × 10 or 7 × 101
 In 207, value 0f 7 is 7 units or 7 or 7 × 1 or 7 × 100

The weightage of each position can be represented as follows:

In digital systems, instructions are given through electric signals; variation is done by varying the
voltage of the signal. Having 10 different voltages to implement decimal number system in digital
equipment is difficult.
Binary Number System: The easiest way to vary instructions through electric signals is two-state
system – on and off. On is represented as 1 and off as 0, though 0 is not actually no signal but signal
at a lower voltage. The number system having just these two digits – 0 and 1 – is called binary
number system.
Each binary digit is also called a bit. Binary number system is also positional value system, where
each digit has a value expressed in powers of 2, as displayed here.

Pragati Engineering College (Autonomous) Page 5


Programming for Problem Solving using C (R20)
In any binary number, the rightmost digit is called least significant bit (LSB) and leftmost digit is
called most significant bit (MSB).

And decimal equivalent of this number is sum of product of each digit with its positional value.
110102 = 1×24 + 1×23 + 0×22 + 1×21 + 0×20
= 16 + 8 + 0 + 2 + 0
= 2610
Computer memory is measured in terms of how many bits it can store. Here is a chart for memory
capacity conversion.
 1 byte (B) = 8 bits
 1 Kilobytes (KB) = 1024 bytes
 1 Megabyte (MB) = 1024 KB
 1 Gigabyte (GB) = 1024 MB
 1 Terabyte (TB) = 1024 GB
 1 Exabyte (EB) = 1024 PB
 1 Zettabyte = 1024 EB
 1 Yottabyte (YB) = 1024 ZB

Octal number system has eight digits – 0, 1, 2, 3, 4, 5, 6 and 7. Octal number system is also a
positional value system with where each digit has its value expressed in powers of 8, as shown here

Decimal equivalent of any octal number is sum of product of each digit with its positional value.
7268 = 7×82 + 2×81 + 6×80
= 448 + 16 + 6
= 47010
Hexadecimal Number System has 16 symbols – 0 to 9 and A to F where A is equal to 10, B is
equal to 11 and so on till F. Hexadecimal number system is also a positional value system with
where each digit has its value expressed in powers of 16, as shown below.

Decimal equivalent of any hexadecimal number is sum of product of each digit with its positional
value.
27FB16 = 2×163 + 7×162 + 15×161 + 10×160
= 8192 + 1792 + 240 +10
= 1023410

Number System Relationship: The following table depicts the relationship between decimal,
binary, octal and hexadecimal number systems.

Pragati Engineering College (Autonomous) Page 6


Programming for Problem Solving using C (R20)

HEXADECIMAL DECIMAL OCTAL BINARY


0 0 0 0000
1 1 1 0001
2 2 2 0010
3 3 3 0011
4 4 4 0100
5 5 5 0101
6 6 6 0110
7 7 7 0111
8 8 10 1000
9 9 11 1001
A 10 12 1010
B 11 13 1011
C 12 14 1100
D 13 15 1101
E 14 16 1110
ASCII
Besides numerical data, computer must be able to handle alphabets, punctuation marks,
mathematical operators, special symbols, etc. that form the complete character set of English
language. The complete set of characters or symbols are called alphanumeric codes. The complete
alphanumeric code typically includes −
 26 upper case letters
 26 lower case letters
 10 digits
 7 punctuation marks
 20 to 40 special characters
Now a computer understands only numeric values, whatever the number system used. So, all
characters must have a numeric equivalent called the alphanumeric code. The most widely used
alphanumeric code is American Standard Code for Information Interchange (ASCII). ASCII is a 7-
bit code that has 128 (27) possible codes.

Pragati Engineering College (Autonomous) Page 7


Programming for Problem Solving using C (R20)

ISCII : ISCII stands for Indian Script Code for Information Interchange. IISCII was developed
to support Indian languages on computer. Language supported by IISCI include Devanagari, Tamil,
Bangla, Gujarati, Gurmukhi, Tamil, Telugu, etc. IISCI is mostly used by government departments
and before it could catch on, a new universal encoding standard called Unicode was introduced.

Unicode: Unicode is an international coding system designed to be used with different language
scripts. Each character or symbol is assigned a unique numeric value, largely within the framework
of ASCII. Earlier, each script had its own encoding system, which could conflict with each other.
In contrast, this is what Unicode officially aims to do − Unicode provides a unique number for every
character, no matter what the platform, no matter what the program, no matter what the language.
Decimal to Binary: Decimal numbers can be converted to binary by repeated division of the number
by 2 while recording the remainder.

The remainders are to be read from bottom to top to obtain the binary equivalent.
4310 = 1010112
Decimal to Octal: Decimal numbers can be converted to octal by repeated division of the number
by 8 while recording the remainder. Let’s take an example to see how this happens.

Reading the remainders from bottom to top,


47310 = 7318
Decimal to Hexadecimal: Decimal numbers can be converted to octal by repeated division of the
number by 16 while recording the remainder.

Reading the remainders from bottom to top we get, 42310 = 1A716


Binary to Octal and Vice Versa

Pragati Engineering College (Autonomous) Page 8


Programming for Problem Solving using C (R20)
To convert a binary number to octal number, these steps are followed −
 Starting from the least significant bit, make groups of three bits.
 If there are one or two bits less in making the groups, 0s can be added after the most
significant bit
 Convert each group into its equivalent octal number
For example:

101100101012 = 26258

To convert an octal number to binary, each octal digit is converted to its 3-bit binary equivalent
according to this table.

Octal Digit 0 1 2 3 4 5 6 7

Binary Equivalent 000 001 010 011 100 101 110 111

546738 = 1011001101110112
Binary to Hexadecimal
To convert a binary number to hexadecimal number, these steps are followed −
 Starting from the least significant bit, make groups of four bits.
 If there are one or two bits less in making the groups, 0s can be added after the most
significant bit.
 Convert each group into its equivalent octal number.

For example:

101101101012 = DB516

To convert an octal number to binary, each octal digit is converted to its 3-bit binary equivalent.

Storing Integers : Integers are whole numbers which will be stored in computer using 4 bytes (32
bit) of memory.
Example: 65 : Binary equivalent of 65 is (01000001)2.
The MSB (most significant bit) bit is used to indicate whether the number is positive or negative.
For positive numbers MSB will be 0.
For negative numbers MSB will be 1.
In our case, 65 is positive so MSB will be 0.
This binary equivalent of 65 will be stored in 32-bit memory like below, Pictorial Explanation

Pragati Engineering College (Autonomous) Page 9


Programming for Problem Solving using C (R20)

Storing Negative Numbers : Computer uses special mechanism to store negative numbers which
is 2’s complement format.
1’s complement of a number : 1’s compliment of number is just inverting binary bits of an actual
number.

Example: 10 : Binary representation will be (1010) 2


1’s compliment of 10 is, 0101 (switching 0 to 1 and 1 to 0).
2’s complement of a number
To get 2’s complement of a number, just add 1 to 1’s complement of an actual number.

Example: This 2’s complement form will be stored in computer.

Storing Real Numbers


float a=34.125;
This data type is called float, because the decimal point will be moving (floating). The other data type
is called fixed point, because the decimal point does not move. C does not support fixed point
The number 34.125 can be converted to binary as follows.
34 = 32 *1 + 0 * 16 + 8 * 0 + 4 * 0 + 2 * 1 + 1 * 0 = 100010
.125 = 0.5 * 0 + 0.25 * 0 + 0.125 * 1 = 2^-3

So, the binary representation of 34.125 can be 100010.001


RHS — 34.125 = 100010.001
= 1.00010001 x 2⁵ (The decimal point is moved left 5 position)

Pragati Engineering College (Autonomous) Page 10


Programming for Problem Solving using C (R20)
Now as per the standard 1. will be removed .00010001 is called mantissa (significand). 101(5) is
called exponent.

Now let us see how to construct a 32-bit binary number using these values.
1 bit represent sign bit
8 bits represent exponent
23 bits represent mantissa
In this case, the number is positive, so sign bit is 0. In this case, the exponent is 5, add 127 (exponent
bias) we get 132= 10000100. In this case, the mantissa = 00010001000000000000000
So, the 32-bit binary value of 34.125 is 0 10000100 00010001000000000000000
= 01000010 00001000 10000000 00000000 – 4 bytes stored in memory.
If the system allocates the address as 5000 for variable a. Then the values are stored as follows.
5000 – 00000000
5001 – 10000000
5002 – 00001000
5003 – 01000010

INTRODUCTION TO C LANGUAGE
Background

C’ is a general purpose and structured programming language developed by 'Dennis Ritchie' at


AT&T's (American Telephone & Telegraph), Bell Laboratories in the 1972s in USA. It is also called
as Procedure oriented programming language’. It has some various features like control structures,
looping statements, arrays, macros required for these applications. The C language has following
numerous features like Portability, Flexibility, Effectiveness and efficiency, Reliability, Interactivity.
 ALGOL-60: (1960): ALGOL is an acronym for Algorithmic Language. It was the first
structured procedural programming language, developed in the late 1950s and once widely used
in Europe. But it was too abstract and too general structured language.
 BCPL: (1967): BCPL is an acronym for Basic Combined Programming Language. It was
developed by Martin Richards at Cambridge University in 1967. BCPL was not so powerful. So,
it was failed.
 B (1970): B language was developed by Ken Thompson at AT& T Bell Laboratories in 1970. It
was machine dependent. So, it leads to specific problems. There are no data types.
 C or Traditional C: (1972): 'C' Programming Language was developed by Dennis Ritchie at AT
& T Bell Laboratories in 1972. This is general purpose, compiled, structured programming

Pragati Engineering College (Autonomous) Page 11


Programming for Problem Solving using C (R20)
language. Dennis Ritchie studied the BCPL, B, ALGOL then improved and named it as 'C' which
is the second letter of BCPL.
 Data types also included.
 K & R C: Traditional C is documented and popularized in the book THE C PROGRAMMING
LANGUAGE developed by Brain W. Kernighan and Dennis Ritche in 1978 because of book
popularity this language known as K&RC.
 ANSI C: (ANSI) American national standard institute approved standards on c in year 1989
known as ANSI C.
 ANSI/ISO C : in 1990 ISO (International Standard adopted ANSI standard) known as ANSI/ISO
C.
 C99: Some changes made to C89 and then C95 developed after adding of significant features
finally C99 developed.
STRUCTURE OF A C PROGRAM
A C program is divided into different sections. There are six main sections to a basic program

Documentation Section: The documentation section is the part of the program where the
programmer gives the details associated with the program. He usually gives the name of the program,
the details of the author and other details like the time of coding and description. It gives anyone
reading the code the overview of the code.
/*
File Name: Helloworld.c
Description: A program to display hello world
*/
Link Section: This part of the code is used to declare all the header files that will be used in the
program. The link section provides instructions to the compiler to link functions from the system
library.
#include<stdio.h>
Definition Section: The definition section defines all symbolic constants. The keyword define is used
in this part.

Pragati Engineering College (Autonomous) Page 12


Programming for Problem Solving using C (R20)
#define PI=3.14
Global Declaration Section: In this section, global variables are declared. Global variables are the
variables that are used in more than one function. All the global variables used are declared in this
section that is outside of all the functions. The user-defined functions are also declared in this section.
float area(float r);
int a=7;

Main Function Section: Every C-program must have one main() function section. This section
contains two parts, declaration part and an execution part. The declaration part declares all the
variables used in the execution part. The execution part consists of atleast one statement. These two
parts must appear between the opening and the closing braces. The program execution begins at the
opening brace and ends at the closing brace. The closing brace of the main function section is the
logical end of the program. All the statements in the declaration and execution parts end with the
semicolon (:).
int main(void)
{
int a=10;
printf(" %d", a);
return 0;
}
Sub Program Section: The subprogram section contains all the user-defined functions that are called
in the main function. User defined functions are generally placed immediately after the main
function, although they may appear in any order.
int add(int a, int b)
{
return a+b;
}
Note: All sections, except the main function section may be absent when they are not required.

KEYWORDS AND IDENTFIERS


Every C word is either classified as a keyword or an identifier. All keywords have fixed meanings
and these meanings cannot be changed. Keywords serve as basic building blocks for program
statements. A list of 32 reserved keywords in C language is given below:

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Keywords are written in lowercase letters.
Identifiers: Identifies allows to name the data and other objects in the program i.e., variables,
functions, arrays, structures, Union, Pointers. These are user-defined names and consist of sequence
of letters and digits, with a letter as first character. Each identifier in the computer is stored at a unique
address.
Rules for Identifiers:
Pragati Engineering College (Autonomous) Page 13
Programming for Problem Solving using C (R20)
1. First character must be an alphabet.
2. Must consist of only letters, digits or underscore.
3. Only first 31 characters are significant.
4. Cannot use a keyword.
5. Must not contain white space.
Examples of valid and invalid names:
Valid Names Invalid Names
a $um //$ is illegal
student_name 2names // first character digit
_systemname sum-sal-sal //contains -
INT_Min int //keyword
DATA TYPES
A type defines a set of values and a set of operations that can be applied on those values. Data used
in C program is classified into different types based on its properties.
Data types in the C programming language are used to specify what kind of value can be stored in a
variable. The memory size and type of the value of a variable are determined by the variable data
type. In a C program, each variable or constant or array must have a data type and this data type
specifies how much memory is to be allocated and what type of values are to be stored in that variable
or constant or array.
The Data type is a set of value with predefined characteristics. Data types are used to declare
variable, constants, arrays, pointers, and functions.

In the C programming language, data types are classified as follows.


1. Primary data types (Basic data types OR Predefined data types)
2. Derived data types (Secondary data types OR User-defined data types)
3. User defined data types (structure, union, enum, typedef)

Pragati Engineering College (Autonomous) Page 14


Programming for Problem Solving using C (R20)

Primary data types


The primary data types in the C programming language are the basic data types. All the primary data
types are already defined in the system. Primary data types are also called as Built-In data types.
The following are the primary data types in C programming language...
1. Character (char)
2. Integer (int)
3. Floating Point (float)
4. Double-precision floating point (double)
5. void

Integer Data type: The integer data type is a set of whole numbers. Every integer value does not
have the decimal value. We use the keyword "int" to represent integer data type in C. We use the
keyword int to declare the variables and to specify the return type of a function. The integer data type
is used with different type modifiers like short, long, signed and unsigned. The following table

Pragati Engineering College (Autonomous) Page 15


Programming for Problem Solving using C (R20)
provides complete details about the integer data type.

TYPE SIZE RANGE SPECIFIER


int 2 -32768 to +32767 %d
short int 2 -32768 to +32767 %hd
long int 4 -2147473648 to 2147473647 %ld
unsigned int 2 0 to 65535 %u
unsigned long int 4 0 to 4294967295 %u

Floating Point data types: Floating-point data types are a set of numbers with the decimal value.
Every floating-point value must contain the decimal value. The floating-point data type has two
variants.

float: The keyword "float" is used to represent floating-point data type and "double" to represent
double data type in C. Both float and double are similar but they differ in the number of decimal
places. The float value contains 6 decimal places whereas double value contains 15 or 19 decimal
places. The following table provides complete details about floating-point data types.

TYPE SIZE RANGE SPECIFIER


float 4 1.2E -38 to 3.4E +38 %f
double 8 2.3E -308 to 1.7E+308 %If
long double 10 3.4E-4932 to 1.1E+4932 %lf

Character data type: The character data type is a set of characters enclosed in single quotations.
The following table provides complete details about the character data type.

TYPE SIZE RANGE SPECIFIER


char 1 -128 to + 127 %c
unsigned 1 0 to 255 %c

Void data type: The void data type means nothing or no value. Generally, void is used to specify a
function which does not return any value. Void data type is also used to specify empty parameters of
a function.
Enumerated data type: An enumerated data type is a user-defined data type that consists of integer
constants and each integer constant is given a name. The keyword "enum" is used to define the
enumerated data type.

Derived data types: Derived data types are user-defined data types. The derived data types are also
called as user-defined data types or secondary data types.

VARIABLE: A variable is a data name that may be used to store a data value. A variable may
different value at different times during execution.
Declaring Variables: To create a variable, specify the type and assign a value to it.
Syntax:
type variableName;

Example:
int length;
Pragati Engineering College (Autonomous) Page 16
Programming for Problem Solving using C (R20)
variable name: length
Value
10
Storage address: 1000

Note: If you assign a new value to an existing variable, it will overwrite the previous value:

Example:
int a = 15; // a is 15
a = 10; // Now a is 10

Output Variables
Example
int a = 15;
printf(a); // Nothing happens
----------------------------------------
int a = 15;
printf(“%d”,a); // prints number stored in variable

CONSTANTS
Constants are data values that have fixed values and cannot be changed during the execution of a
program. Like variables constants have a type.

Example
const int a = 15; // a will always be 15
a = 10; // error: assignment of read-only variable 'a'

Note: When you declare a constant variable, it must be assigned with a value.
Example
const int minutesPerHour = 60;

Constants

Numerical Character
Constants Constants

Integer Real Single Character String


Constants Constants Constants Constants

Integer Constants: Integer constant refers to a sequence of digits. There are three types of Integers
namely decimal integer, octal and hexadecimal. There are three different types of integers, namely,
decimal integer, octal integer, and hexadecimal integer.
Decimal integers consist of a set of digits, 0 through 9, preceded by an optional – or + sign.
Examples of decimal constants are: 231 -567 0 34557 +81
Pragati Engineering College (Autonomous) Page 17
Programming for Problem Solving using C (R20)

Embedded spaces, commas, and non-digit characters are permitted between digits.
Examples that are not valid decimal integers: 13 980 10,000 $2100

Octal integer constants consist of any combination of digits from 0 to 7, with leading 0.
Examples of octal integer are: 031 0567 0 0345 0881
Embedded spaces, commas, and non-digit characters are permitted between digits.
Examples that are not valid decimal integers: 13 980 10,000 $2100
Hexadecimal integers are a sequence of digits preceded by 0x, 0X. They may also include alphabets
from A to F which represent the numbers 10 to 15.
Example: 0X2 0x9F 0XAED 0xaef
Table : Examples of Integer Constants
Representation Value Type
+123 123 int
-378 -378 int
-31247L -31,247 long int
45676LU 45,676 unsigned long int
343454365LL 34,34,54,365 long long int

Real Constants: Real (or floating point) constants are used to represent quantities that vary
continuously such as distances, heights, temperatures, prices so on. They are represented using by
numbers containing fractional parts like 18.345.
Example: 0.0034 -0.80 456.89 +456.09
These numbers are decimal notation, having whole number followed by a decimal point and the
fractional part. It is possible to omit digits before the decimal part, or digits after the decimal part.
A real number may be expressed in exponential notation.
Mantissa e exponent
The mantissa is either a real number expressed in decimal notation or integer. The exponent is an
integer number with an optional + or – sign. The letter e can be written in either uppercase or
lowercase. Embedded white space is not allowed. The e notation is called floating-point form.
Floating point constants are represented as double-precision quantities. f or F may be used for Single
precision, l or L for Double-precision.
Valid real numbers: 78688L, 25636l, 444.643f, 321.55F, 2.5e+05, 374e-04
Invalid real numbers: 1.5E+0.5, $25, ox7B, 7.5 e -0.5, 1,00,00.00
Single Character Constants: A single character constants contains a single character enclosed
within a pair of single quote marks.
Example: ’5’ ‘X’ ‘;’ ‘’
Note: Character constant 5 is not same as number 5. The last constant is a blank space.
Character constants have integer values known as ASCII values.
Example: printf(“%d”, ‘a’);
prints number 97, the ASCII value of the letter a.
printf(“%c”, 95);
the above printf statement prints the letter a.

Pragati Engineering College (Autonomous) Page 18


Programming for Problem Solving using C (R20)
String Constants: A string constant is a sequence of characters enclosed in double quotes. The
characters may be letters, numbers, special characters and blank space.
Example: “Hello!” “1987” “?….!” “6+4” “X”
Note: 1. Character constant example X is not equivalent to string constant X.
2. A single character string constant does not have an equivalent integer value while a character
constant has an integer value.

Backslash character constants: Backslash character constants are used in output functions and each
one of them represents one character. These characters combinations are known as escape sequences.
Constant Meaning
‘\a’ Audible Alert (Bell)
‘\b’ Backspace
‘\f’ Formfeed
‘\n’ New Line
‘\r’ Carriage Return
‘\t’ Horizontal tab
‘\v’ Vertical Tab
‘\” Single Quote
‘\”‘ Double Quote
‘\?’ Question Mark
‘\\’ Back Slash
‘\0’ Null

INPUT/OUTPUT
The three essential functions of a computer are reading, processing, and writing data. Most C
programs take data as input, and then after processing, the processed data is displayed, which is called
information. To read and print data, you can use the predefined functions scanf() and printf() in C
programs.
In C, data is input to and output from a stream. A stream is a source or destination for data. It is
associated with a physical device such as terminal or with a file stored in RAM.
C uses two forms of streams: text and binary. A text stream consists of sequence of characters
divided into lines with each line terminated by a new line (\n). A binary stream consists of sequence
of data values such as integer, real, or complex using memory representation.
A terminal keyboard and monitor can be associated with text stream. A keyboard is source and
monitor is a destination for text stream.

Pragati Engineering College (Autonomous) Page 19


Programming for Problem Solving using C (R20)

#include <stdio.h>
void main()
{
int a, b, c;
printf("Enter any two numbers: \n");
scanf("%d %d", &a, &b);
c = a + b;
printf("The addition of two number is: %d", c);
}
Output: Enter any two numbers: 12 3
The addition of two number is: 15
Managing Input/Output
I/O operations are helpful for a program to interact with users. C stdlib is the standard C library for
input-output operations. Two essential streams play their role when dealing with input-output
operations in C. These are:
1. Standard Input (stdin)
2. Standard Output (stdout)
Standard input or stdin is used for taking input from devices such as the keyboard as a data stream.
Standard output or stdout is used to give output to a device such as a monitor. For I/O functionality,
programmers must include the stdio header file within the program.
Formatted Input: It refers to input data that has been arranged in a specific format. This is possible
in C using scanf() function.
Syntax: scanf("control string", arg1, arg2, ..., argn);
The control string specifies field format in which data is to be entered and the arguments specify the
address of the locations where data is stored. Control string and arguments are separated by commas.
Example: scanf("%d%d",&a,&b);
%d used for integers
%f floats
%l long
%c character
Formatted output: The printf statement enables to control the alignment and spacing of print-outs
on the terminals.
Syntax: printf("control string", arg1, arg2,...argn);
Control string consists of 3 items
1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.

Pragati Engineering College (Autonomous) Page 20


Programming for Problem Solving using C (R20)
3. Escape sequences characters such as \n,\t,\b etc.
The control string indicates the number of arguments and their data type. The arguments arg1, arg2,
..., argn are the variables whose values are formatted and printed according to the specifications of
the control string. The arguments should match in number, order and tie with the format
specifications.
printf(“ The values are %c %d %f” , a, b, c);

In the above statement, character type data, integer type data and float type data of three variables
a, b, and c are displayed respectively.
Example 1: C Output
#include <stdio.h>
void main()
{
printf("C Programming"); // Displays the string inside quotations
}
Output: C Programming

Example 2: Integer Output


#include <stdio.h>
int main()
{
int a = 5;
printf("Number = %d", a);
return 0;
}
Output: 5

Example 3: float and double Output


#include <stdio.h>
void main()
{
float n1 = 13.5;
double n2 = 12.4;
printf("number1 = %f\n", n1);
printf("number2 = %lf", n2);
}
Output:
number1 = 13.500000
number2 = 12.400000

Example 4: Print Characters


include <stdio.h>
void main()
{
char chr = 'a';
printf("character = %c", chr);
}
Output: character =a

Example: Float and Double Input/Output


#include <stdio.h>
Pragati Engineering College (Autonomous) Page 21
Programming for Problem Solving using C (R20)
int main()
{
float num1;
double num2;

printf("Enter a number: ");


scanf("%f", &num1);
printf("Enter another number: ");
scanf("%lf", &num2);
printf("num1 = %f\n", num1);
printf("num2 = %lf", num2);
return 0;
}
Output: Enter a number: 12.523
Enter another number: 10.2
num1 = 12.523000
num2 = 10.200000
Note : Use %f and %lf format specifier for float and double respectively.
When a character is entered by the user in the above program, the character itself is not stored. Instead,
an integer value (ASCII value) is stored. And when we display that value using %c text format, the
entered character is displayed. If we use %d to display the character, it's ASCII value is printed.
Example: ASCII Value
#include <stdio.h>
int main()
{
char chr;
printf("Enter a character: ");
scanf("%c", &chr);
printf("You entered %c.\n",chr); // When %c is used, a character is displayed
printf("ASCII value is %d", chr); // When %d is used, ASCII value is displayed
return 0;
}
Output
Enter a character: g
You entered g.
ASCII value is 103.

Format Specifiers or Control Specifiers in C


The format specifiers are used in C for input and output purposes. Using this concept, the compiler
can understand that what type of data is in a variable during taking input using the scanf() function
and printing using printf() function. Here is a list of format specifiers.
Format Specifier Type
%c Character
%d Signed integer
%e or %E Scientific notation of floats
%f Float values
%g or %G Similar as %e or %E
%hi Signed integer (short)

Pragati Engineering College (Autonomous) Page 22


Programming for Problem Solving using C (R20)
%hu Unsigned Integer (short)
%i Unsigned integer
%l or %ld or %li Long
%lf Double
%Lf Long double
%lu Unsigned int or unsigned long
%lli or %lld Long long
%llu Unsigned long long
%o Octal representation
%s String
%u Unsigned int
%x or %X Hexadecimal representation
%n Prints nothing
%% Prints % character

SCOPE
A scope is simply life time of a defined variable throughout the program. In any programming is a
region of the program where a defined variable can have its existence and beyond that variable it
cannot be accessed. There are three places where variables can be declared in C programming
language − Inside a function or a block which is called local variables. The variables declared outside
of all functions are called global variables.
In the definition of function parameter which are called formal parameters.
Local Variables - Variables that are declared inside a function or block are called local variables.
They can be used only by statements that are inside that function or block of code. Local variables
are not known to functions outside their own.
Global Variables - Global variables are defined outside a function, usually on top of the program.
Global variables hold their values throughout the lifetime of your program and they can be accessed
inside any of the functions defined for the program.
A global variable can be accessed by any function.
Example 1: Program To Print Global Variable And Local Variable
#include <stdio.h>
int g = 10; //global variable declaration
main ()
{
int a= 20; // local variable declaration
printf ("value of g = %d\n", g);
printf ("value of a= %d\n", a);
}
Output: value of g = 10
value of a= 20

Example 2: Program To Use Global Variable


#include <stdio.h>
/* global variable
declaration */
int g = 10;
main ()
{
Pragati Engineering College (Autonomous) Page 23
Programming for Problem Solving using C (R20)
/* local variable declaration */
int a= 20,c;
c=a+g;
printf ("value of a = %d\n", a);
printf ("value of g = %d\n", g);
printf ("value of c = %d\n", c);
}
Output: value of a = 20
value of g = 10
value of c = 30

STORAGE CLASSES IN C
Storage classes in C are used to determine the lifetime, visibility, memory location, and initial value
of a variable. There are four types of storage classes in C
Storage Storage
Default Value Scope Lifetime
Classes Place
auto RAM Garbage Value Local Within function
Till the end of the main program
extern RAM Zero Global Maybe declared anywhere in the
program
Till the end of the main program, Retains
static RAM Zero Local
value between multiple functions call

register Register Garbage Value Local Within the function


 Automatic
 External
 Static
 Register

Automatic
 Automatic variables are allocated memory automatically at runtime.
 The visibility of the automatic variables is limited to the block in which they are defined.
 The scope of the automatic variables is limited to the block in which they are defined.
 The automatic variables are initialized to garbage by default.
 The memory assigned to automatic variables gets freed upon exiting from the block.
 The keyword used for defining automatic variables is auto.
 Every local variable is automatic in C by default.
Example 1
#include <stdio.h>
int main()
{
int a; //auto
char b;
float c;
printf("%d %c %f",a,b,c); // printing initial default value of automatic variables a, b, and c.
return 0;
}
Output: garbage garbagegarbage

Pragati Engineering College (Autonomous) Page 24


Programming for Problem Solving using C (R20)

Static
 The variables defined as static specifier can hold their value between the multiple function calls.
 Static local variables are visible only to the function or the block in which they are defined.
 A same static variable can be declared many times but can be assigned at only one time.
 Default initial value of the static integral variable is 0 otherwise null.
 The visibility of the static global variable is limited to the file in which it has declared.
 The keyword used to define static variable is static.

Example 1
#include<stdio.h>
static char c;
static int i;
static float f;
static char s[100];
void main ()
{
printf("%d %d %f %s",c,i,f); // the initial default value of c, i, and f will be printed.
}

Example 2
#include<stdio.h>
void sum()
{
static int a = 10;
static int b = 24;
printf("%d %d \n",a,b);
a++;
b++;
}
void main()
{
int i;
for(i = 0; i< 3; i++)
{
sum(); // The static variables holds their value between multiple function calls.
}
}
Output:
10 24
11 25
12 26
Register
 The variables defined as the register is allocated the memory into the CPU registers depending
upon the size of the memory remaining in the CPU.
 We cannot dereference the register variables, i.e., we cannot use &operator for the register
variable.
 The access time of the register variables is faster than the automatic variables.
 The initial default value of the register local variables is 0.
 The register keyword is used for the variable which should be stored in the CPU register. However,
it is compilers choice whether or not; the variables can be stored in the register.

Pragati Engineering College (Autonomous) Page 25


Programming for Problem Solving using C (R20)
 We can store pointers into the register, i.e., a register can store the address of a variable.
 Static variables cannot be stored into the register since we cannot use more than one storage
specifier for the same variable.

Example:
#include <stdio.h>
int main()
{
register int a; // variable a is allocated memory in the CPU register. The initial default value
of a is 0.
printf("%d", a);
}
Output: 0

Example:
#include <stdio.h>
int main()
{
register int a = 0;
printf("%u",&a); // This will give a compile time error since we can not access the address
of a register variable.
}

External
 The external storage class is used to tell the compiler that the variable defined as extern is declared
with an external linkage elsewhere in the program.
 The variables declared as extern are not allocated any memory. It is only declaration and intended
to specify that the variable is declared elsewhere in the program.
 The default initial value of external integral type is 0 otherwise null.
 We can only initialize the extern variable globally, i.e., we cannot initialize the external variable
within any block or method.
 An external variable can be declared many times but can be initialized at only once.
 If a variable is declared as external then the compiler searches for that variable to be initialized
somewhere in the program which may be extern or static. If it is not, then the compiler will show
an error.

Example 1
#include <stdio.h>
int main()
{
extern int a;
printf("%d",a);
}
Output
main.c:(.text+0x6): undefined reference to `a'
collect2: error: ld returned 1 exit status

Example 2
#include <stdio.h>
int a;
int main()
Pragati Engineering College (Autonomous) Page 26
Programming for Problem Solving using C (R20)
{
extern int a; // variable a is defined globally, the memory will not be allocated to a
printf("%d",a);
}

TYPE QUALIFIERS
Type qualifiers are the keywords used to modify the properties of variables. Using type
qualifiers, the properties of variables can be changed. The C programming language provides two
type qualifiers and they are as follows.
const
volatile
const type qualifier : The const type qualifier is used to create constant variables. When a
variable is created with const keyword, the value of that variable can't be changed once it is
defined. The keyword const is used at the time of variable declaration.
Syntax:
const datatype variableName;
When a variable is created with const keyword it becomes a constant variable. The value of the
constant variable can't be changed once it is defined. The following program generates error message
because we try to change the value of constant variable x.
Example
#include<stdio.h>
void main()
{
int i = 9 ;
const int x = 10 ;
i = 15 ;
x = 100 ; // creates an error
printf("i = %d\nx = %d", i, x ) ;
}
Output: [Error] assignment of read-only variable 'x'
volatile type qualifier : The volatile type qualifier is used to create variables whose values can't
be changed in the program explicitly but can be changed by any external device or hardware.
For example: The variable which is used to store system clock is defined as a volatile variable. The
value of this variable is not changed explicitly in the program but is changed by the clock routine of
the operating system.
Constant vs Volatile : The following table represents the constant against volatile

Constant Volatile
Constant variables are unchangable. Volatile variables are changable.
Constant variable can be created by using the Volatile variable can be created by using the
keyword const. keyword Volatile.
For example: const int i = 16 is the way of For example 1: volatile int j = 30, is the way
declaring and initializing constant variable. of declaring and initializingvolatile variable.
Constant variable can only be initialized at the
Volatile varibale can be initialized at anytime.
time of declaration.

Pragati Engineering College (Autonomous) Page 27


Programming for Problem Solving using C (R20)

By default, all variables are not constant. By default, all variables are volatile.
The const variable is otherwise known as Read The volatile variable is otherwise known as
Only Variable. Read/Write Variable.
Another way to achieve constant variable by the Another way to achieve volatile variable by
use of #define preprocessor directive e.g.) the use of nothing e.g.)
#define a 5. int a = 5 is volatile.

Constant Program Using Keyword


void main()
{
const int i = 16;
i = i + 1;
printf("The value of i = %d ",i);
}
Note: Variable i is constant here. Thus, incrementing its value by any number
is impossible throughout the entire program. So the above program will cause an error.
Constant Program Without Using Keyword
#include <stdio.h>
#definei 16
void main()
{
printf("The value of i = %d ",i);
}
The value of i = 16
Note: Variable i is constant here because we defined using preprocessor directive. Thus, incrementing
its value by any number is impossible throughout the entire program.
Volatile Program Using Keyword
#include <stdio.h>
void main()
{
volatile int j = 1;
j = j + 1;
printf("The value of j = %d ",j);
}
The value of j = 2
Note: Variable 'j' is declared as volatile variable. Thus, incrementing its value by any number
is possible throughout the entire program.
Volatile Program Without Using Keyword
#include <stdio.h>
void main()
{
int j = 1;
j = j + 1;
printf("The value of j = %d ", j);
}
The value of j = 2

Pragati Engineering College (Autonomous) Page 28


Programming for Problem Solving using C (R20)
Note: Variable 'j' is volatile because by default all variables are volatile. Thus, incrementing its value
by any number is possible throughout the entire program.
Side Effects
 A side Effect is an action that results from the evaluation of an expression.
 C first evaluates the expression on the right of the assignment operator and then places the value
in the left variable. Changing the value of the left variable is a side effect.
 x = 4;
 Expression has 3 parts:
 first, on the right of the assignment operator is a primary expression that has the value 4
 second, the whole expression(x=4) has a value of 4
 third, as a side effect, x receives the value 4
Example: x = x + 4
Assuming that x has the initial value of 3, the value of the expression on the right of the assignment
operator has a value 7.The whole expression also has the value of 7.And as a side effect,x receives
the value of 7
int x =3;
printf(“step 1– Value of x: %d\n”, x)
printf((“step 2 - Value of x =x + 4: %d\n”,x=x+4);
printf((“step 2 - Value of x now:%d\n”,x);

EXPRESSIONS: An Expression is a sequence of operands and operators that reduces toa single
value. An expression is a simple or complex. An expression contains operator and operand. An
operator is a syntactical token that requires an action to be taken. An operand is an object on which
an operator is performed. An Expression always reduces to a single value.

Every expression consists of at least one operand and can have one or more operators. Operands are
either variables or values, whereas operators are symbols that represent particular actions. In the
expression x + 5; x and 5 are operands, and + is an operator.

In C programming, there are mainly expressions are in two forms. They are as follows:
1. Simple expression
2. Complex expression

Simple expression: An expression which contains one operator and two operands or constants.
Example: x+y;
3+5;
a*b;
x-y etc.

Complex expression: An expression which contains two or more operators and operands or
constants.
Example: x+y-z;
a+b-c*d;
2+5-3*4;
x=6-4+5*2 etc.

Pragati Engineering College (Autonomous) Page 29


Programming for Problem Solving using C (R20)
Expression Categories:

Fig: Expression Categories


Primary Expression: A primary Expression consists of only one operand with no operation. The
operand in a primary expression can be a name, constant or aparenthesized expression. A primary
expression is evaluated first in a complex expression.
Name: Name is any identifier for a variable, a function, or any other object .
Example: a b12 price calc INT_MAX SIZE

Literal Constant: A constant is a piece of data whose value can‘t change during the execution of the
program.
Example: 5 123.9 ‘A’ “Welcome”

Parenthetical Expressions: Any value enclosed in a parentheses must be reducible to a singlevalue


and is therefore a primary expression.
A complex expression enclosed with in parentheses to make a primaryexpression.
Example: (2*3+4) (a=23+b*6)

Postfix Expression: Postfix Expression consists of one operand followed by one operator. Some of
the operators that create a postfix expression are function call.
Function Call: Function calls are postfix expressions. The function name is the operand and the
operator is the parentheses that follow the name. The parentheses may contain arguments or be empty.
Ex: printf(“Hello World”); or printf( );
Postfix Increment/Decrement: Postfix increment and decrement are also postfix operators. Postfix
increment the variable by 1.
Example: int a=5, x;
x=a++; x=6;
Hear the effect of Postfix decrement the variable value is decremented by 1.
Ex: int a=5,x; x=a--; x=4;
Prefix Expressions: In prefix expression the operator comes before the operand. Similar to postfix
increment and decrement the prefix increment and decrement operators are shorthand notations for
adding or subtracting 1from the value.
Example: a function call
The function name is operand and the parenthesis is the operator. The other examples are post
increment and post decrement. In post increment the variable is increased by 1, a++ results in the

Pragati Engineering College (Autonomous) Page 30


Programming for Problem Solving using C (R20)
variable increment by 1. Similarly, in post decrement, the variable is decreased by 1, a—results in the
variable decreased by 1.

Prefix Expression: Prefix expression consists of one operand and one operator, the operand come
after the operator. Examples of prefix expressions are prefix increment and prefix decrement i.e ++a,
--a. The only difference between postfix and prefix operators is, in the prefix operator, the effect take
place before the expression that contains operators is evaluated. It is other way in case of post-fix
operations.
Example Postfix Increment:
int a=5,x;
x=a++; x=6;

Example Prefix Decrement:


int a=5,x;
x=a--; x=4;

Unary Expressions: An unary expression is like a prefix expression, consists of one operand and one
operator and the operand comes after the operator. Unary Expression can have an expression or
variable as the operand. Some of the Unary expressions are sizeof operator,
plus/minus operator and the cast operator.

Sizeof operator: The size of operator tells the size, in bytes, of a type or a primary expression. By
specifying the size of an object during execution, we make our program more portable to other
hardware.
Syntax : sizeof(type);

Unary plus/Minus: These two operators are used to compute the arithmetic value of an operand. The
plus operator does not change the value of an expression. The minus operator change the sign of a
value algebraically i.e., to change it from plus to minus and minus to plus.

Cast Operator: The cast operator converts one expression type to another.
Example to convert integer type to float we use cast operator.
float(x)

Binary Expressions: Binary Expressions are the Expressions which consists of two operands and an
operator. Any two variables are added, subtracted, multiplied and divided in a binary expression.
Ex: a+b; a-b; a*b; a/b; etc

Ternary Expression: Ternary Expressions are also called Conditional Expressions. Ternary
Expression is an expression which consists of a ternary operator pair “? :”
Ex: exp 1? exp 2: exp 3;
In the above example, if exp1 is true exp2 is executed else exp3 is executed.
Multiplicative Expressions:Name of the expression takes from the first operator , include the
multiply , divide , and modulus operator. These operators have the highest priority among
binary operators. Multiply operator is the product of the two operands.
Example: 10*3 //result=30
true*4 //result=4
‘A‘*2 //result=2
22.3 //result=44.6
The type of the result depends on the conversion rules.

Pragati Engineering College (Autonomous) Page 31


Programming for Problem Solving using C (R20)
- if both operands are Integers result is Integer.
-if any one of the operand is floating point the result is floating point.
-if both operands are floating point the result is floating point.

• The result of divide operator depends on the type of operand.


Example:
10/3 //result=3
true/4 //result=0
‘A‘/2 //result=32

• The modulus(%) operator divides the first operator by the second operator and returns the reminder
rather than quotient.
Example:
10%3 // result=1 true%4 // result=1
‘A‘ %10 // result=5
22.3%2 // result=Error because modulo can not be float.

• Both operands must be integral types and operator returns the remainder as an integer type.
• In this type of Expressions the second operand is added to or subtracted from the first operand,
depending on the operator used.
Example:
3+7 // result=10
3-7 // result=-4

Assignment Expressions
• The assignment expression evaluates the operand on the right side of the operator(=) and places
its value in the variable on the left.
• The assignment expression has a value and a side effect.
• The value of the total expression is the value of the expression on the right of the assignment
operator(=).
• The side effect places the expression value in the variable on the left of the assignment operator.
• There are two forms of Assignment Expressions:
1.Simple
2.Compound

1. Simple Expressions
• Simple assignment is found in algebraic expressions. Example: a=5 ; b=x+1 i=i+1
• The left variable must be able to receive the effect.
• That is it must be a variable , not a constant.
• If the left operand cannot receive a value and we assign a value we get a compile time error.
2. Compound Assignment
• A compound assignment is a shorthand notation for a simple assignment.
• It requires that the left operand be repeated as a part of the right expression.
• To evaluate the compound expression first change it to simple expression.
•The left operand in an assignment expression must be a single variable.

Pragati Engineering College (Autonomous) Page 32


Programming for Problem Solving using C (R20)

Fig: Expansion of Compound Expressions


Example: x*=y+3 evaluated as x=x*(y+3).

PRECEDENCE AND ASSOCIATIVITY


Precedence: To determine the order in which different operators in a complex expression are
evaluated.
Example 1: 2+3*4 is evaluated as (2+(3*4)) =(2+12)=14.
In the above example + having the precedence 12 and * having the precedence 13 so first multiply
3*4 then add 2+12.
Example 2: -6++ is evaluated as (-(6++))=-7.

Associativity : Associativity is applied when we have more than one operator of the same precedence
level in an expression. Associativity is used when two operators of same precedence appear in an
expression.
There are various levels of ‘precedence’. This precedence is especially used to determine to
 Evaluation of expression which has more than one operator in it.
 The operators which have higher precedence are executed first and vice-versa.
 Operators which have same precedence level are evaluated from left to right.
 It is dependent on its level. This feature is well known as ‘Associativity’ of an operator.
 Associativity can be left-to-right or right-to-left.
• Left-to-right associativity evaluates the expression by starting on the left and moving to the right.
• Right-to-left associativity evaluates the expression by proceeding from the right to left.
 Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example, the
multiplication operator has a higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher precedence
than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear
at the bottom. Within an expression, higher precedence operators will be evaluated first.

Example : 3 * 8 / 4 % 4 * 5
((((3*8)/4)%4)*5) value is 10.

Category Operator Associatively


Postfix () [] -> . ++ - - Left to right
Unary + - ! ~ ++ - - (type)* &sizeof Right to left
Multiplicative * / % Left to right

Pragati Engineering College (Autonomous) Page 33


Programming for Problem Solving using C (R20)

Additive + - Left to right


Shift <<>> Left to right
Relational <<= >>= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

Example: operator precedence


#include <stdio.h>
main()
{
int a = 20;
int b = 10;
int c = 15;
int d = 5;
int e;
e=(a +b) *c/ d; // ( 30 * 15 ) / 5

printf("Value of (a + b) * c / d is : %d\n",e );
e=((a+b) * c) / d; // (30 * 15 )/ 5

printf("Value of ((a + b) * c) / d is: %d\n" ,e );


e = (a + b) * (c / d); // (30) * (15/5)

printf("Value of (a + b) * (c / d) is: %d\n",e );


e=a+(b *c) / d; //20 + (150/5)

printf("Value of a + (b * c) / d is: %d\n" ,e );


return0;
}
Output:
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is: 0
Value of (a + b) * (c d) is: 90
Value of a+(b*c) / d is: 5

Pragati Engineering College (Autonomous) Page 34


Programming for Problem Solving using C (R20)
Side Effects: A side effect is an action that results from the evaluation of an expression. C language
evaluates the expression from right of the assignment operator and place result in left variable.
Changing the value of left variable is a side effect.
Example: x=x+3 expression has three parts . Assume x=3
1. The value of right of the right of the assignment operator is 6
2. The value of whole expression is also 6
3. The side effect x receives the value 6.

In C language six operators generate side effect.


– prefix increment and decrement
– postfix increment and decrement
– Assignment
– Function call

Expressions With no Side Effects


Example:
1. a*4+b/2–c*b
Assume the values for a=3 , b=4 , c=5 Substitute the values in the Expression
3*4+4/2–5*4
Evaluate expression based on their precedence
(3 * 4) + (4 / 2) – (5 * 4)
12 + 2 - 20
the value is -6.
In the above expression there is no side effect , all the variables have the same value after the
expression has been evaluated.

Expression With Side Effects


Example:
1. --a * (3 + b) / 2 – c++ * b Assume the values a=3 , b=4 , c=5
calculate the value of Parenthesized expression first
--a * 7 / 2 – c++ * b
--a * 7 / 2 – 5 * b
2*7/2–5*b
14 /2 – 5 * b
7–5*4
7 – 20
-13
Note: After the side effect the variables have the value

Typecasting:
Converting one type of data to another type of data is called type conversion.
There are two types of Conversions.
1. Implicit type conversion
2. Explicit Type Conversion

Implicit Type Conversion


• When the two types of a binary expression are different then the c compiler automatically converts
one type to another. This is known implicit type casting.
• We can assign the conversion ranks to the integral and floating point arithmetic types.
Pragati Engineering College (Autonomous) Page 35
Programming for Problem Solving using C (R20)
• A long double real has a higher rank than a long.

Conversion in Assignment Statements : In a simple assignment expression involve an assignment


operator and two operands. Depending on the rank of right expression the left variable takes
promotion or demotion. Promotion occurs if the right expression has lower rank. Demotion occurs
if the right expression has higher rank.
Syntax: (type) value;

Fig: Conversion Rank

Promotion: The rank of the right expression is evaluated to the rank of the left variable. The val;ue
of the expression is the value of the right expression after promotion.

Example:
bool b = true;
char char c=’A‘;
int i =1234;
long double d=3456.2345;

i=c; //value of i is 65
d=b; // value of d is 1.0
d=i // value of d is 1234.0

Demotion: If the right expression having the higher rank than the left variable then the right
expression value is demoted to the left variable.
• When the integer or real is stored into a char , the least significant byte is converted to a char and
stored.
• When a real is stored in a int the fraction part is dropped.

Example:
bool b= false;
char c='A‘;
int k=65;
b=c; // value of b is 1(true)
c=k+1; // value of c is B.

Explicit Type Conversion: In Explicit type conversion the programmer convert data from one
type to another. It uses Unary cast operator to convert the data from one type to another , specify the
new type in parentheses before the value to be converted.
Ex:

Pragati Engineering College (Autonomous) Page 36


Programming for Problem Solving using C (R20)
int a;
float f=(float) a;
Example 1: C program to demonstrate explicit type casting
#include<stdio.h>
main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
printf("sum = %d", sum);
}
Output: Sum=2

Example 2: C program to demonstrate explicit type casting


#include<stdio.h>
int main()
{
float a = 1.2;
//int b = a; //Compiler will throw an error for this
int b = (int)a + 1;
printf("Value of a is %f\n", a);
printf("Value of b is %d\n",b);
return 0;
}
Output: Value of a is 1.200000
Value of b is 2

Command Line Arguments: Command line arguments are the arguments specified after the
program name in the operating system's command line, and these arguments values are passed
to your program at the time of execution from your operating system. command-line arguments
are given after the name of a program in command-line operating systems like DOS or Linux,

The arguments passed from command line are called command line arguments. These arguments are
handled by main() function.

Syntax: int main(int argc, char *argv[] )


Here, argc counts the number of arguments. It counts the file name as the first argument.
The argv[] contains the total number of arguments. The first argument is the file name always

Components of Command Line Arguments : There are 2 components of Command Line Argument in
C:
1. argc: It refers to “argument count”. It is the first parameter that we use to store the number of
command line arguments. It is important to note that the value of argc should be greater than or
equal to 0.
2. agrv: It refers to “argument vector”. It is basically an array of character pointer which we use to
list all the command line arguments.

argv[0] stores the name of your program always


argv[1] gets the pointer to the 1st command line argument that has been supplied by the user,
*argv[n] denotes the last argument of the list.

Pragati Engineering College (Autonomous) Page 37


Programming for Problem Solving using C (R20)

Example: Command line arguments where we are passing one argument with file name.
#include <stdio.h>
int main( intargc, char *argv [] )
{
printf(" \n Name of my Program %s \t", argv[0]);
if( argc == 2 )
{
printf("\n Value given by user is: %s \t", argv[1]);
}
else if( argc> 2 )
{
printf("\n Many values given by users.\n");
}
else
{
sprintf(" \n Single value expected.\n");
}
}
Output:
Name of my Program D:\commandlineexample.exe
Single value expected.
C:\Users\91988>d:
D:\>commandlineexample.exe
Name of my Program commandlineexample.exe
Single value expected.
D:\>commandlineexample.exe first
Name of my Program commandlineexample.exe
Value given by user is: first
D:\>commandlineexample.exe first second
Name of my Program commandlineexample.exe
Many values given by users.

D:\>commandlineexample.exe first second third


Name of my Program commandlineexample.exe
Many values given by users.

D:\>commandlineexample.exe "first"" second ""third"


Name of my Program commandlineexample.exe
Many values given by users.

Pragati Engineering College (Autonomous) Page 38


Programming for Problem Solving using C (R20)
PREVIOUS YEAR QUESTIONS FROM UNIT -I
1. Differentiate Variables, Constants and Keywords?
2. Explain the basic structure of C program and explain the significance of each section?
3. How do you write and run C programs? Explain with an example?
4. List and explain basic data types with their sizes and ranges?
5. Explain about various number systems used for storing numbers in memory? Explain any two
systems in detail?
6. Define key word in C. Explain any two key words with examples?
7. Explain about different storage classes?
8. Explain about Command Line Arguments?
9. Define Type conversion. Illustrate the types of type conversions with example?
10. Write a program in C to print the numbers from 1 to10 and their squares?
11. Which of the following are valid identifiers in C? If not valid state the reason?
(i)@abc (ii)4xyz (iii) abc_x (iv)_ (v) a4b (vi)for (vii) 11
12. Explain the structure of a C program with an example?

Assignment 1
Bloom’s
Q.No. Questions CO
Taxonomy Level
SET - 1
Explain about various number systems used for storing
1 K2 CO1
numbers in memory? Explain any two systems in detail?
2 Elaborate on the data types defined in C Language? K2 CO1
Write a C program to swap two numbers by reading two
3 K3 CO1
numbers.
SET - 2
Explain the basic structure of C program and explain the
1 K3 CO1
significance of each section?
Define key words in C. Explain any two key words with
2 K3 CO1
examples?
3 Explain the usage of various storage classes? K2 CO1
SET - 3
How do you write and run C programs? Explain with an
1 K3 CO1
example?
2 What is type conversion? Explain with example? K2 CO1

3 Differentiate Variables, Constants? With Example K3 CO1

Pragati Engineering College (Autonomous) Page 39


Programming for Problem Solving using C (R20)
UNIT - II
Operators: An operator is a symbol used to perform mathematical and logical operations in a
program. Operators are used in program to manipulate data and variables. That means an operator is
a special symbol that tells to the compiler to perform mathematical or logical operations.
C operators can be classified as follows.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators

Expression: An expression is a sequence of operands and operators that reduces to a single value.
Example: 10 + 15 = 25
Arithmetic Operators: The operators +, -, *, /, and % are arithmetic operators that are used to
perform basic mathematical operations like addition, subtraction, multiplication, division and modulo
division. The following table provides information about arithmetic operators.

Operator Meaning Example


+ Addition or unary plus a+b
- Subtraction or unary minus a-b
* Multiplication a*b
/ Division a/b
% Modulo Division a%b

 In the above table, a and b are known as operands.


 The arithmetic operators can operate on any built-in data type allowed in C.
 The unary operator multiplies its single operand by -1.Therefore, a number preceded by minus
sign changes its sign.
 Integer division truncates any fractional part.
 The modulo division % produces the remainder of an integer division. The modulo division
cannot be used on floating point data.
 The addition operator can be used with numerical data types and character data type. When it is
used with numerical values, it performs mathematical addition and when it is used with character
data type values, it performs concatenation (appending).
NOTE: C does not have an operator for exponentiation.

Integer Arithmetic: When both the operands in a single arithmetic expression such as a + b are
integers, the expression is called integer arithmetic. The integer arithmetic always gives an integer
value.
Example:
a – b = 10

Pragati Engineering College (Autonomous) Page 40


Programming for Problem Solving using C (R20)
a + b = 15
a * b = 30
a / b = 3 (decimal part truncated)
a % b = 2 (remainder of a division)

Example:
#include <stdio.h>
int main()
{
int a=40, b=20, add, sub, mul, div, mod;
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf("Addition of a, b is : %d\n", add);
printf("Subtraction of a, b is : %d\n", sub);
printf("Multiplication of a, b is : %d\n", mul);
printf("Division of a, b is : %d\n", div);
printf("Modulus of a, b is : %d\n", mod);
}
OUTPUT:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0

EXAMPLE:
#include<stdio.h>
main()
{
int months, days;
printf(“Enter days:”);
scanf(“%d”, &days);
months =days/30;
days=days%30;
printf(“Months = %d Days = %d”, months, days);
}
OUTPUT:
Enter days: 265
Months = 8 Days = 25

Real Arithmetic: An arithmetic operation involving only real operands is called real arithmetic.
Example: 2.45 + 6.824
Note: Operator % cannot be used with real operands.

Pragati Engineering College (Autonomous) Page 41


Programming for Problem Solving using C (R20)

Mixed-mode Arithmetic: When one of the operands is real and other is integer, the expression is
called a Mixed-mode Arithmetic. If either operand is of the real type, then only real operation is
performed and the result is always a real number.
Example: 15/10.0 = 1.5
whereas 15/10 = 1

RELATIONAL OPERATORS: The relational operators <, >, <=, >=, ==, != are the symbols that
are used to compare the value of two expressions depending on their relation. Expression that contain
relational operator is called relational expression. Every relational operator has two results TRUE or
FALSE. In simple words, the relational operators are used to define conditions in a program.
NOTE: Relational operators are used in decision making and loops.
Operator Meaning Example Return value
< is less than 2<9 1
<= is less than or equal to 2<=2 1
> is greater than 2>9 0
>= is greater than or equal to 3>=2 1
== is equal to 2==3 0
!= is not equal to 2!=2 0
EXAMPLE:
#include <stdio.h>
int main()
{
int a = 5, b = 5, c = 10;
printf("%d == %d = %d \n", a, b, a == b); // true
printf("%d == %d = %d \n", a, c, a == c); // false
printf("%d > %d = %d \n", a, b, a > b); //false
printf("%d > %d = %d \n", a, c, a > c); //false
printf("%d < %d = %d \n", a, b, a < b); //false
printf("%d < %d = %d \n", a, c, a < c); //true
printf("%d != %d = %d \n", a, b, a != b); //false
printf("%d != %d = %d \n", a, c, a != c); //true
printf("%d >= %d = %d \n", a, b, a >= b); //true
printf("%d >= %d = %d \n", a, c, a >= c); //false
printf("%d <= %d = %d \n", a, b, a <= b); //true
printf("%d <= %d = %d \n", a, c, a <= c); //true
return 0;
}
Output
5 == 5 = 1
5 == 10 = 0
5>5=0
5 > 10 = 0
5<5=0
5 < 10 = 1
5 != 5 = 0
5 != 10 = 1
Pragati Engineering College (Autonomous) Page 42
Programming for Problem Solving using C (R20)
5 >= 5 = 1
5 >= 10 = 0
5 <= 5 = 1
5 <= 10 = 1

Logical Operators: The logical operators &&, ||, ! are the symbols that are used to combine the
results of two or more conditions. Logical operators are commonly used to test more than one
condition and make decisions. An expression containing logical operator returns either 0 or 1
depending upon whether expression results true or false.
Example: a > b && x ==10

Operator Meaning Example Return value


&& Logical AND (9>2)&&(17>2) 1
|| Logical OR (9>2) || (17 = = 7) 1
! Logical NOT 29!=29 0

 Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions is FALSE
then complete condition becomes FALSE.
 Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions is TRUE
then complete condition becomes TRUE.

Logical AND (&&) : If any one condition false the complete condition becomes false.
exp1 exp2 exp1&&exp2
T T T
T F F
F T F
F F F

Logical OR (||) : If any one condition true the complete condition becomes true.
exp1 exp2 exp1||exp2
T T T
T F T
F T T
F F F

Logical NOT(!) : This operator reverses the value of the expression it operates on i.e, it makes a
true expression false and false expression true.
exp1 !exp2
true false
false true

Operator Description Example a=10,b=20,c=30 output


&& logical AND (a>b)&&(a<c) (10>20)&& 0
|| logical OR (a>b)||(a<c) (10>20)||(10<30) 1
! logical NOT !(a>b) ! (10>20) 1

Pragati Engineering College (Autonomous) Page 43


Programming for Problem Solving using C (R20)
Relative precedence of the relational and Logical operator
Highest !
> >= < <=
== !=
&&
Lowest ||

Example Program
main ()
{
int a=10, b =20, c=30;
printf(“%d”,(a>b) &&(a<c));
printf(“%d”,(a>b)||(a<c));
printf(“%d”, !(a>b));
}
Output
0
1
1

Example 2:
#include stdio.h>
void main()
{
int a = 5, b = 5, c = 10, result;

result = (a == b) && (c > b);


printf("(a == b) && (c > b) equals to %d \n", result);

result = (a == b) && (c < b);


printf("(a == b) && (c < b) equals to %d \n", result);

result = (a == b) || (c < b);


printf("(a == b) || (c < b) equals to %d \n", result);

result = (a != b) || (c < b);


printf("(a != b) || (c < b) equals to %d \n", result);

result = !(a != b);


printf("!(a == b) equals to %d \n", result);

result = !(a == b);


printf("!(a == b) equals to %d \n", result);
}
Output:
(a == b) && (c > b) equals to 1
(a == b) && (c < b) equals to 0
(a == b) || (c < b) equals to 1

Pragati Engineering College (Autonomous) Page 44


Programming for Problem Solving using C (R20)
(a != b) || (c < b) equals to 0
!(a != b) equals to 1
!(a == b) equals to 0

Assignment Operators: Assignment operators are used to assign a value (or) an expression (or) a
value of a variable to another variable.
Syntax : variable name=expression (or) value (or) variable
Example : x=10;
y=a+b; z=p;

Compound assignment operator: “C” provides compound assignment operators to assign a value
to variable in order to assign a new value to a variable after performing a specified operation.
Operator Example Meaning
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y X=x%y

// C Program to demonstrate the working of assignment operators


#include <stdio.h>
int main()
{
int a = 5, c; c = a;
printf("c = %d \n", c);
c += a; // c = c+a
printf("c = %d \n", c);
c -= a; // c = c-a
printf("c = %d \n", c);
c *= a; // c = c*a
printf("c = %d \n", c);
c /= a; // c = c/a
printf("c = %d \n", c);

c %= a; // c = c%a
printf("c = %d \n", c);
return 0;
}
Output:
c=5
c = 10
c=5
c = 25
c=5
c=0

Pragati Engineering College (Autonomous) Page 45


Programming for Problem Solving using C (R20)

Assignment Operators: The assignment operators =, +=, -=, *=, /=, %= are used to assign right
hand side value (RHS value) to the left hand side variable (LHS value). The assignment operator is
used in different variants along with arithmetic operators (compound assignment operators). The
following table describes all the assignment operators in C programming language.

Operator Meaning Example


= Assign the right hand side value to left hand side variable A = 15
Add both left and right hand side values and store the result into left A += 10
+=
hand side variable ⇒ A=A+10
Subtract right hand side value from left hand side variable value and A -= B
-=
store the result into left hand side variable ⇒ A=A-B
Multiply right hand side value with left hand side variable A *= B
*=
value and store the result into left hand side variable ⇒ A=A*B
Divide left hand side variable value with right hand side variable A /= B
/=
value and store the result into left hand side variable ⇒ A=A/B
Divide left hand side variable value with right hand side variable A %= B
%=
value and store the remainder into left hand side variable ⇒ A=A%B
Statement with simple Statement with short
assignment operator hand operator
a=a+1 a+=1
a=a– 1 a-=1
a=a* (n+1) a*=(n+1)
a=a/ (n+1) a/= (n+1)
a=a%b a%=b
Example:
#include<stdio.h>
void main ()
{
int a, b=3; a = b;
a+=10; // equivalent to a=a+10
printf("\n a is %d ", a);
}
Output:
a is 13

// C Program to demonstrate the working of Assignment operators:


#include <stdio.h>
int main()
{
int a = 21,c;
c = a;
printf("Operator is = and c = %d\n", c );
c += a;
printf("Operator is += and c=%d\n",c);
c -= a;
printf("Operator is -= and c=%d\n",c);
Pragati Engineering College (Autonomous) Page 46
Programming for Problem Solving using C (R20)
c *= a;
printf("Operator is *= and c=%d\n",c);
c /= a;
printf("Operator is /= and c=%d\n", c);
c = 200;
c %= a;
printf("Operator is %= and c=%d\n",c);
c <<= 2;
printf("Operator is <<= and c=%d\n",c);
c >>= 2;
printf("Operator is >>= and c=%d\n",c);
c &= 2;
printf("Operator is &= and c = %d\n", c );
c ^= 2;
printf("Operator is ^= and c = %d\n", c );
c |= 2;
printf("Operator is |= and c = %d\n", c );
return 0;
}
Output:
Operator is = and c = 21
Operator is += and c=42
Operator is -= and c=21
Operator is *= and c=441
Operator is /= and c=21
Operator is = and c=11
Operator is <<= and c=44
Operator is >>= and c=11
Operator is &= and c = 2
Operator is ^= and c = 0
Operator is |= and c = 2

Increment and Decrement Operators: The increment and decrement operators are called as unary
operators because, both needs only one operand. The increment operator (++) add one to the existing
value of the operand and the decrement operator (--) subtracts one from the existing value of the
operand.
1. Increment operator is used to increment the current value of variable by adding integer 1.
2. Increment operator can be applied to only variables.
3. Increment operator is denoted by ++.
4. The increment and decrement operators are used extensively in for and while loops.

There are two types of increment operators: Pre-Increment and Post-Increment Operator.

Pre-Increment: Pre-increment operator is used to increment the value of variable before using in
the expression. In the Pre-Increment value is first incremented and then used inside the expression.
Example: b = ++y;

In this example suppose the value of variable “y” is 5 then value of variable “b” will be 6 because
the value of “y” gets modified before using it in a expression.

Post-Increment: Post-increment operator is used to increment the value of variable as soon as after

Pragati Engineering College (Autonomous) Page 47


Programming for Problem Solving using C (R20)
executing expression completely in which post increment is used. In the Post-Increment value is first
used in a expression and then incremented.
Example: b = x++;

In this example suppose the value of variable “x” is 5 then value of variable “b” will be 5 because
old value of “x” is used.

Note: We cannot use increment operator on the constant values because increment operator operates
on only variables. It increments the value of the variable by 1 and stores the incremented value back
to the variable

b = ++5; or b = 5++;
Operator Meaning Example
int a = 5; a++;
++ Increment - Adds one to existing value
⇒a=6
int a = 5; a--;
-- Decrement - Subtracts one from existing value
⇒a=4
Operator Meaning
++x Pre increment
- -x Pre decrement
x++ Post increment
x-- Post decrement

Where
1: ++x : Pre increment, first increment and then do the operation.
2: --x : Pre decrement, first decrements and then do the operation.
3 : x++ : Post increment, first do the operation and then increment.
4 : x- - : Post decrement, first do the operation and then decrement.

// C Program to demonstrate the working of pre-increment operator


#include <stdio.h>
void main()
{
int i = 5,j;
j=++i; // Pre-Increment
printf("i = %d, j =%d",i,j);
}
Output:
i = 6, j = 6

// C Program to demonstrate the working of post-increment operator


#include <stdio.h>
void main()
{
int i = 5,j;
j= i++; // Post-Increment
printf("i = %d, j =%d",i,j);
}
Output:
i = 6, j = 5
Pragati Engineering College (Autonomous) Page 48
Programming for Problem Solving using C (R20)

// C Program to demonstrate the working of increment and decrement operators


#include <stdio.h>
int main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d \n", ++a);
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
return 0;
}
Output:
++a = 11
--b = 99
++c = 11.500000
++d = 99.500000

// C Program to demonstrate the working of Multiple increment operators inside printf


#include<stdio.h>
void main()
{
int i = 1;
printf("%d %d %d", i, ++i, i++);
}
Output : 3 3 1

Pictorial representation

Explanation of program :
1. Whenever more than one format specifiers (i.e., %d) are directly or indirectly related with same
variable (i,i++,++i) then we need to evaluate each individual expression from right to left.
2. As shown in the above image evaluation sequence of expressions written inside printf will be –
i++,++i, i.
3. After execution we need to replace the output of expression at appropriate place.

No Step Explanation
1 Evaluate i++ At the time of execution we will be using older value of i = 1

Pragati Engineering College (Autonomous) Page 49


Programming for Problem Solving using C (R20)
At the time of execution we will be increment value already modified
2 Evaluate ++i
after step 1 i.e i = 3
3 Evaluate i At the time of execution we will be using value of i modified in step 2

// C Program to demonstrate the working of Postfix and Prefix Expression in Same Statement
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 0, j = 0; j = i++ + ++i;
printf("%d\n", i);
printf("%d\n", j);
}
Output :
2
2

Explanation of Program

Unary Operators: Unary operators are having higher priority than the other operators. Unary
operators, meaning they only operate on a single operand. C language supports three unary
operators. They are:
1. Unary minus
2. Increment operator
3. Decrement operator

Unary minus: The unary minus operator returns the operand multiplied by –1, effectively changing
its sign. When an operand is preceded by a minus sign, the unary minus operator negates its value.
Example:
int a, b=10; a=-(b);
Output: a=-10.

Pragati Engineering College (Autonomous) Page 50


Programming for Problem Solving using C (R20)
Conditional Operator/ Ternary operator: Conditional operator checks the condition and executes
the statement depending on the condition. A conditional operator is a ternary operator, that works on
3 operands. Conditional operator consists of two symbols.
1. question mark (?).
2. colon ( : ).
Syntax: condition ? exp1 : exp2;

It first evaluate the condition, if it is true (non-zero) then the “exp1” is evaluated, if the condition is
false (zero) then the “exp2” is evaluated.
// C Program to demonstrate the working of Conditional Operator
#include <stdio.h>
int main()
{
int a=10, b=20,x;
x=(a>b)?a:b;
printf("x = %d",x);
return 0;
}
Output: x=20
Note: This is achieved using if...else statement
if(a>b)
x=a;
else
x=b;

Bitwise Operators: Bitwise operators are used to manipulate the data at bit level. To perform bit-
level operations in C programming, bitwise operators are used. It operates on integers only. It may
not be applied to float. C has two categories of bitwise operators that operate on data at bit level.
1. Logical bitwise operators
2. Shift bitwise operators
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
<< Shift left
>> Shift right
~ One’s complement.

1. Logical bitwise operators: Logical bitwise operators consider data as individual bits to ne
manipulated. They are four bitwise operators bitwise and(&),bitwise or(|) bitwise exclusive or(^) and
one’s compliment (~).
Bitwise AND operator &: The bitwise and is a binary operator that requires two integral operands
(character or integer). The output of bitwise AND is 1 if the corresponding bits of two operands is
1. If either bit of an operand is 0, the result of corresponding bit is evaluated to 0. The truth table for
bitwise and is as follows.

Pragati Engineering College (Autonomous) Page 51


Programming for Problem Solving using C (R20)

Op1 Op2 OP1 & OP2


0 0 0
0 1 0
1 0 0
1 1 1
Example: 12 = 00001100 (In Binary) 25 = 00011001 (In Binary).
Bit Operation of 12 and 25 is 00001100 & 00011001 = 00001000 = 8 (In decimal)

// C Program to demonstrate the working of Bitwise AND


void main()
{
int a = 12, b = 25;
printf("Output = %d", a&b);
return 0;
}
Output =8

Bitwise OR operator |: The bitwise OR is a binary operator that requires two integral operands
(character or integer). The output of bitwise OR is 1 if at least one corresponding bit of two operands
is 1. In C Programming, bitwise OR operator is denoted by |. The truth table for bitwise or is as
follows.

Op1 Op2 OP1 | OP2


0 0 0
0 1 0
1 0 0
1 1 1
Example: 12 = 00001100 (In Binary), 25 = 00011001 (In Binary)
Bitwise OR Operation of 12 and 25 00001100| 00011001 = 00011101 = 29 (In decimal)

// C Program to demonstrate the working of Bitwise OR


#include <stdio.h>
void main()
{
int a = 12, b = 25;
printf("Output = %d", a|b);
}
Output: Output =29

Bitwise XOR (exclusive OR) operator ^: The bitwise exclusive OR is a binary operator that
requires two integral operands. The result of bitwise XOR operator is 1 if the corresponding bits of
two operands are opposite. It is denoted by ^. The truth table for bitwise exclusive OR is as
follows.

Pragati Engineering College (Autonomous) Page 52


Programming for Problem Solving using C (R20)

Op1 Op2 OP1 ^ OP2


0 0 0
0 1 1
1 0 1
1 1 0
Example: 12 = 00001100 (In Binary), 25 = 00011001 (In Binary)
Bitwise XOR Operation of 12 and 25 00001100 | 00011001= 00010101 = 21 (In decimal)

// C Program to demonstrate the working of Bitwise XOR


#include <stdio.h>
void main()
{
int a = 12, b = 25;
printf("Output = %d", a^b);
}
Output: 21

One’s complement operator ~: One’s compliment operator is an unary operator that works on only
one operand. It changes 1 to 0 and 0 to 1. It is denoted by ~. The truth table for One’s complement
operator is as follows.
Op1 ~ Op1
0 1
0 1
1 0
1 0

Example: 35 = 00100011 (In Binary)


Bitwise complement Operation of 35 is ~ 00100011 = 11011100 = 220 (In decimal)

Twist in bitwise complement operator in C Programming


The bitwise complement of 35 (~35) is -36 instead of 220.
This is because, for any integer n, bitwise complement of n will be -(n+1). To understand this, you
should have the knowledge of 2's complement.

2's Complement
Two's complement is an operation on binary numbers. The 2's complement of a number is equal to
the complement of that number plus 1. For example:
Decimal Binary 2's complement
0 00000000 -(11111111+1) = -00000000 = -0(decimal)
1 00000001 -(11111110+1) = -11111111 = -256(decimal)
12 00001100 -(11110011+1) = -11110100 = -244(decimal)
220 11011100 -(00100011+1) = -00100100 = -36(decimal)
Decimal Binary 2's complement

Note: Overflow is ignored while computing 2's complement.


The bitwise complement of 35 is 220 (in decimal). The 2's complement of 220 is -36. Hence, the

Pragati Engineering College (Autonomous) Page 53


Programming for Problem Solving using C (R20)
output is -36 instead of 220.

Bitwise complement of any number N is -(N+1). Here's how:


bitwise complement of N = ~N (represented in 2's complement form) 2'complement of ~N= -
(~(~N)+1) = -(N+1)

// C Program to demonstrate the working of Bitwise complement


#include <stdio.h>
main()
{
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; // 12 = 0000 1100
printf("Line 1 - Value of c is %d\n", c );
c = a | b; // 61 = 0011 1101
printf("Line 2 - Value of c is %d\n", c );
c = a ^ b; // 49 = 0011 0001
printf("Line 3 - Value of c is %d\n", c );
c = ~a; //-61 = 1100 0011
printf("Line 4 - Value of c is %d\n", c );
}
Output:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 4 - Value of c is -61

// C Program to demonstrate the working of Bitwise complement


#include <stdio.h>
int main()
{
printf("complement = %d\n",~35);
printf("complement = %d\n",~-12);
return 0;
}
Output:
Complement = -36
Complement = 11

2. SHIFT OPERATORS: There are two Bitwise shift operators in C programming:


• Right shift operator
• Left shift operator.

Left Shift Operator: Left shift operator is a binary operator that requires two integral operands
(character or integer). Left shift operator shifts all bits towards left by certain number of specified

Pragati Engineering College (Autonomous) Page 54


Programming for Problem Solving using C (R20)
bits. It is denoted by <<.
Syntax: Operand << n
Where, Operand is an integer expression on which we apply the left-shift operation. n is the number
of bits to be shifted.
Example:

Right Shift Operator: Right shift operator is a binary operator that requires two integral operands
(character or integer). Right shift operator shifts all bits towards right by certain number of specified
bits. It is denoted by >>.
Syntax: Operand >> n
Where, Operand is an integer expression on which we apply the right-shift operation. n is the number
of bits to be shifted.
Example:

// C Program to demonstrate the working of Shift Operators


#include<stdio.h>
int main()
{
unsigned char a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
printf("a<<1 = %d\n", a<<1); // The result is 00001010
printf("b<<1 = %d\n", b<<1); // The result is 00010010
return 0;
}
Output:
a<<1 = 10
b<<1 = 18

Special Operators: The following are the special operators in C programming language.
1. Comma Operator: The comma operator is used to separate the statement elements such as
variables, constants or expressions, and this operator is used to link the related expressions together,
Pragati Engineering College (Autonomous) Page 55
Programming for Problem Solving using C (R20)
such expressions can be evaluated from left to right and the value of right most expressions is the
value of combined expressions
Example : value = (a=3, b=9, c=77, a+c);
First signs the value 3 to a, then assigns 9 to b, then assigns 77 to c, and finally 80(3+77) to value.

2. Sizeof Operator : The sizeof() is a unary operator, that returns the length in bytes o the specified
variable, and it is very useful to find the bytes occupied by the specified variable in the memory.
Syntax : sizeof(variable-name);
int a;
Example: sizeof(a); //OUTPUT 2bytes

// C Program to demonstrate the working of sizeof Operator


#include <stdio.h>
int main()
{
int a, e[10]; float b; double c; char d;
printf("Size of int=%lu bytes\n", sizeof(a));
printf("Size of float=%lu bytes\n", sizeof(b));
printf("Size of double=%lu bytes\n", sizeof(c));
printf("Size of char=%lu byte\n", sizeof(d));
printf("Size of integer type array having 10 elements = %lu bytes\n", sizeof(e));
return 0;
}
Output:
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte
Size of integer type array having 10 elements = 40 bytes

Pointer operator(*): This operator is used to define pointer variables in c programming language.

Dot operator(.): This operator is used to access members of structure or union.

Points to be remembered on operators:


• Unary operator: It requires only one operand.
• Binary operator: It requires two operands like a+b, a-b,a*c etc.
• Logical operator: Used to compare two or more operands. Operands may be variable constants
or expression.
• Assignment operator: Used to combine the results of two or more statements.
• Conditional operator: Checks the condition and executes the statement depending on the
condition.
• Bitwise operator: Used to manipulate the data at bit level. It operates on integer only. It may not
be applied to float or real.

Pragati Engineering College (Autonomous) Page 56


Programming for Problem Solving using C (R20)

Pragati Engineering College (Autonomous) Page 57


Programming for Problem Solving using C (R20)
Selection and Making Decision:
A program is nothing but the execution of sequence of one or more instructions. Sometimes it is
desirable to alter the execution of sequence of statements in the program depending upon certain
circumstances. This involves decision making through branching and looping. Control statements
specify the order in which the various instructions in a program are to be executed by the computer.
i.e., they determine the ‘flow of control’ in a program. Various control statements in C are:

 One way Selection statement


 Two way Selection statement
 Multi way Selection statement
 Repetition or Loop control statements

One way Selection statement: The statement is executed if the value of the expression is true. One
way Selection is implemented using simple if statement.
simple if statement: The if statement is a powerful decision making statement and is used to control
the flow of execution of statements. C uses the keyword “if” to execute a set of statements or one
statements when the logical condition is true.
Syntax:
if(condition or expression)
{
Statements-block;
}
next statement;

In above syntax, the condition is checked first which allows the computer to evaluate the expression
first and then depending on the value of expression, the control transfers to the particular statement.
If the expression is true (non- zero value) then the statement-block is executed and next statement is
executed. If the expression is false (zero), directly next statement is executed without executing the
statement- block. Statement-block may be one or more statements. If more than one statement, then
keep all those statements in compound block({ }).
Flow Chart:

Note: Null else is also same as Simple if with else followed by ‘;’ (semi-colon) i.e. if followed by
else with no statements (null).
 Constructing the body of "if" statement is always optional, create the body when we are
having multiple statements.

Pragati Engineering College (Autonomous) Page 58


Programming for Problem Solving using C (R20)
 For a single statement, it is not required to specify the body.
 If the body is not specified, then automatically condition part will be terminated with next
semicolon(;).

// C Program to find a given number is greater than or equal to 4


#include <stdio.h>
void main()
{
int a=5;
if(a>4)
{
printf("\nValue of ‘a’ is greater than 4 !");
}
if(a==4)
{
printf("\n\n Value of ‘a’ is 4 !");
}
}

//A C program to check whether the given number is +ve or –ve using simple if statement.
#include<stdio.h>
void main()
{
int num;
printf("Enter a number:");
scanf("%d”, &num);
if(num>0)
{
printf(“%d is a positive number\n”, num);
}
}
Output: Enter a number: 9
9 is a positive number.

// C program to demonstrate Simple if statement


#include<stdio.h>
void main()
{
int no=0;
printf("Enter a number:");
scanf("%d",&no);
if(no%2==0)
{
printf("%d is even number",no);
}
}
Output: Enter a number: 4
4 is even number

Pragati Engineering College (Autonomous) Page 59


Programming for Problem Solving using C (R20)
// C Program to find the largest number of the three.
#include <stdio.h>
void main()
{
int a, b, c;
printf("Enter three numbers");
scanf("%d %d %d",&a,&b,&c);
if(a>b && a>c)
{
printf("%d is largest",a);
}
if(b>a && b > c)
{
printf("%d is largest",b);
}
if(c>a && c>b)
{
printf("%d is largest",c);
}
if(a == b && a == c)
{
printf("All are equal");
}
}
Output: Enter three numbers
12 23 34
34 is largest
TWO WAY SELECTION STATEMENT: Selection statements allow the computer to take a
decision as to which statement is to be executed next based on the answer either true or false. If the
answer is true, one or more statements are executed. If the answer is false, then different set of
statements are executed. Two way selection is implemented using
a) if – else b) nested if-else

a) if –else statement: Two way selection is implement in C using if …else statement. It is an


extension of simple if. It takes care of both the true as well as false conditions. It has two blocks. One
is for if and it is executed when the condition is true, the other block is for else and it is executed
when the condition is false. No multiple else statements are allowed with one if.
This is also one of the most useful conditional statements used in C to check conditions.
Syntax:
if(condition)
{
True statements; // if code
}
else
{
False statements; //else code
}
In above syntax, the condition is checked first. If it is true, then the program control flow goes inside

Pragati Engineering College (Autonomous) Page 60


Programming for Problem Solving using C (R20)
the braces and executes the block of statements associated with it. If it returns false, then it executes
the else part of a program.
Flow Chart:

else: It is a keyword, by using this keyword we can create an alternative block for "if" part. Using
else is always optional i.e., it is recommended to use when we are having alternate block of condi-
tion. In any program among if and else only one block will be executed. When if condition is false
then else part will be executed, if part is executed then automatically else part will be ignored.

// A C Program to find a given number is even or odd


#include <stdio.h>
void main()
{
int no;
printf("\n Enter Number :");
scanf("%d",&no);
if(no%2==0)
{
printf("\n\n Number is even !");
}
else
{
printf("\n\n Number is odd !");
}
}
Output:
Enter Number : 11
Number is odd !

// C Program to check whether a person is eligible to vote or not.


#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");

Pragati Engineering College (Autonomous) Page 61


Programming for Problem Solving using C (R20)

scanf("%d",&age);
if(age>=18)
{
printf("You are eligible to vote");
}
else
{
printf("Sorry ... you can't vote");
}
}
Output:
Enter your age: 18
You are eligible to vote
Enter your age:13
Sorry ... you can't vote

// C program to check whether the given year is leap or not using if..else statement.
#include<stdio.h>
void main()
{
int year;
printf("Enter any year:");
scanf("%d",&year);
if(year%4==0)
printf("%d is leap year\n", year);
else
printf("%d is non leap year\n", year);
}
Output: Enter any year: 1996
1996 is leap year.

Nested if-else Statement: It is a conditional statement which is used when we want to check more
than 1 condition at a time in a same program. The conditions are executed from top to bottom
checking each condition whether it meets the conditional criteria or not. If it found the condition is
true then it executes the block of associated statements of true part else it goes to next condition to
execute.
Syntax:
if(condition1)
{
if(condition2)
{
if condition1 and condition2 true statements; //statement1
}
else
{
if condition1 true and condition2 false statements; //statement2
Pragati Engineering College (Autonomous) Page 62
Programming for Problem Solving using C (R20)
}
}
else
{
Condition1 false statements; //statement3
}
In above syntax, the condition1 is checked first. If it is true, then the program control flow goes inside
the braces and again checks the next condition2. If it is true then it executes the block of statements
associated with it else executes else part.

// C Program to check the user credentials


#include <stdio.h>
void main()
{
char username;
int password;
printf("Username:");
scanf("%c",&username);
printf("Password:");
scanf("%d",&password);
if(username=='a')
{
if(password==12345)
{
printf("Login successful");
}
else
{
printf("Password is incorrect, Try again.");
}
}
else
{
printf("Username is incorrect, Try again.");
}
}

// C Program to find largest of three numbers


#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter a,b,c values:");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
{
Pragati Engineering College (Autonomous) Page 63
Programming for Problem Solving using C (R20)
if(a>c)
printf("%d is the big\n",a);
else
printf("%d is the big\n",c);
}
else
{
if(b>c)
printf("%d is the big\n",b);
else
printf("%d is the big\n",c);
}
return 0;
}
Output: Enter a,b,c values:
9
4
5
9 is the big

//C Program to find Roots of a Quadratic Equation


#include <math.h>
#include <stdio.h>
int main()
{
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);

discriminant = b * b - 4 * a * c;

if (discriminant > 0) // condition for real and different roots


{
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
else if (discriminant == 0) // condition for real and equal roots
{
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
else // if roots are not real
{
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);

Pragati Engineering College (Autonomous) Page 64


Programming for Problem Solving using C (R20)
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart,
realPart, imagPart);
}
return 0;
}
Output:
Enter coefficients a, b and c:
2.3
4
5.6
root1 = -0.87+1.30i and root2 = -0.87-1.30i

MULTI-WAY SELECTION: Multiway selection chooses among several alternatives. The decision
logic for multiway selection is shown below.

if-else if / else if ladder Statement: As if else statement are too complicated for humans to write
when they are nested more deeply. To reduce this complication of statements else if clause can be
used.
Syntax:
if(test expression1 is true)
statement1;
else if(test expression2 is true)
statement2;
else if(test expression3 is true)
statement3;
……..

It is combination of if else statement, at the start if test expression1 of if statement evaluates false,
then the program control moves downward till any of the else if statement evaluates true. After
evaluating true any of the else if statement it executes the statements and exits the clause.

Pragati Engineering College (Autonomous) Page 65


Programming for Problem Solving using C (R20)
Flow Chart:

// C Program to find whether input year is leap year or not


#include <stdio.h>
main()
{
int year;
printf("Enter the year:");
scanf("%d",&year);
if(year%400==0)
{
printf("It is a leap year");
}
else if(year%100==0)
{
printf("It is not a leap year");
}
else if(year%4==0)
{
printf("It is a leap year");
}
else
{
printf("It is not a leap year");
}
}
Output: Enter the year: 2020
It is a leap year
Enter the year: 2021
It is not a leap year

// C Program to find aggregate of marks using multiway statement


#include<stdio.h>
int main( )

Pragati Engineering College (Autonomous) Page 66


Programming for Problem Solving using C (R20)
{
int s1,s2,s3,s4,s5,tot; int aggr;
printf("Enter marks of 5 subjects:");
scanf("%d%d%d%d%d",&s1,&s2,&s3,&s4,&s5);
tot=s1+s2+s3+s4+s5;
printf("Total marks = %d\n",tot);
aggr=tot/5;
printf("Aggregate = %d\n",aggr);
if(aggr>=80)
printf("Grade: Excellent\n");
else if (aggr>=75)
printf("Grade: First class with Distinction");
else if(aggr>=60)
printf(" Grade : First Class");
else if(aggr>=50)
printf("Grade : Second Class");
else if(aggr>=40)
printf("Grade : Pass class");
else
printf("Grade: Fail"); return 0;
}
Output: Enter marks of 5 subjects: 90 90 88 86 84
Total marks = 438
Aggregate = 87
Grade: Excellent

// C Program to find aggregate of marks using multiway statement


#include <stdio.h>
void main()
{
int marks;
printf("Enter your marks:");
scanf("%d",&marks);
if(marks > 85 && marks <= 100)
{
printf("Congrats ! you scored grade A");
}
else if (marks > 60 && marks <= 85)
{
printf("You scored grade B +");
}
else if (marks > 40 && marks <= 60)
{
printf("You scored grade B");
}

Pragati Engineering College (Autonomous) Page 67


Programming for Problem Solving using C (R20)
else if (marks > 30 && marks <= 40)
{
printf("You scored grade C");
}
else
{
printf("Sorry you are fail");
}
}
Output:
Enter your marks:10
Sorry you are fail
Enter your marks:40
You scored grade C
Enter your marks:90
Congrats ! you scored grade A

Switch Statement: Switch() case statement is used when user has multiple alternatives of codes to
choose, depending upon the value of single variable.
Syntax:
switch (integer expression or integer or character variable)
{
case 1: statement1;
statement2;
break;
case 2: statement1;
statement2;
break;
case 3: statement1;
statement2;
break;
default:
statement;
}

In the above syntax after case keyword constant (1, 2, 3) is considered as label integers, it may be
character too. First integer expression is calculated then the value of integer or character is matched
one after another with constant values of case statements. When a match is found then that case
section of code is executed and if no match is found then default keyword code is executed.
 Switch variable and case constant variables should be of same data type.
 Value of switch variable should be assigned before entering the switch case.
 Each case keyword is followed by a constant.
 Case labels must end with (:) colon.
 Every case section should end with break statement to end the switch case else it enters into the
next case.

Pragati Engineering College (Autonomous) Page 68


Programming for Problem Solving using C (R20)
Flow Chart:

//A C program demonstrating switch case statement


#include <stdio.h>
#include <conio.h>
void main()
{
int choice;
clrscr();
printf("Select any option number from 1 to 4 : ");
scanf("%d", &choice);
switch(choice)
{
case 1: printf("You have selected first option");
break;
case 2: printf("You have selected second option");
break;
case 3: printf("You have selected third option");
break;
case 4: printf("You have selected fourth option");
break;
default:printf("Invalid option selected");
break;
}
getch();
}
//A C program demonstrating switch case statement
#include <stdio.h>
void main()
{
int a, b, op;
printf("Enter a and b values ");
scanf("%d%d", &a,&b);
printf("Enter an operator +,-,*,/: ");
scanf("%d", &op);
switch(op)

Pragati Engineering College (Autonomous) Page 69


Programming for Problem Solving using C (R20)
{
case ‘+’: c=a+b;
printf(“Addition=%d”, c);
break;
case ‘-’: c=a-b;
printf(“Subtraction=%d”, c);
break;
case ‘*’: c=a*b;
printf(“Multiplication=%d”, c);
break;
case ‘/’: c=a/b;
printf(“Division=%d”, c);
break;
default: printf(“wrong option”);
}
}

More Standard Functions


C language consists of rich set of standard functions that make programming much easier. The two
libraries of standard functions that are closely related to selection statements are given below.

C99 has two parallel but separate header files for manipulating characters.
1. ctype.h - supports the ASCII character set.
2. wctype.h - supports wide characters.

The wide-character library (wctype.h) contains some functions not found in the ASCII character
library (ctype.h), they follow a common naming format. For example, the ASCII library contains a
function, islower, to test for lowercase alphabetic characters. The equivalent function in the wide-
character library is islower.

Standard Characters Functions


The character libraries are divided into two major groups: classifying functions and converting
functions. The prototypes of these functions are in the ctype.h or wctype.h header files.

Characters are first broken down into control characters, such as carriage return and end of file, or
into printable characters. This tells us that control characters are not printable. The printable
characters are either a space or the rest of the printable characters, which are classified as graphical.
In turn, the graphical characters are broken down into alphanumeric and punctuation characters.
Alphanumeric means either an alphabetic character or a digit. Finally, alphabetic characters are either
upper- or lowercase.

Classifying Functions: Classifying functions examine a character and tell if it belongs to a given
classification as described previously. They all start with the prefix is and return true if the actual
parameter is in the specified class and false if it is not. The prototypes of these functions are found in
the ctype,h and cwtype.h files. The general form of the prototype function is

int is… (int testChar)

Pragati Engineering College (Autonomous) Page 70


Programming for Problem Solving using C (R20)
where the function name starts with is or isw; for example, iscntrl, which stands for "is a control
character."

All of the classifying functions return true or false. If the character matches the set being tested by
the function, it returns true; if it doesn't, it returns false. For example, the isdigit function tests the
character against the decimal digits (0 through 9). If the character is a decimal digit, it returns true; if
the character is not a decimal digit, it returns false. The following table summarizes each function
with a brief explanation.

Function Description
iscntrl Control characters
isprint Printable character, that is character with an assigned graphic
Whitespace character: space character (32), horizontal tab (9), line feed (10),
isspace
vertical tab (11), form feed (12), and carriage return (13)
isgraph Character with printable graphic; all printable characters except space
isalnum Alphanumeric: any alphabetic or numeric character
ispunct Any graphic character that is not alphanumeric
isalpha Any alphabetic character, upper- or lowercase
isupper Only uppercase alphabetic
islower Only lowercase alphabetic
isdigit Decimal digits (0...9)
isxdigit Hexadecimal digits (0...9, a...f. A...F)
isodigit Octal digits (0...7)

Character Conversion Functions:


Inverting are used to convert a character from one case to another. These functions with prefix to or
tow (for wide characters) and return an integer that is the value of the converted c. Their basic format
is

int to (int oldChar)

Function Description
toupper Converts lower- to uppercase. If not lowercase, returns it unchanged.
tolower Converts upper- to lowercase. If not uppercase, returns it unchanged.

LOOPING STATEMENTS / REPETITIVE STATEMENTS / ITERATIVE


STATEMENTS
In situations, when a block of code needs to be executed several number of times. In general,
statements are executed sequentially: The first statement in a function is executed first, followed by
the second, and so on. Programming languages provide various control structures that allow for more
complicated execution paths. A loop statement allows us to execute a statement or group of statements
multiple times.
Loops: Executing a set of statements repeatedly some number of times or until some condition is
true, is called looping.
Looping Statements: In looping, a sequence of statements is executed until some conditions for
termination of the loop are satisfied. A program loop therefore consists of two Segments. One has
Pragati Engineering College (Autonomous) Page 71
Programming for Problem Solving using C (R20)
known as the body of the loop and the other known as the control statements. The control statement
tests certain conditions and then directs the repeated execution of the statements contained in the body
of the loop.
Advantages with Looping Statements:
 Reduce length of Code
 Take less memory space.
 Burden on the developer is reducing.
 Time consuming process to execute the program is reduced.
C language provides 3 loop structures:
 while statement
 do-while statement
 for statement

While Loop (Condition-Controlled Loop)


 Both while loop and do-while loop are condition-controlled, meaning that they continue to loop
until some condition is met.
 Both while and do-while loops alternate between performing actions and testing for the stopping
condition.
 While loop checks for the stopping condition first, and may not execute the body of the loop at
all if the condition is initially false.
While loop statement is used when programmer doesn't knows how many times the code will be
executing before starting the loop, as it depends upon the users input.
Syntax:
while (test expression is true)
{
statement1;
statement2;

}
In the above Syntax, Executes the loop till the test expression condition is true.
Flow Chart:

//C Program using while loop statement


#include <stdio.h>
#include <conio.h>
void main()

Pragati Engineering College (Autonomous) Page 72


Programming for Problem Solving using C (R20)
{
int a=5; clrscr();
while(a!=0)
{
Printf(“Welcome”);
a--;
}
getch();
}
Output:
Welcome
Welcome
Welcome
Welcome
Welcome
Program working steps:
 First 7 lines of the program are common about comment, preprocessor directives, void main
function, initialization and clearing the console screen.
 As we have declared the value of a = 5, the while loop statement test expression results true
entering the program in while loop body asking for the user to enter the number using scanf
statement.
 When number entered by the user is 0, the loop and program terminates.

do-while Loop (Condition-Controlled Loop): do-while loops are exactly like while loops, except
that the test is performed at the end of the loop rather than the beginning. This guarantees that the
loop will be performed at least once, which is useful for checking user input among other things.
Syntax:
do
{
statement1;
statement2; // body of do-while
}while (test expression is true);

 In theory the body can be either a single statement or a block of statements within {curly
braces}, but in practice the curly braces are almost always used with do-whiles.
 Loop ends with semicolon.
Flow Chart:

Pragati Engineering College (Autonomous) Page 73


Programming for Problem Solving using C (R20)
#include<stdio.h>
void main()
{
int num=1; do
{
printf( “ %d\t”, num);
num++;
}
while(num<=5);
}
Output: 1 2 3 4 5

For Loop (Counter Controlled Loops): The type of loops, where the number of the execution is
known in advance is termed by the counter controlled loop. That means, in this case, the value of the
variable which controls the execution of the loop is previously known. The control variable is known
as counter. A counter controlled loop is also called definite repetition loop.
Syntax:
for (initialization expression; test expression; increment/decrement expression)
{
// Block of statements to execute
}

Defines three expressions:


 First expression initializes the value of variable only once at the start e.g.: int i=0;
 Second test expression checks every time whether the condition is true or not, if true it will enter
into block of statements else it will end the loop and controls transfers to the following statement.
e.g.: i<10;
 And last increment expression is always executed at the end of loop, which increments the value
of the variable. e.g.: i++;
Example: A for loop is an example of counter controlled loop.
for(i=1; i<=10; i++)
{
}

This is a typical example of counter controlled loop. Here, the loop will be executed exactly 10 times
for n = 1, 2, 3... 10.

for loop: A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times. for loops are counter-controlled, meaning that they are
normally used whenever the numbers of iterations are known in advance. for loop statement exe-
cutes a block of statements repeatedly for fixed number of times. It is used when the user knows how
many times you want to execute the code.

Pragati Engineering College (Autonomous) Page 74


Programming for Problem Solving using C (R20)
Flow Chart:

//C Program to demonstrate for loop


#include<stdio.h>
main()
{
int n,i=0;
printf("enter a number:");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("%d\n",i);
}
}
Output: enter a number: 5
0
1
2
3
4
// C Program using for statement to print two's multiplication table
#include <stdio.h>
main()
{
int i,j;
for(i=1;i<=5;i++)
{
j=2*i;
printf("2 x %d = %d\n", i,j);
}
}
Output:
2x1=2
2x2=4
2x3=6
2x4=8
Pragati Engineering College (Autonomous) Page 75
Programming for Problem Solving using C (R20)
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
The Infinite Loop: A loop becomes an infinite loop if a condition never becomes false. The for loop
is traditionally used for this purpose. Since none of the three expressions that form the 'for' loop are
required, you can make an endless loop by leaving the conditional expression empty.
Example:
int main ()
{
for( ; ; )
{
printf("This loop will run forever.\n");
}
return 0;
}

When the conditional expression is absent, it is assumed to be true. You may have an initialization
and increment expression, but C programmers more commonly use the for(;;) construct to signify an
infinite loop.
NOTE: an infinite loop can terminate by pressing Ctrl + C

Nested Loops: C programming allows to use one loop inside another loop (Nested Loop). The
following section shows a few examples to illustrate the concept.
Syntax:
1) Syntax for a nested for loop statement
for ( init; condition; increment )
{
for ( init; condition; increment )
{
statement(s);
}
statement(s);
}

2) Syntax for a nested while loop statement


while(condition)
{
while(condition) { statement(s);
}
statement(s);
}

Pragati Engineering College (Autonomous) Page 76


Programming for Problem Solving using C (R20)
3) Syntax for a nested do...while loop statement
do {
statement(s);
do {
statement(s);
}while( condition );
}while( condition );

NOTE : You can put any type of loop inside any other type of loop. For example, a 'for' loop can
be inside a 'while' loop or vice versa.

// C Program to demonstrates nested for loop to output a multiplication table


#include <stdio.h>
int main()
{
int i, j;
int table = 2;
int max = 5;
for (i = 1; i <= table; i++)
{ // outer loop
for (j = 0; j <= max; j++)
{ // inner loop
printf("%d x %d = %d\n", i, j, i*j);
}
printf("\n"); /* blank line between tables */
}
}
Output:
1x0=0
1x1=1
1x2=2
1x3=3
1x4=4
1x5=5

2x0=0
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10

#include<stdio.h>
main()
{

Pragati Engineering College (Autonomous) Page 77


Programming for Problem Solving using C (R20)
int i=1;
while(i<=10)
{
printf("%d",i);
i=i+1;
}
}
Output:12345678910

//C Program to find the sum of n natural numbers


#include<stdio.h>
main()
{
int n,i=1,sum=0;
printf("enter a number:");
scanf("%d",&n);
while(i<=n)
{
printf("%d",i);
sum=sum+i;
i=i+1;
}
printf("Sum of %d natural numbers are %d",n,sum);
}
Output: enter a number: 10
Sum of 10 natural numbers are 55

Unconditional Statements: Unconditional statements interrupt the sequential execution of


statements, so that execution continues at a different point in the program. There are four statements
that cause unconditional jumps in C: break, continue, goto and return.

Break statement: When break statement is encountered inside a loop, the loop is immediately
terminated, and program control is transferred to nest statement following the loop. The break
statement is widely used with for loop, while loop, do-while loop and switch statement.
Syntax: break;
Flow chart

Pragati Engineering College (Autonomous) Page 78


Programming for Problem Solving using C (R20)
// C Program to demonstrate break statement
#include<stdio.h>
void main()
{
int i;
for(i=0;i<5;++i)
{
if(i==3)
break;
printf("%d\n",i);
}
}
Output: 0
1
2
//C Program to demonstrate break statement
#include <stdio.h>
int main()
{
int num = 5;
while (num > 0)
{
if (num == 3)
break;
printf("%d\n", num);
num--;
}
}
Output:
5
4

The continue statement: When continue statement is encountered inside a loop, the loop is
immediately terminated, and program control is transferred to nest statement following the loop. The
break statement is widely used with for loop, while loop, do-while loop and switch statement. Syntax:
continue;
Flowchart:

Pragati Engineering College (Autonomous) Page 79


Programming for Problem Solving using C (R20)

// C Program to demonstrate continue statement


#include<stdio.h>
main()
{
int i;
for(i=0;i<5;++i)
{
if(i==3)
continue;
printf("%d\n",i);
}
}
Output: 0
1
2
4

// C Program to demonstrate continue statement


#include <stdio.h>
int main()
{
int nb = 7;
while (nb > 0)
{
nb--;
if (nb == 5)
continue;
printf("%d\n", nb);
}
}
Output:
6
4

Pragati Engineering College (Autonomous) Page 80


Programming for Problem Solving using C (R20)
3
2
1
So, the value 5 is skipped.

goto statement: By using goto statement you can transfer the control of program anywhere. This
keyword is not recommended to use in any situation. goto jump statement is used to transfer the flow
of control to any part of the program desired. The programmer needs to specify a label or identifier
with the goto statement in the following manner:
Syntax: goto label;

This label indicates the location in the program where the control jumps to.

//C Program to demonstrate goto statement


#include<stdio.h>
void main()
{
int i=1;
if(i==1)
goto one;
else if(i==2)
printf("2");
else
printf("Its nothing");
one:
printf("Avoid goto keyword");
}
Output: Avoid goto keyword

//C Program to demonstrate goto statement


#include<stdio.h>
int main()
{
int age;

Pragati Engineering College (Autonomous) Page 81


Programming for Problem Solving using C (R20)
Vote: printf("you are eligible for voting\n");
NoVote: printf("you are not eligible to vote\n");
printf("Enter your age:\n");
scanf("%d", &age);
if(age>=18)
goto Vote;
else
goto NoVote;
}
Output: Enter your age: 17
you are not eligible to vote

SOME OF THE IMPORTANT QUESTIONS WITH ANSWERS


When to Use Which Loop?
If you know (or can calculate) how many iterations you need, then use a counter-controlled (for)
loop. Otherwise, if it is important that the loop complete at least once before checking for the stopping
condition, or if it is not possible or meaningful to check the stopping condition be- fore the loop has
executed at least once, then use a do-whileloop. Otherwise use a whileloop.

Write the differences between while and do-while loop

while (Pretest Loop) do-while (Posttest Loop)


Also called ‘Entry Control Loop’ or ‘Top Also called ‘Exit Control Loop’ or ‘Bottom
Tested Loop’ Tested Loop’
Condition is checked before loop execution Condition is checked at the end ofloop
Executes false condition at least once since
Never execute loop if condition is false
condition is checked later
There is no semicolon at the end of while There is semicolon at the end of while
statement statement
Syntax: Syntax:
while(condition) do
{ {
Statements; Statements;
} }while(condition);
Flowchart: Flowchart:

Pragati Engineering College (Autonomous) Page 82


Programming for Problem Solving using C (R20)

SOME MORE EXAMPLE PROGRAMS


// C Program to Check Prime Number
#include <stdio.h>
int main()
{
int n, i, flag = 0;
printf("Enter a positive integer: ");
scanf("%d", &n);
if (n == 0 || n == 1)
flag = 1;
for (i = 2; i <= n / 2; ++i)
{
if (n % i == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
printf("%d is a prime number.", n);
else
printf("%d is not a prime number.", n);
return 0;
}
Output: Enter a positive integer: 29
29 is a prime number

// C Program to Check Armstrong Number


#include<stdio.h>
int main()
{
int n,r,sum=0,temp;
printf("enter the number=");
scanf("%d",&n);

Pragati Engineering College (Autonomous) Page 83


Programming for Problem Solving using C (R20)
temp=n;
while(n>0)
{
r=n%10;
sum=sum+(r*r*r);
n=n/10;
}
if(temp==sum)
printf("armstrong number ");
else
printf("not armstrong number");
return 0;
}
Output: enter the number=153
armstrong number
enter the number=5
not armstrong number

// C Program to find the Sum of digits of a Number


#include<stdio.h>
int main()
{
int n,sum=0,m;
printf("Enter a number:");
scanf("%d",&n);
while(n>0)
{
m=n%10;
sum=sum+m;
n=n/10;
}
printf("Sum is=%d",sum);
return 0;
}
Output: Enter a number: 654
Sum is=15
Enter a number:123
Sum is=6

// C Program to find the reverse of a Number


#include<stdio.h>
int main()
{
int n, reverse=0, rem;
printf("Enter a number: ");

Pragati Engineering College (Autonomous) Page 84


Programming for Problem Solving using C (R20)
scanf("%d", &n);
while(n!=0)
{
rem=n%10;
reverse=reverse*10+rem;
n/=10;
}
printf("Reversed Number: %d",reverse);
return 0;
}
Output: Enter a number: 123
Reversed Number: 321

//C Program to swap two numbers without third variable


#include<stdio.h>
int main()
{
int a=10, b=20;
printf("Before swap a=%d b=%d",a,b);
a=a+b;//a=30 (10+20)
b=a-b;//b=10 (30-20)
a=a-b;//a=20 (30-10)
printf("\nAfter swap a=%d b=%d",a,b);
return 0;
}
Output: Before swap a=10 b=20
After swap a=20 b=10

//C Program to find Fibonacci Series


#include<stdio.h>
int main()
{
int n1=0,n2=1,n3,i,number;
printf("Enter the number of elements:");
scanf("%d",&number);
printf("\n%d %d",n1,n2);//printing 0 and 1
for(i=2;i<number;++i)//loop starts from 2 because 0 and 1 are already printed
{
n3=n1+n2;
printf(" %d",n3);
n1=n2;
n2=n3;
}
return 0;
}

Pragati Engineering College (Autonomous) Page 85


Programming for Problem Solving using C (R20)
Output: Enter the number of elements: 15
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

//C Program to check whether a number is palindrome


#include<stdio.h>
int main()
{
int n,r,sum=0,temp;
printf("enter the number=");
scanf("%d",&n);
temp=n;
while(n>0)
{
r=n%10;
sum=(sum*10)+r;
n=n/10;
}
if(temp==sum)
printf("palindrome number ");
else
printf("not palindrome");
return 0;
}
Output: enter the number=151
palindrome number
enter the number=5621
not palindrome number

//C Program to find the factorial of a number


#include<stdio.h>
int main()
{
int i,fact=1,number;
printf("Enter a number: ");
scanf("%d",&number);
for(i=1;i<=number;i++)
{
fact=fact*i;
}
printf("Factorial of %d is: %d",number,fact);
return 0;
}
Output: Enter a number: 5
Factorial of 5 is: 120

Pragati Engineering College (Autonomous) Page 86


Programming for Problem Solving using C (R20)
//C Program to convert Decimal to Binary
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a[10],n,i;
system ("cls");
printf("Enter the number to convert: ");
scanf("%d",&n);
for(i=0;n>0;i++)
{
a[i]=n%2;
n=n/2;
}
printf("\nBinary of Given Number is=");
for(i=i-1;i>=0;i--)
{
printf("%d",a[i]);
}
return 0;
}
Output: Enter the number to convert: 5
Binary of Given Number is=101

//C Program to convert Number in Characters


#include<stdio.h>
#include<stdlib.h>
int main()
{
long int n,sum=0,r;
system("cls");
printf("enter the number=");
scanf("%ld",&n);
while(n>0)
{
r=n%10;
sum=sum*10+r;
n=n/10;
}
n=sum;
while(n>0)
{
r=n%10;
switch(r)
{

Pragati Engineering College (Autonomous) Page 87


Programming for Problem Solving using C (R20)
case 1: printf("one ");
break;
case 2: printf("two ");
break;
case 3: printf("three ");
break;
case 4: printf("four ");
break;
case 5: printf("five ");
break;
case 6: printf("six ");
break;
case 7: printf("seven ");
break;
case 8: printf("eight ");
break;
case 9:printf("nine ");
break;
case 0: printf("zero ");
break;
default:printf("tttt");
break;
}
n=n/10;
}
return 0;
}
Output: enter the number=4321
four three two one

// C program to print all factors of a number


#include <stdio.h>
int main()
{
int i, num;
printf("Enter any number to find its factor: ");
scanf("%d", &num);
printf("All factors of %d are: \n", num);
for(i=1; i<=num; i++)
{
if(num % i == 0)
{
printf("%d, ",i);
}
}

Pragati Engineering College (Autonomous) Page 88


Programming for Problem Solving using C (R20)
return 0;
}
Output: Enter any number to find its factors: 100
All factors of 100 are:
1 2 4 5 10 20 25 50 100

// C program to find HCF of two numbers


#include <stdio.h>
void main()
{
int i, num1, num2, min, hcf=1;
printf("Enter any two numbers to find HCF: ");
scanf("%d%d", &num1, &num2);
min = (num1<num2) ? num1 : num2;
for(i=1; i<=min; i++)
{
if(num1%i==0 && num2%i==0)
{
hcf = i;
}
}
printf("HCF of %d and %d = %d\n", num1, num2, hcf);
}
Output: Enter any two numbers to find HCF: 12
30
HCF of 12 and 30 = 6

//C program to find LCM of any two number


#include <stdio.h>
void main()
{
int i, num1, num2, max, lcm=1;
printf("Enter any two numbers to find LCM: ");
scanf("%d%d", &num1, &num2);
max = (num1 > num2) ? num1 : num2;
i = max;
while(1)
{
if(i%num1==0 && i%num2==0)
{
lcm = i;
break;
}
i += max;

Pragati Engineering College (Autonomous) Page 89


Programming for Problem Solving using C (R20)
}
printf("LCM of %d and %d = %d", num1, num2, lcm);
}
Output: Enter any two numbers to find LCM: 12
30
LCM of 12 and 30 = 60

//C Program to print Pattern


#include <stdio.h>
int main()
{
int n;
printf("Enter the number of rows");
scanf("%d",&n);
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
printf("*");
}
printf("\n");
}
return 0;
}
Output: Enter the number of rows 6
******
******
******
******
******
******

//C Program to print Pattern


#include <stdio.h>
int main()
{
int n;
printf("Enter the number of rows");
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
{
printf("* ");
}
printf("\n");

Pragati Engineering College (Autonomous) Page 90


Programming for Problem Solving using C (R20)
}
return 0;
}
Output :Enter the number of rows 6
*
**
***
****
*****
******

//C Program to print Pattern of numbers


#include <stdio.h>
int main()
{
int i, j, rows;
printf("Enter the number of rows: ");
scanf("%d", &rows);
for (i = 1; i <= rows; ++i)
{
for (j = 1; j <= i; ++j)
{
printf("* ");
}
printf("\n");
}
return 0;
}

Output: Enter the number of row 5


1
12
123
1234
12345

//C Program to print the full Pyramid of number


#include <stdio.h>
int main()
{
int n,m=1;
printf("Enter the number of rows");
scanf("%d",&n);
for(int i=n;i>=1;i--)

Pragati Engineering College (Autonomous) Page 91


Programming for Problem Solving using C (R20)
{
for(int j=1;j<=i-1;j++)
{
printf(" ");
}
for(int k=1;k<=m;k++)
{
printf("*");
}
printf("\n");
m++;
}
return 0;
}
Output: Enter the number of rows 5
1
232
34543
4567654
567898765

EXERCISE PROGRAMS
1. Write a C program to print all natural numbers from 1 to n. - using while loop
2. Write a C program to print all natural numbers in reverse (from n to 1). - using while loop
3. Write a C program to print all alphabets from a to z. - using while loop
4. Write a C program to print all upper case and lower case alphabets.
5. Write a C program to print all even numbers between 1 to 100. - using while loop
6. Write a C program to print all odd number between 1 to 100.
7. Write a C program to find sum of all natural numbers between 1 to n.
8. Write a C program to find sum of all even numbers between 1 to n.
9. Write a C program to find sum of all odd numbers between 1 to n.
10. Write a C program to count number of digits in a number.
11. Write a C program to find first and last digit of a number.
12. Write a C program to find sum of first and last digit of a number.
13. Write a C program to swap first and last digits of a number.
14. Write a C program to calculate product of digits of a number.
15. Write a C program to enter a number and print its reverse.
16. Write a C program to find frequency of each digit in a given integer.
17. Write a C program to enter a number and print it in words.
18. Write a C program to print all ASCII character with their values.
19. Write a C program to find power of a number using for loop.
20. Write a C program to print all Prime numbers between 1 to n.

Pragati Engineering College (Autonomous) Page 92


Programming for Problem Solving using C (R20)
21. Write a C program to find sum of all prime numbers between 1 to n.
22. Write a C program to find all prime factors of a number.
23. Write a C program to print all Armstrong numbers between 1 to n.
24. Write a C program to check whether a number is Perfect number or not.
25. Write a C program to print all Perfect numbers between 1 to n.
26. Write a C program to check whether a number is Strong number or not.
27. Write a C program to print all Strong numbers between 1 to n.
28. Write a C program to print Fibonacci series up to n terms.
29. Write a C program to find one's complement of a binary number.
30. Write a C program to find two's complement of a binary number.
31. Write a C program to convert Binary to Octal number system.
32. Write a C program to convert Binary to Decimal number system.
33. Write a C program to convert Binary to Hexadecimal number system.
34. Write a C program to convert Octal to Binary number system.
35. Write a C program to convert Octal to Decimal number system.
36. Write a C program to convert Octal to Hexadecimal number system.
37. Write a C program to convert Decimal to Binary number system.
38. Write a C program to convert Decimal to Octal number system.
39. Write a C program to convert Decimal to Hexadecimal number system.
40. Write a C program to convert Hexadecimal to Binary number system.
41. Write a C program to convert Hexadecimal to Octal number system.
42. Write a C program to convert Hexadecimal to Decimal number system.
43. Write a C program to print Pascal triangle upto n rows.
44. Star pattern programs - Write a C program to print the given star patterns.
45. Number pattern programs - Write a C program to print the given number patterns.
46. C program to print square, cube and square root of all numbers from 1 to N.
47. C program to print all leap years from 1 to N.

PREVIOUS YEAR QUESTIONS FROM UNIT – II


1. List all the operators used in C. Give examples?
2. Write a short note on Precedence and Associativity of operators with examples?
3. What are the Control statements used in C? Explain any two control statements with
syntax.
4. What is the basic difference between while and do-while loop. Explain with an example.
5. Explain switch statement with syntax and example
6. Discuss in detail about Bitwise operators in C with examples
7. What is a Conditional Operator? How to use it? Explain with examples.
8. Show how break and continue statements are used in a C-program, with example
9. Define conditional control statements. Classify them. Explain any one with an example.
10. List the logical operators and explain with examples
11. Write a C program to find sum of Natural numbers from 1 to N using for loop
Pragati Engineering College (Autonomous) Page 93
Programming for Problem Solving using C (R20)
12. Implement a C program to find the reverse of an integer number and check whether it is
palindrome or not.
13. Write a C program to find the factorial of a number using do-while ,where the number n is
entered by user
14. Write a C program that accepts three numbers and find the largest number and prints it.
15. Write a C program that prints all even numbers between 1 and 100
16. Develop a C program to print the sum of all the digits of a given number.
17. Write a C program to check whether a given year is leap year or not
18. Write a C program to print odd numbers from 1 to n.

Assignment 2
Bloom’s
Q.No. Questions CO
Taxonomy Level
SET - 1
1 List all the operators used in C. Give examples? K2 CO2

2 Explain switch statement with syntax and example. K2 CO2

3 Write a C program to print odd numbers from 1 to n. K3 CO2

SET - 2
What are the Control statements used in C? Explain any
1 K2 CO2
two control statements with syntax.
Write a short note on Precedence and Associativity of operators
2 K2 CO2
with examples?

3 Write a C program to print prime numbers from 1 to n. K3 CO2

SET - 3
Explain for loop, while loop, and do..while loop with suitable
1 K2 CO2
examples.
2 Explain bitwise operators in detail. K2 CO2

3 Write a C program to find all the leap years from 2000 to 2100. K3 CO2

Pragati Engineering College (Autonomous) Page 94

You might also like