0% found this document useful (0 votes)
18 views54 pages

Unit 2

Uploaded by

balaraju92466
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views54 pages

Unit 2

Uploaded by

balaraju92466
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 54

Introduction to Programming (AR23)

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.

KEYWORDS AND IDENTFIERS


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

NSRIT Page 2
Introduction to Programming (AR23)

auto double int struct


break else long switch
case enum register typedef
char extern return union
const float short unsigned
continue for signed void
default goto sizeof volatile
do if static while
Note: Keywords are written in lowercase letters.

Identifiers: Identifies allows to name the data and other objects in the program i.e., variables,
functions, arrays, structures, Union, Pointers. These are user-defined names and consist of
sequence of letters and digits, with a letter as first character. Each identifier in the computer is
stored at a unique address.
Rules for Identifiers:
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)

Primary data types


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

Integer Data type: The integer data type is a set of whole numbers. Every integer value does not
have 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)

Type Size Range Specifier


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

Floating Point data types: Floating-point data types are a set of numbers with the decimal value.
Every floating-point value must contain the decimal value. The floating-point data type has two
variants.
float: The keyword "float" is used to represent floating-point data type and
double: 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.

Type Size Range Specifier


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

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

Integer Real Single String


Constants Constants 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.
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
Embedded spaces, commas, and non-digit characters are not 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 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)

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

Example 2: Integer Output


#include <stdio.h>
int main()
{
int a = 5;
printf("Number = %d", a);
return 0;
}
Output: 5
NSRIT Page 9
Introduction to Programming (AR23)
Example 3: float and double Output
#include <stdio.h>
void main()
{
float n1 = 13.5;
double n2 = 12.4;
printf("number1 = %f\n", n1);
printf("number2 = %lf", n2);
}
Output: number1 = 13.500000
number2 = 12.400000
Example 4: Print Characters
include <stdio.h>
void main()
{
char chr = 'a';
printf("character = %c", chr);
}
Output: character =a

Example: Float and Double Input/Output


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

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.

Format Specifiers or Control Specifiers in C


The format specifiers are used in C for input and output purposes. Using this concept, the compiler
can understand what type of data is in a variable during taking input using the scanf() function and
printing using printf() function. Here is a list of format specifiers.
Format Specifier Type
%c Character
%d Signed integer
%e or %E Scientific notation of floats
%f Float values
%g or %G Similar as %e or %E
%hi Signed integer (short)
%hu Unsigned Integer (short)
%i Unsigned integer
%l or %ld or %li Long
%lf Double
%Lf Long double
%lu Unsigned int or unsigned long
%lli or %lld Long long
%llu Unsigned long long
%o Octal representation
%s String
%u Unsigned int
%x or %X Hexadecimal representation
%n Prints nothing
%% Prints % character

Operators: An operator is a symbol used to perform mathematical and logical operations in a


program. Operators are used in program to manipulate data and variables. That means an operator
is a special symbol that tells the compiler to perform mathematical or logical operations.
C operators can be classified as follows.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators
Expression: An expression is a sequence of operands and operators that reduces to a single value.
Example: 10 + 15 = 25

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.

Operator Meaning Example


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

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


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

Integer Arithmetic: When both the operands in a single arithmetic expression such as a + b are
integers, the expression is called integer arithmetic. The integer arithmetic always gives an integer
value.
Example: 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.

NOTE: Relational operators are used in decision making and loops.

NSRIT Page 13
Introduction to Programming (AR23)

Operator Meaning Example Return value


< Is less than 2<9 1 (true)
<= Is less than or equal to 2 <=2 1
> Is greater than 2 >9 0 (false)
>= 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>
void 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
}
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
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

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

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


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

Relative precedence of the relational and Logical operator


Highest !
>>= <<=
== !=
&&
Lowest ||

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

result = !(a != b);


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

result = !(a == b);


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

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

NSRIT Page 16
Introduction to Programming (AR23)

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

