Unit 2
Unit 2
Unit II
Basics of C Programming
Introduction, Structure of a C Program, Comments, Keywords, Identifiers, Data Types, Variables,
Constants, Input/output Statements. Operators, Type Conversion. Control Flow, Relational
Expressions: Conditional Branching Statements: if, if-else, if-else-if, switch. Basic Loop Structures:
while, do-while loops, for loop, nested loops, The Break and Continue Statements, goto statement.
Self - Learning Topic: Escape Sequence
-----------------------------------------------------------------------------------------------------------------
Introduction
C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in
1972.
It is a very popular language, despite being old. The main reason for its popularity is because
it is a fundamental language in the field of computer science.
C is a High level programming language.
C is a structured programming language. So every instruction in a c program must follow
the predefined structure (Syntax).
C is also known as Function Oriented Programming Language. So every executable
statement must written inside a function.
Why Learn C?
It is one of the most popular programming languages in the world
If you know C, you will have no problem learning other popular programming languages
such as Java, Python, C++, C#, etc., as the syntax is similar.
C is very fast, compared to other programming languages, like Java and Python
C is very versatile; it can be used in both applications and technologies
Structure of a C Program
A C program is divided into different sections. There are six main sections to a basic program
NSRIT Page 1
Introduction to Programming (AR23)
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.
#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 at least 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 (:).
void main(void)
{
int a=10;
printf(" %d", a);
}
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.
NSRIT Page 2
Introduction to Programming (AR23)
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:
1. First character must be either an alphabet or _ (underscore).
2. Must consist of only alphabets, digits or underscore.
3. Only first 31 characters are significant.
4. Cannot use a keyword.
5. Must not contain any special characters including 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)
NSRIT Page 3
Introduction to Programming (AR23)
Integer Data type: The integer data type is a set of whole numbers. Every integer value does not
have a 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 provides complete details about the integer data type.
NSRIT Page 4
Introduction to Programming (AR23)
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: The keyword “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 %lf
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.
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 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
have different values 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;
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:
NSRIT Page 5
Introduction to Programming (AR23)
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. To declare a constant type
variable, we have to use “const” keyword.
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
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 not 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
NSRIT Page 6
Introduction to Programming (AR23)
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 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 constant 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”, 97);
the above printf statement prints the letter a.
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.
NSRIT Page 7
Introduction to Programming (AR23)
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
NSRIT Page 8
Introduction to Programming (AR23)
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 for float, %l for long, and %c for char
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.
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
NSRIT Page 10
Introduction to Programming (AR23)
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
}
Output: Enter a character: g
You entered g.
ASCII value is 103.
NSRIT Page 11
Introduction to Programming (AR23)
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: if a = 10, b = 6
a–b=4
a + b = 16
a * b = 60
a / b = 1 (decimal part truncated)
a % b = 4 (remainder of a division)
Example:
#include <stdio.h>
void 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);
NSRIT Page 12
Introduction to Programming (AR23)
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>
void main()
{
int months, days;
printf(“Enter days:”);
scanf(“%d”, &days);
months =days/30;
days=days%30;
printf(“\nMonths = %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 produce either
TRUE or FALSE. In C true is represented with 1 and false is represented with 0. In simple words,
the relational operators are used to define conditions in a program.
NSRIT Page 13
Introduction to Programming (AR23)
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
NSRIT Page 14
Introduction to Programming (AR23)
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
Example Program
void main ()
{
int a=10, b =20, c=30;
NSRIT Page 15
Introduction to Programming (AR23)
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);
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;
NSRIT Page 16
Introduction to Programming (AR23)
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.
NSRIT Page 17
Introduction to Programming (AR23)
NSRIT Page 18
Introduction to Programming (AR23)
printf("Operator is %= and c=%d\n",c);
c <<= 2;
printf("Operator is <<= andc=%d\n",c);
c >>= 2;
printf("Operator is >>= andc=%d\n",c);
c &= 2;
printf("Operator is &= andc = %d\n", c );
c ^= 2;
printf("Operator is ^= andc = %d\n", c );
c |= 2;
printf("Operator is |= andc = %d\n", c );
}
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.
NSRIT Page 19
Introduction to Programming (AR23)
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 Preincrement
--x Predecrement
x++ Postincrement
x-- Postdecrement
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.
NSRIT Page 20
Introduction to Programming (AR23)
printf("--b = %d \n", --b);
printf("++c = %f \n", ++c);
printf("--d = %f \n", --d);
}
Output: ++a = 11
--b = 99
++c = 11.500000
++d = 99.500000
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 old value of i =1
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 step2
NSRIT Page 21
Introduction to Programming (AR23)
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.
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>
void main()
NSRIT Page 22
Introduction to Programming (AR23)
{
int a=10, b=20,x;
x=(a>b)?a:b;
printf("x = %d",x);
}
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.
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 AND Operation of 12 and 25 is 00001100 & 00011001 = 00001000 = 8 (In decimal)
NSRIT Page 23
Introduction to Programming (AR23)
printf("Output = %d", a&b);
}
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
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 corresponding bits of
two operands are opposite. It is denoted by ^. 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
Example: 35 = 00100011 (In Binary)
Bitwise complement Operation of 35 is ~ 00100011 = 11011100 = 220 (In decimal)
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
NSRIT Page 25
Introduction to Programming (AR23)
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
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
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:
NSRIT Page 26
Introduction to Programming (AR23)
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, 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 of the specified
variable, and it is very useful to find the bytes occupied by the specified variable in the memory.
Syntax: sizeof(variable-name);
Example: int a;
sizeof(a); //Output 2bytes
Type conversion: 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
NSRIT Page 28
Introduction to Programming (AR23)
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.
• 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;
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 converts 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: int a;
float f=(float) a;
NSRIT Page 29
Introduction to Programming (AR23)
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
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
NSRIT Page 30
Introduction to Programming (AR23)
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 a 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.
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 (;).
NSRIT Page 31
Introduction to Programming (AR23)
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.
NSRIT Page 32
Introduction to Programming (AR23)
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 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
condition. 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.
NSRIT Page 33
Introduction to Programming (AR23)
{
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 the given year is leap or not using if.. else statement.
#include<stdio.h>
void main()
{
int year;
NSRIT Page 34
Introduction to Programming (AR23)
printf("Enter any year:");
scanf("%d", &year);
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 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 condition2truestatements; //statement1
}
else
{
if condition1 true and condition2false statements; //statement2
}
}
else
{
Condition1falsestatements; //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;
NSRIT Page 37
Introduction to Programming (AR23)
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.
Flow Chart:
NSRIT Page 38
Introduction to Programming (AR23)
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
NSRIT Page 39
Introduction to Programming (AR23)
else
printf("Grade: Fail"); return 0;
}
Output: Enter marks of 5 subjects: 90 90 88 86 84
Total marks = 438
Aggregate = 87
Grade: Excellent
Switch Statement: Switch() case statement is used when user has multiple alternatives of codes
NSRIT Page 40
Introduction to Programming (AR23)
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.
Flow Chart:
NSRIT Page 41
Introduction to Programming (AR23)
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)
{
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”);
}
}
NSRIT Page 42
Introduction to Programming (AR23)
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
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
NSRIT Page 43
Introduction to Programming (AR23)
Flow Chart:
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);
NSRIT Page 44
Introduction to Programming (AR23)
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:
#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
}
NSRIT Page 45
Introduction to Programming (AR23)
This is a typical example of counter controlled loop. Here, the loop will be executed exactly 10
times for n = 1, 2, 3... 10.
Flow Chart:
NSRIT Page 46
Introduction to Programming (AR23)
2x2=4
2x3=6
2x4=8
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:
void main ()
{
for( ; ; )
{
printf("This loop will run forever.\n");
}
}
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.
NSRIT Page 48
Introduction to Programming (AR23)
{
printf("%d ",i);
i=i+1;
}
}
Output:1 2 3 4 5 6 7 8 9 10
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
NSRIT Page 49
Introduction to Programming (AR23)
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>
void main()
{
int num = 5;
while (num > 0)
{
if (num == 3)
break;
printf("%d\n", num);
num--;
}
}
Output: 5
4
The continue statement: When the continue statement is encountered inside a loop (e.g., for,
while, or do-while), it does not terminate the loop. Instead, it causes the loop to skip the rest of
the current iteration and immediately start the next iteration. Program control remains within the
loop. The loop does not terminate; it simply moves on to the next iteration. The continue statement
is typically used to skip specific loop iterations based on a condition.
Syntax: continue;
Flowchart:
NSRIT Page 50
Introduction to Programming (AR23)
// 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>
void main()
{
int nb = 7;
while (nb > 0)
{
nb--;
if (nb == 5)
continue;
printf("%d\n", nb);
}
}
Output: 6
4
3
2
1
So, the value 5 is skipped.
goto statement: By using goto statement you can transfer the control of the program
anywhere. This keyword is not recommended to use in any situation. 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.
NSRIT Page 51
Introduction to Programming (AR23)
NSRIT Page 52
Introduction to Programming (AR23)
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.
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.
NSRIT Page 53
Introduction to Programming (AR23)
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.
NSRIT Page 54