PPSC Unit 1&2 Lesson Notes
PPSC Unit 1&2 Lesson Notes
SOLVING USING C
DIGITAL NOTES
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:
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,
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/
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
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.
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.
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.
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
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.
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
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.
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.
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
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.
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.
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 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.
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.
#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.
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
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
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
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
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.
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.
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.
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.
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”
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
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;
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.
• 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.
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.
printf("Value of (a + b) * c / d is : %d\n",e );
e=((a+b) * c) / d; // (30 * 15 )/ 5
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
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:
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.
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.
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.
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
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.
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
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.
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
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
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;
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 %= a; // c = c%a
printf("c = %d \n", c);
return 0;
}
Output:
c=5
c = 10
c=5
c = 25
c=5
c=0
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.
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
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.
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
// 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.
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.
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.
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.
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
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
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
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:
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
Pointer operator(*): This operator is used to define pointer variables in c programming language.
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.
//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.
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.
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.
discriminant = b * b - 4 * a * c;
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.
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.
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.
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
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)
Function Description
toupper Converts lower- to uppercase. If not lowercase, returns it unchanged.
tolower Converts upper- to lowercase. If not uppercase, returns it unchanged.
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:
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
}
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.
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);
}
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.
2x0=0
2x1=2
2x2=4
2x3=6
2x4=8
2 x 5 = 10
#include<stdio.h>
main()
{
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
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:
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.
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.
Assignment 2
Bloom’s
Q.No. Questions CO
Taxonomy Level
SET - 1
1 List all the operators used in C. Give examples? K2 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?
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