Compound assignment operator: Compound assignment operators assign a value to variable in


order to assign a new value to a variable after performing a specified operation.

// C Program to demonstrate the working of assignment operators


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

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

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)

Operator Meaning Example


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

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


#include <stdio.h>
void main()
{
int a = 21,c;
c = a;
printf("Operator is = and c = %d\n", c );
c += a;
printf("Operator is += and c=%d\n",c);
c -= a;
printf("Operator is -= and c=%d\n",c);
c *= a;
printf("Operator is *= and c=%d\n",c);
c /= a;
printf("Operator is /= and c=%d\n", c);
c = 200;
c %= a;

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.

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


after executing expression completely in which post increment is used. In the Post-Increment value
is first used in an expression and then incremented.
Example: b = x++;
In this example suppose the value of variable “x” is 5 then value of variable “b” will be 5 because
old value of “x” is used.

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.

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


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

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


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

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


#include <stdio.h>
void main()
{
int a = 10, b = 100;
float c = 10.5, d = 100.5;
printf("++a = %d \n", ++a);

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

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


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

Pictorial representation

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

No Step Explanation
1 Evaluate i++ At the time of execution we will be using 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

// C Program to demonstrate the working of Postfix and Prefix Expression in Same


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

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)

// C Program to demonstrate the working of Bitwise AND


void main()
{
int a = 12, b = 25;

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

Example: 12 = 00001100 (In Binary), 25 = 00011001 (In Binary)


Bitwise OR Operation of 12 and 25 is: 00001100| 00011001 = 00011101 = 29 (In decimal)

// C Program to demonstrate the working of Bitwise OR


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

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

Op1 Op2 OP1 ^ OP2


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

// C Program to demonstrate the working of Bitwise XOR


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

One’s complement operator ~: One’s compliment operator is an unary operator that works on
only one operand. It changes 1 to 0 and 0 to 1. It is denoted by ~.The truth table for One’s
complement operator is as follows.
Op1 ~ Op1
0 1
0 1
1 0
1 0
Example: 35 = 00100011 (In Binary)
Bitwise complement Operation of 35 is ~ 00100011 = 11011100 = 220 (In decimal)

Twist in bitwise complement operator in C Programming


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

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

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


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

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


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

// C Program to demonstrate the working of Bitwise complement


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

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

// C Program to demonstrate the working of Bitwise complement


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

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


• Right shift operator
• Left shift operator.

Left Shift Operator: Left shift operator is a binary operator that requires two integral operands
(character or integer). Left shift operator shifts all bits towards left by certain number of specified
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)

// C Program to demonstrate the working of Shift Operators


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

Special Operators: The following are the special operators in C programming language.
1. Comma Operator: The comma operator is used to separate the statement elements such as
variables, constants or expressions, and this operator is used to link the related expressions
together, 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

// C Program to demonstrate the working of sizeof Operator


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

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


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

Points to be remembered on operators:


• Unary operator: It requires only one operand.
• Binary operator: It requires two operands like a+b, a-b, a*c etc.
• Logical operator: Logical operators are used to perform logical operations on one or more
Boolean values (true or false), that can be variables, constants, or expressions.
• Assignment operator: Used to combine the results of two or more statements.
• Conditional operator: check a condition and execute one of two statements based on the result
of that condition
• Bitwise operator: Used to manipulate the data at bit level. It operates on integer only. It may
not be applied to float or real.

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;

Fig: Conversion Rank


Promotion: The rank of the right expression is evaluated to the rank of the left variable. The value
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 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

Selection and Making Decision:


A program is nothing but the execution of sequence of one or more instructions. Sometimes it is
desirable to alter the execution of sequence of statements in the program depending upon certain
circumstances. This involves decision making through branching and looping. Control statements
specify the order in which the various instructions in a program are to be executed by the computer.
i.e., they determine the ‘flow of control’ in a program. Various control statements are:
 One way Selection statement
 Two way Selection statement
 Multi way Selection statement
 Repetition or Loop control statements

One way Selection statement: The statement is executed if the value of the expression is true.
One way Selection is implemented using simple if statement.
Simple if statement: The “if” statement is a powerful decision making statement and is used to
control the flow of execution of statements. C uses the keyword “if” to execute a set of statements
or one statements when the logical condition is true.
Syntax: if(condition or expression)
{
Statements-block;
}
Next statement;
In above syntax, the condition is checked first which allows the computer to evaluate the

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

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


#include <stdio.h>
void main()
{
int a=5;
if(a>4)
{
printf("\nValue of ‘a’ is greater than 4 !");
}
if(a==4)
{
printf("\n\n Value of ‘a’ is 4 !");
}
}
//A C program to check whether the given number is +ve or –ve using simple if statement.
#include<stdio.h>
void main()
{
int num;

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.

// C program to demonstrate Simple if statement


#include<stdio.h>
void main()
{
int no=0;
printf("Enter a number:");
scanf("%d", &no);
if(no%2==0)
{
printf("%d is even number", no);
}
}
Output: Enter a number:4
4 is even number
// C Program to find the largest number of the three.
#include <stdio.h>
void main()
{
int a, b, c;
printf("Enter three numbers");
scanf("%d %d %d", &a, &b, &c);
if(a>b && a>c)
{
printf("%d is largest”, a);
}
if(b>a && b > c)
{
printf("%d is largest", b);
}
if(c>a && c>b)
{
printf("%d is largest", c);
}
if(a == b && a == c)
{
printf("All are equal");
}
}
Output: Enter three numbers

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.

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


#include <stdio.h>
void main()

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 a person is eligible to vote or not.


#include <stdio.h>
int main()
{
int age;
printf("Enter your age:");
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;

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.

// C Program to check the user credentials


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

// C Program to find largest of three numbers


#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter a,b,c values:");
scanf("%d%d%d", &a,&b,&c);
if(a>b)
{
if(a>c)
printf("%d is the big\n",a);
else
printf("%d is the big\n",c);
}
else
{
if(b>c)
printf("%d is the big\n",b);
else
printf("%d is the big\n",c);
}
return 0;
}
Output: Enter a,b,c values:
9
4
5
9 is the big
NSRIT Page 36
Introduction to Programming (AR23)
//C Program to find Roots of a Quadratic Equation
#include <math.h>
#include <stdio.h>
int main()
{
double a, b, c, discriminant, root1, root2, realPart, imagPart;
printf("Enter coefficients a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);

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

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


{
root1 = (-b + sqrt(discriminant)) / (2 * a);
root2 = (-b - sqrt(discriminant)) / (2 * a);
printf("root1 = %.2lf and root2 = %.2lf", root1, root2);
}
else if (discriminant == 0) // condition for real and equal roots
{
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
else // if roots are not real
{
realPart = -b / (2 * a);
imagPart = sqrt(-discriminant) / (2 * a);
printf("root1 = %.2lf+%.2lfi and root2 = %.2f-%.2fi", realPart, imagPart, realPart,
imagPart);
}
return 0;
}
Output: Enter coefficients a, b and c:
2.3
4
5.6
root1 = -0.87+1.30i and root2 = -0.87-1.30i

MULTI-WAY SELECTION: Multi-way selection chooses among several alternatives. The


decision logic for multiway selection is shown below.

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:

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


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

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

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


#include<stdio.h>
int main( )
{
int s1,s2,s3,s4,s5,tot; int aggr;
printf("Enter marks of 5 subjects:");
scanf("%d%d%d%d%d",&s1,&s2,&s3,&s4,&s5);
tot=s1+s2+s3+s4+s5;
printf("Total marks = %d\n", tot);
aggr=tot/5;
printf("Aggregate = %d\n",aggr);
if(aggr>=80)
printf("Grade: Excellent\n");
else if (aggr>=75)
printf("Grade: First class with Distinction");
else if(aggr>=60)
printf(" Grade : First Class");
else if(aggr>=50)
printf("Grade : Second Class");
else if(aggr>=40)
printf("Grade : Pass class");

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

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


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

Switch Statement: Switch() case statement is used when user has multiple alternatives of codes

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:

//A C program demonstrating switch case statement


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

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

While Loop (Condition-Controlled Loop)


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

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

NSRIT Page 43
Introduction to Programming (AR23)
Flow Chart:

//C Program using while loop statement


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

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

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
}

Defines three expressions:


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

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:

//C Program to demonstrate for loop


#include<stdio.h>
void main()
{
int n,i=0;
printf("enter a number:");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("%d\n",i);
}
}
Output: enter a number: 5
0
1
2
3
4
//C Program using for statement to print two's multiplication table
#include <stdio.h>
main()
{
int i,j;
for(i=1;i<=5;i++)
{
j=2*i;
printf("2 x %d = %d\n", i,j);
}
}
Output:
2x1=2

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

2) Syntax for a nested while loop statement


while(condition)
{
while(condition) { statement(s);
}
statement(s);
}
NSRIT Page 47
Introduction to Programming (AR23)

3) Syntax for a nested do...while loop statement


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

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

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


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

NSRIT Page 48
Introduction to Programming (AR23)
{
printf("%d ",i);
i=i+1;
}
}
Output:1 2 3 4 5 6 7 8 9 10

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


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

Unconditional Statements: Unconditional statements interrupt the sequential execution of


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

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

// C Program to demonstrate break statement


#include<stdio.h>

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)

//C Program to demonstrate goto statement


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

//C Program to demonstrate goto statement


#include<stdio.h>
int main()
{
int age;
Vote:printf("you are eligible for voting\n");
NoVote:printf("you are not eligible to vote\n");
printf("Enter your age:\n");
scanf("%d", &age);
if(age>=18)
goto Vote;
else
goto NoVote;
}
Output: Enter your age: 17
you are not eligible to vote

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.

PREVIOUS YEAR QUESTIONS FROM UNIT – II


1. Differentiate Variables, Constants and Keywords?
2. Explain the basic structure of C program and explain the significance of each section?
3. How do you write and run C programs? Explain with an example?
4. List and explain basic data types with their sizes and ranges?
5. Define key word in C. Explain any two key words with examples?
6. Define Type conversion. Illustrate the types of type conversions with example?
7. Write a program in C to print the numbers from 1 to10 and their squares?
8. Which of the following are valid identifiers in C? If not valid state the reason?
9. (i)@abc (ii)4xyz (iii) abc_x (iv)_ (v) a4b (vi)for (vii) 11
10. List all the operators used in C. Give examples?
11. Write a short note on Precedence and Associativity of operators with examples?
12. What are the Control statements used in C? Explain any two control statements with
syntax.
13. What is the basic difference between while and do-while loop. Explain with an example.
14. Explain switch statement with syntax and example
15. Discuss in detail about Bitwise operators in C with examples
16. What is a Conditional Operator? How to use it? Explain with examples.
17. Show how break and continue statements are used in a C-program, with example
18. Define conditional control statements. Classify them. Explain any one with an example.
19. List the logical operators and explain with examples
20. Write a C program to find sum of Natural numbers from 1 to N using for loop
21. Implement a C program to find the reverse of an integer number and check whether it is
palindrome or not.
22. Write a C program to find the factorial of a number using do-while ,where the number n is
entered by user
23. Write a C program that accepts three numbers and find the largest number and prints it.
24. Write a C program that prints all even numbers between 1 and 100
25. Develop a C program to print the sum of all the digits of a given number.
26. Write a C program to check whether a given year is leap year or not
27. Write a C program to print odd numbers from 1 to n.

NSRIT Page 54

You might also like