0% found this document useful (0 votes)
120 views65 pages

Module 1-1

The document discusses algorithms, flowcharts, pseudocode, and basic concepts of the C programming language. It defines an algorithm as a set of step-by-step instructions to solve a problem and lists properties like finiteness and definiteness. Examples of algorithms are provided. Flowcharts are described as a pictorial representation of an algorithm using standard symbols. Pseudocode uses a combination of English phrases and syntax to describe programs. Basic C concepts covered include data types, comments, source characters, and type qualifiers.

Uploaded by

Pranay Reddy
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)
120 views65 pages

Module 1-1

The document discusses algorithms, flowcharts, pseudocode, and basic concepts of the C programming language. It defines an algorithm as a set of step-by-step instructions to solve a problem and lists properties like finiteness and definiteness. Examples of algorithms are provided. Flowcharts are described as a pictorial representation of an algorithm using standard symbols. Pseudocode uses a combination of English phrases and syntax to describe programs. Basic C concepts covered include data types, comments, source characters, and type qualifiers.

Uploaded by

Pranay Reddy
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/ 65

1.

1 Algorithm
An algorithm is a finite set of step-by-step instructions to solve a problem. The
essential properties of an algorithm are:
1. Finiteness: The algorithm must always terminate after a finite number of steps.
2. Definiteness: Each and every instruction should be precise and unambiguous i.e.
each and every instruction should be clear and should have only one meaning.
3. Effectiveness: Each instruction should be performed in finite amount of time.
4. Input and Output: An algorithm must take zero or more inputs, and produce
one or more outputs.
5. Generality: An algorithm applies to different sets of same input type.

Advantages:
1. It is step-by-step solution to a given problem which is very easy to understand.
2. It has got a definite procedure.
3. It is easy to first develop an algorithm, then convert into a flowchart and then
into a computer program.
4. It is easy to debug as every step has got its own logical sequence.
5. It is independent of programming languages.

Disadvantages:
1. It is time consuming and cumbersome as an algorithm is developed first which is
converted into flowchart and then into a computer program
2. Algorithm lacks visual representation hence understanding the logic becomes
difficult.
Examples:
Write an algorithm to add two numbers
Step 1: Start
Step 2: Declare variables num1, num2 and sum
Step 3: Read num1 and num2
Step 4: Add num1 and num2 and assign the result to sum. sum←num1+num2
Step 5: Display sum
Step 6: Stop

Write an algorithm to find the largest among three different numbers


Step 1: Start
Step 2: Declare variables A, B and C.
Step 3: Read variables A, B and C.
Step 4: If A>B
If A>C
Display A is the largest number.
else
Display C is the largest number.
else
If B>C
Display B is the largest number.
Else
Display C is the largest number.
Step 5: Stop
1.2 Flowchart
Flowchart is a pictorial or symbolic representation of an algorithm.It indicates
process of solution. They are constructed by using special geometrical symbols. Each
symbol represents an activity. Flowcharts are read from top to bottom unless a branch
alters the normal flow.

Advantages
1. It clarifies the program logic.
2. Before coding begins the flowchart assists the programmer in determining the
type of logic control to be used in a program
3. The flowchart gives pictorial representation
4. Serves as documentation
5. Serves as a guide for program writing.
6. Ensure that all possible conditions are accounted for.
7. Help to detect deficiencies in the problem statement.

Disadvantages:
1. When the program logic is complex the flowchart quickly becomes complex and
clumsy and lacks the clarity of decision table.
2. It alterations and modifications are required, the flowchart may require re-
drawing completely.
3. As the flowchart symbols cannot be typed reproduction of flowcharts often a
problem.
4. It is sometimes difficult for a business person or user to understand the logic
depicted in a flowchart.
Symbols used to draw flowcharts:
Comparison between flow chart and algorithm
S. No. Algorithm Flow chart
An algorithm is a finite set of step- Flowchart is a pictorial or symbolic
1 by-step instructions that solve a representation of an algorithm.
problem
Algorithm gives verbal which is Gives pictorial representation.
2
almost similar to English language.
Suitable for large and modular Suitable for small programs.
3
programs
Easier to understand To understand flowcharts one has to
4
familiar with symbols.
5 Drawing tools are not required. Required.
Algorithm can be typed so Flowcharts cannot be typed. So
6
reproduction is easy. reproduction is a problem.
It is independent of programming We have to use predefined standard
7 languages. symbols only.

Example for a flowchart

Pseudo code: It is a simple way of writing programming code in English. It is a combination of


generic syntax and normal English language. Pseudo code is not actual programming language.
It uses short phrases to write code for programs before actually create it in a specific language.
It helps the programmer understand the basic logic of the program.

The example of a pseudo code to add two numbers and display the result as shown below:

DEFINE: Integer num1, num2, result


READ: Integer num1
READ: Integer num2 SET:
result=num1+num2
Display: result

Advantages
 Developing program code using Pseudo codeis easier.
 The program code instructions are easier to modify in comparison to a flowchart.
 It is well suited for large program design.
Disadvantages
 It is difficult to understand the program logic since it does not use pictorial
representation.
 There is no standard format for developing a Pseudocode
Basic concept’s of C Program
C language was developed by Dennis Ritchie in 1972 at AT&T Bell Laboratories
(USA). C language was derived from B language which was developed by Ken Thomson in
1970. This B language was adopted from a language BCPL (Basic Combined Programming
Language), which was developed by Martin Richards at Cambridge University. The language
B named as so by borrowing the first initial from BCPL language. Dennis Ritchie modified
and improved B language and named it as C language, using second initial from BCPL.

C is a general purpose, structured programming language. C language is one of the


most popular computer languages today because it is a structured, high level, machine
independent language. It allows software developers to develop software without worrying
about the hardware platforms where they will be implemented.

Here are most common reasons why C is still so popular:


 C is one of the most popular programming languages of all time to create system
software as well as application software.
 C is a standardized programming language with international standards.
 C is the base for almost all popular programming languages.
 C is one of the foundations for modern computer science and information technology.

Importance of C
It is a robust language whose rich set of built in functions and operators can be used to
write any complex program. The C compiler combines the capabilities of an assembly
language with the features of a higher level language and therefore it is well suited for both
system software and business packages.

Features
 C is a general purpose language
 C can be used for system programming as well as application programming.
 C is middle level language
 C is portable language
 An application program written on C language will work on many different
computers with little or no modifications.
 C Block structured language. In C , a block is marked by two curly braces({ })
 C programs are compact, fast and efficient
 C is case sensitive language
 C is function oriented language
 C language includes advanced data types like pointers, structures, unions,
enumerated types etc.
 C language supports recursion and dynamic storage allocation
 C can manipulate with bits, bytes and addresses
 Parameter passing can be done using call-by-value and call-by-reference

2.1 The C Character Set


We know that English language has 26 alphabets. We will use combinations of these
alphabets to form words, sentences, paragraphs etc. In a similar way we will use the available
characters while writing programs in any programming language.

There are two set of characters in “C” language


1. Source characters
2. Execution characters
Source Characters
These are characters that are used to create source text file. Source characters include
Alphabets A to Z, a to z
Digits 0,1,2,3,4,5,6,7,8,9
Special Characters , . ; : ? ‘ “ ! | / \ ~ _ $ % # & ^ * + - <> ( ) { } [ ] and blank

Comments
 Comments are used by programmers to add remarks and explanations within the
program.
 Compilerignores all the comments and they do not have any effect on the executable
program.
 Comments are of two types; single line comments and multi-line comments.
 Single line comments start with two slashes ( // ) and all the text until the end of
the line is considered a comment.
// this is a single line comment
 Multi-line comments start with characters /* and end with characters */. Any text
between those characters is considered a multi-line comment.
/* this is a multi-line comment and it
spawned over
multiple lines */

2.2 Data Types of C


C supports different types of data. The type or Data type refers a type of data that is
going to be stored in variable. Data types can be broadly classified as shown in figure

C provides a standard minimal set of data types. Sometimes these are also called as
‘Primitivetypes’. They are:
 ‘char’ is used to store any single character.
 ‘int’ is used to store integer value.
 ‘float’ is used to store floating point value and
 ‘double’ is used for storing long range of floating point number.

Type Qualifiers
In addition, C has four type qualifiers, also known as type modifiers which precede the basic
data type. A type modifier alters the meaning of basic data type to yield a new data type.
They are as follows:
 short
 long ( to increase the size of an int or double type)
 signed
 unsigned
The qualifiers can be classified into two types:
1. Size qualifier (e.g., short and long)
2. Sign qualifier (e.g., signed and unsigned)

Size qualifiers: alters the size of basic data type. The keywords long and short are two size
qualifiers. For example:
long int i;
The size of int is 2 bytes but, when long keyword is used, that variable will be either 4 bytes
or 8 bytes.

Sign qualifiers: Whether a variable can hold only positive value or both values is specified
by sign qualifiers. Keywords signed and unsigned are used for sign qualifiers.

a. Each of these type modifiers can be applied to base type int.


b. The modifiers signed and unsigned can also be applied to base type char.
c. In addition long can also be applied to double.
d. When base type is omitted from a declaration, int is assumed.

Example
Suppose a variable can be assigned only an integer value. Such variable can be declared as
int a;
This declaration reserves two bytes of memory for storing the number. Such a variable can
store a number in range -32768 to 32767. In order to increase the range you can add a
qualifier to the declaration.
long int a;
The following table shows the basic data types with qualifiers and their ranges.

Data Type Size (in Bytes) Range


char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed int 2 -32768 to 32767
short int 2 -32768 to 32767
unsigned short int 2 0 to 65535
signed short int 2 -32768 to 32767
long int 4 -2147483648 to 2147483647
unsigned long int 4 0 to 4294967295
signed long int 4 -2147483648 to 2147483647
float 4 3.4E-38 to 3.4E +38
double 8 1.7E-308 to 1.7E+308
long double 10 3.4E-4932 to 1.1E+4932

2.3 Various kinds of C Data(Tokens)


The data in C language can be divided into
 Constants/literals
 Variables/Identifiers
 Reserved Words/Key words
 Delimiters
Constants
Constant can be defined as a value that can be stored in memory and cannot be changed
during execution of the program. Constants are used to define fixed values like pi. C has four
basic types of constants. They are:

Integer Constant
An integer constant must have at least one digit and should not have a decimal point. It can
be either positive or negative.
Examples for integer constants
1 9 234 999
Floating point Constant
A floating point constant is decimal number that contains either a decimal point or an
exponent. In the other words, they can be written in 2 forms: fractional and exponential.
When expressed in fractional form, note the following points.
1. There should be at least one digit, and could be either positive or negative value. A
decimal point is must.
2. There should be no commas or blanks.
Examples for fractional form
12.33 -19.56 +123.89 -0.7
When expressed in exponential form, a floating point constant will have 2 parts. One is
before e and after it. The part which appears before e is known as mantissa and the one which
follows is known as exponent. When expressed in this format, note the following
points.mantissa and exponential should be separated by letter E.
1. mantissa can have a positive and negative sign.
2. default is positive.

Examples for fractional form


2E-10 0.5e2 1.2E+3 -5.6E-2

Character Constant
These are single character enclosed in single quotes. A character can be single
alphabet, single digit, single special symbol enclosed with in single quotes. Not more than a
single character is allowed.
Example
‘a’ ‘Z’ ‘5’ ‘$’

String Constant
A String constant is sequence of characters enclosed in double quotes. So “a” is not
same as ‘a’. The characters comprising the string constant are stored in successive memory
locations.
Example
“hello” “Programming” “cse”

Variables/Identifiers
Variable is named memory location that can be used to store values. These variables
can take different values but one value at a time. These values can be changed during
execution of a program.
Identifiers are basically names given to program elements such as variables, arrays and
functions.

Rules for naming a Variable/Identifier


1. The only characters allowed are alphabets, digits and underscore (_).
2. They must start with an alphabet or an underscore (_).
3. It can not include any special characters or punctuation marks (like #, $, ^, ?, ., etc.)
except underscore (_).
4. They can be of any reasonable length. They should not contain more than 31 characters.
But it is preferable to use 8 characters.
5. There cannot be two successive underscores.
6. Reserved words/keywords cannot be identifiers.
7. Lower case or uppercase letters are significant.

Key words
 These are also called as reserved words.
 All Keywords have fixed meanings and these meanings cannot be changed.
 There are 32 keywords in C programming.
 Keywords serve as basic building blocks for a program statement.
 All keywords must be written in lowercase only.

ANSI C Keywords
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

Delimiters
Delimiters are used for syntactic meaning in C. These are given below:

Symbol Name Meaning


: Colon Used for label
; Semicolon End of statement
() Parenthesis Used in expression
[] Square brackets Used in expression
{} Curly braces Used for block of statements
# Hash Pre-processor directive
, Comma Variable separator

2.4 Variables
A variable is named memory location that stores a value. When using a variable, we
actually refer to address of the memory where the data is stored. C language supports two
basic kinds of variables:
1. Numeric variables
2. Character variables

Numeric variables
Numeric variables can be used to store either integer values or floating point values.
While an integer value is a whole number without a fraction part or decimal point. A floating
point value can have a decimal point.

Numeric values may be associated with modifiers like short, long, signed, and
unsigned.

Character variables
Character variables can include any letter from the alphabet or from ASCII chart and
numbers 0-9 that are given within single quotes.

Variable declaration
To declare a variable, specify the data type of the variable followed by its name. The
data type indicates the kind of data that the variable will store. Variable names should always
be meaningful and must reflect the purpose of their usage in the program. In C, variable
declaration always ends with a semicolon, for example:

char grade;
int emp_no;
float salary;
double bal_amount
unsigned short int acc_no;

C allows multiple variable of same type to be declared in one statement, so the following
statement is absolutely legal in C
float temp_in_deg, temp_in_farh;

Initializing variables
Assigning value to variable is called variable initialization. For example:
char grade= ‘A’;
int emp_no=1007;
float salary=8750.25;
double bal_amount=100000000

When variables are declared but not initialized they usually contain garbage values.

Basically variable declaration can be done in three different places in a C program.


1. Inside main() function are called local variables.
2. Outside main() function are called global variables.
3. In the function definition header are called formal parameters.

Declaring Constants
To declare a constant, precede the normal variable declaration with const keyword and assign
it a value. For example,
const float pi=3.1415;
This const keyword specifies that the value of cannot change.

2.5 Structure of a C Program


C program is a collection of one or more functions. Every function is collection of
statements, performs a specific task. The structure of a basic C program is:
Documentation section
The documentation section consists of a set of comment lines giving the name of the
program, the author and other details, which the programmer would like to use later. There
are two types of comment lines.
1. Block comment lines /* */ and
2. Single line comment lines. //

Link section
The link section provides instructions to the compiler to link functions from the
system library.

#include directive
The #include directive instructs the compiler to include the contents of the file
"stdio.h" (standard input output header file) enclosed within angular brackets.

Definition section
The definition section defines all symbolic constants. #define PI 3.1413

Global declaration section


There are some variables that are used in more than one function. Such variables are
called global variables and are declared in the global declaration section that is outside of all
the functions. This section also declares all the user-defined functions.

main() function section

Every C program must have one main function section. This section contains two
parts:
1. Declaration part and
2. Executable part
Declaration part: It declares all the variables used in the executable part.

Executable part: There is at least one statement in the executable part.


These two parts must appear between the opening and closing braces. The program
execution begins at the opening brace and ends at the closing brace. The closing brace of the
main function is the logical end of the program. All statements in the declaration and
executable part end with a semicolon.

Subprogram 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.
For Example a ‘C’ program that prints welcome message:
#include<stdio.h>
int main( )
{
printf(“Welcome to C Programming\n”);

}
Output :
Welcome to C Programming

2.5 Operators in C
An operator is defined as a symbol that operates on operands and does something. The
something may be mathematical, relational or logical operation. C language supports a lot of
operators to be used in expressions. These operators can be categorized into the following
groups:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Increment/Decrement operators
5. Bitwise operators
6. Conditional operators
7. Assignment operators
8. Special operators

Arithmetic operators
 These are used to perform mathematical operations.
 These are binary operators since they operate on two operands at a time.
 They can be applied to any integers, floating-point number or characters.
 C supports 5 arithmetic operators. They are +, -, *, /, %.
 The modulo (%) operator can only be applied to integer operands and cannot be used
on float or double values.
Consider three variables declared as,
int a=9,b=3,result;
We will use these variables to explain arithmetic operators. The table shows the arithmetic
operators, their syntax, and usage in C language.

Operation Operator Syntax Statement Result


Addition + a+b result=a+b 12
Subtraction - a-b result=a-b 6
Multiply * a*b result=a*b 27
Divide / a/b result=a/b 3
Modulo % a%b result=a%b 0
a and b are called operands.
An Example ‘C’ program that illustrates the usage of arithmetic operators.

#include<stdio.h>
int main()
{
int a=9,b=3;
printf("%d+%d=%d\n",a,b,a+b);
printf("%d-%d=%d\n",a,b,a-b);
printf("%d*%d=%d\n",a,b,a*b);
printf("%d/%d=%d\n",a,b,a/b);
printf("%d%%%d=%d\n",a,b,a%b);
return 0;
}
Output
9+3=12
9-3=6
9*3=27
9/3=3
9%3=0

Relational operators
A relational operator, also known as a comparison operator, is an operator that
compares two operands. The operands can be variables, constants or expressions. Relational
operators always return either true or false depending on whether the conditional relationship
between the two operands holds or not.
C has six relational operators. The following table shows these operators along with their
meanings

Operator Meaning Example


< Less than 3<5 gives 1
> Greater than 7<9 gives 0
<= Less than or equal to 100<=100 gives 1
>= Greater than or equal to 50>=100 gives 0
== Equal to 10==9 gives 0
!= Not equal to 10!=9 gives 1

An example program that illustrates the use of arithmetic operators.

#include<stdio.h>
int main()
{
int a=9,b=3;
printf("%d>%d=%d\n",a,b,a>b);
printf("%d>=%d=%d\n",a,b,a>=b);
printf("%d<%d=%d\n",a,b,a<b);
printf("%d<=%d=%d\n",a,b,a<=b);
printf("%d==%d=%d\n",a,b,a==b);
printf("%d!=%d=%d\n",a,b,a!=b);
return 0;
}
Output
9>3=1
9 >= 3 = 1
9<3=0
9 <= 3 = 0
9= =3 = 0
9 != 3 = 1

Logical operators
Operators which are used to combine two or more relational expressions are known as
logical operators. C language supports three logical operators – logical AND(&&), logical
OR(||), logical NOT( !).

 Logical&& and logical || are binary operators whereas logical!is an unary operator.
 All of these operators when applied to expressions yield either integer value 0 (false)
or an integer value 1(true).

Logical AND
It is used to simultaneously evaluate two conditions or expressions with relational
operators. If expressions on the both sides (left and right side) of logical operators is true then
the whole expression is true otherwise false. The truth table of logical AND operator is given
below:
A B A&&B
0 0 0
0 1 0
1 0 0
1 1 1

Logical OR
It is used to simultaneously evaluate two conditions or expressions with relational
operators. If one or both the expressions on the left side and right side of logical operators is
true then the whole expression is true otherwise false. The truth table of logical OR operator
is given below:

A B A||B
0 0 0
0 1 1
1 0 1
1 1 1

Logical NOT
It takes single expression and negates the value of expression. The truth table of logical NOT
operator is given below

A !A
0 1
1 0

For example: x and y are two variables. The following equations explain the use of logical
operators.
z1 = x&&y …1
z2 = x||y …2
z3 =!x …3
Equation1 indicates that z1 is true if both x and y is true. Equation2 indicates z2 is true when
x or y or both true. Equation3 indicates z3 is true when x is not true.

An example ‘C’ program that illustrates the use of logical operators


#include<stdio.h>
int main()
{
int z1,z2,z3;
z1=7>5 && 10>15;
z2=7>5 || 10>15;
z3=!(7>5);
printf(" z1=%d\n z2=%d\n z3=%d \n",z1,z2,z3);
return 0;
}
Output
z1=0
z2=1
z3=0
Unary operators
Unary operators act on single operands. 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.
For example,
int a, b=10;
a=-(b);
the result of this expression is a=-10.

Increment (++) and decrement (− −) operators


The increment operator is unary operator that increases value of its operand by 1.
Similarly, the decrement operator decreases value of its operand by 1. These operators are
unique in that they work only on variables not on constants.These are used in loops like
while, do-while and for statements.
There are two ways to use increment or decrement operators in expressions. If you put
the operator in front of the operand (prefix), it returns the new value of the operand
(incremented or decremented). If you put the operator after the operand (postfix), it returns
the original value of the operand (before the increment or decrement).

Operator Name Value returned Effect on variable


x++ Post-increment x Incremented
++x Pre-increment x=x+1 Incremented
x− − Post-decrement x Decremented
– −x Pre-decrement x=x - 1 Decremented

An example program that illustrates the use of unary operators


#include<stdio.h>
int main()
{
int x=5;
printf("x=%d\n", x++);
printf("x=%d\n",++x);
printf("x=%d\n",x--);
printf("x=%d\n",--x);
printf("x=%d\n",-x);
return 0;
}
Output
x=5
x=7
x=7
x=5
x=-5

Bitwise operators
As the name suggests, the bitwise operators operate on bits. These operations include:
1. bitwise AND(&)
2. bitwise OR(|)
3. bitwise X-OR(^)
4. bitwise NOT(~)
5. shift left(<<)
6. shift right(>>)

Bitwise AND (&)


When we use the bitwise AND operator, the bit in the first operand is ANDed with
the corresponding bit in the second operand. If both bits are 1, the corresponding bit in the
result is 1 and 0 otherwise. For example:
In a C program, the & operator is used as follows.
int a=4,b=2,c;
c=a&b;
printf(“%d”,c); //prints 0

100 (binary equivalent of decimal 4)


&010 (binary equivalent of decimal 2)
000

Bitwise OR (|)
When we use the bitwise OR operator, the bit in the first operand is ORed with the
corresponding bit in the second operand. If one or both bits are 1, the corresponding bit in the
result is 1 and 0 otherwise. For example:
In a C program, the | operator is used as follows.
int a=4,b=2,c;
c=a|b;
printf(“%d”,c); //prints 6

100 (binary equivalent of decimal 4)


| 010 (binary equivalent of decimal 2)
110

Bitwise XOR (^)


When we use the bitwise XOR operator, the bit in the first operand is XORed with the
corresponding bit in the second operand. If both bits are different, the corresponding bit in the
result is 1 and 0 otherwise. The truth table operator is shown below:
A B A&&B
0 0 0
0 1 1
1 0 1
1 1 0

For example:
In a C program, the | operator is used as follows.
int a=4,b=2,c;
c=a^b;
printf(“%d”,c); //prints 6

100 (binary equivalent of decimal 4)


| 010 (binary equivalent of decimal 2)
110

Bitwise NOT (~)


One’s complement operator (Bitwise NOT) is used to convert each 1 to 0 and 0 to 1,
in the given binary pattern. It is a unary operator i.e. it takes only one operand.
For example, In a C program, the ~ operator is used as follows.
int a=4,c;
c=~a;
printf(“%d”,c); //prints -5

~100 (binary equivalent of decimal 4)


101

Shift operators
C supports two bitwise shift operators. They are shift-left (<<) and shift-right (>>).
These operations are simple and are responsible for shifting bits either to left or to the right.
The syntax for shift operation can be given as:

operand operator num


where the bits in operand are shifted left or right depending on the operator (<<, >>) by the
number of places denoted by num.

Left shift operator


When we apply left-shift, every bit in x is shifted to left by one place. So, the MSB
(Most Significant Bit) of x is lost, the LSB (Least Significant Bit) of x is set to 0.

Let us consider int x=4;


Now shifting the bits towards left for 1 time, will give the following result
MSB LSB
23 22 21 20
8 4 2 1
x=4 0 1 0 0
1 0 0
x<<1 = 1 0 0 0 the result of x<<1 is 8

Left-shift is equals to multiplication by 2.


Right shift operator
When we apply right-shift, every bit in x is shifted to right by one place. So, the LSB
(Least Significant Bit) of x is lost, the MSB (Most Significant Bit) of x is set to 0.
Let us consider int x=4;
Now shifting the bits towards right for 1 time, will give the following result.

23 22 21 20
8 4 2 1
x=4 0 1 0 0
0 1 0
x>>1 = 0 0 1 0 the result of x>>1 is 2

Right-shift is equals to division by 2.

An example ‘C’ program that illustrates the use of bitwise operators


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

}
Output:
4|2=6
4&2=0 int a=4,b=2;
4^2=6 printf("%d | %d = %d\n",a,b,a|b);
~4 = -5 printf("%d & %d = %d\n",a,b,a&b);
4 << 1 = 8 printf("%d ^ %d = %d\n",a,b,a^b);
4 >> 1 = 2 printf("~%d = %d\n",a,~a);
printf("%d<<1 = %d\n",a,a<<1);
printf("%d>>1 = %d\n",a,a>>1);
return 0;

Assignment operators
Assignment operator (=)
In C, the assignment operator (=) is responsible for assigning values to variables.
When equal sign is encountered in in an expression, the compiler processes the statement on
the right side of the sign and assigns the result to variable on the left side.
For example,
int x;
x=10;
Assigns the value 10 to variable x. if we have,
int x=2,y=3,sum=0;
sum = x + y;
then sum=5.
The assignment has right-to-left associativity, so the expression
int a=b=c=10;
is evaluated as
(a=(b=(c=10)))

Consider the following set of examples:


a = 5; // value of variable ‘a’ becomes 5
a = 5+10; // value of variable ‘a’ becomes 15
a = 5 + b; // value of variable ‘a’ becomes 5 + value of b
a = b + c; // value of variable ‘a’ becomes value of b + value of c

Short hand/Compound assignment operators


The assignment operator can be combined with the major arithmetic operators such operators
are called compound assignment operators. C language supports a set of compound
assignment operators of the form:
variable op = expression;
where op is binary arithmetic operator.

The following table lists the assignment operators supported by the C:


Op Description Example
Add AND assignment operator. It adds the right C += A is equivalent to
+= operand to the left operand and assign the result to C = C + A
the left operand.
Subtract AND assignment operator. It subtracts the C −= A is equivalent to
−= right operand from the left operand and assigns the C = C − A
result to the left operand.
Multiply AND assignment operator. It multiplies C *= A is equivalent to
*= the right operand with the left operand and assigns C = C * A
the result to the left operand.
Divide AND assignment operator. It divides the C /= A is equivalent to
/= left operand with the right operand and assigns the C = C / A
result to the left operand.
Modulus AND assignment operator. It takes C %= A is equivalent to
%= modulus using two operands and assigns the result C = C % A
to the left operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

An example ‘C’ program that illustrates the use of assignment operators

#include <stdio.h>
int main() Output
{ Operator is = and c = 21
int a = 21,c; Operator is += and c = 42
c = a; Operator is −= and c = 21
printf("Operator is = and c = %d\n", c ); Operator is *= and c = 441
c += a; Operator is /= and c = 21
printf("Operator is += and c=%d\n",c); Operator is %= and c = 11
c −= a; Operator is <<= and c = 44
printf("Operator is −= and c=%d\n",c); Operator is >>= and c = 11
c *= a; Operator is &= and c = 2
printf("Operator is *= and c=%d\n",c); Operator is ^= and c = 0
c /= a; Operator is |= and c = 2
printf("Operator is /= and c=%d\n", c);
c = 200;
c %= a;
printf("Operator is %= and c=%d\n",c);
c <<= 2;
printf("Operator is <<= and c=%d\n",c);
c >>= 2;
printf("Operator is >>= and c=%d\n",c);
c &= 2;
printf("Operator is &= and c = %d\n", c );
c ^= 2;
printf("Operator is ^= and c = %d\n", c );
c |= 2;
printf("Operator is |= and c = %d\n", c );
return 0;
}

Advantages:
1. Short hand expressions are easier to write.
2. The statement involving short hand operators are easier to read as they are more
concise.
3. The statement involving short hand operators are more efficient and easy to
understand.

Conditional operator (? : )
It is also called ternary operator because it takes three operands. It has the general form:
variable = expression1 ? expression2 : expression3;
If the expression1 is evaluated totrue then it evaluates expression2 and its value is
assigned to variable, otherwise it evaluates expression3 and its value is assigned to variable.

It is an alternative to simple if..else statement

For example
#include<stdio.h>
int main()
{
int a=5,b=6,big;
big = a>b ? a : b;
printf("%d is big\n", big);
return 0;
}
Output
6 is big
Special operators: Comma operator (,)
This operator allows the evaluation of multiple expressions, separated by the comma,
from left to right in the order and the evaluated value of the rightmost expression is accepted
as the final result. The general form of an expression using a comma operator is
expressionM= ( expression1, expression2, expressionN);
For example
#include<stdio.h> i=5 j=9
int main() #include<stdio.h>
{ int main()
int k=5; {
i=k++, j=(k++,k++,++k); int k=5;
printf(i=%d\t j=%d”, i,j); i=k++, j =k++, k++, ++k;
return 0; printf(i=%d \t j=%d”, i,j);
} return 0;
Output }
17
Output i=5 j=6
sizeof Operator
The operator sizeof is a unary operator used calculates the size of data types and
variables. The operator returns the size of the variable, data type in bytes. i.e. the sizeof
operator is used to determine the amount of memory space that the variable/data type will
take. The outcome is totally machine-dependent.
For example:
#include<stdio.h>
int main()
{
printf("char occupies %d bytes\n",sizeof(char));
printf("int occupies %d bytes\n",sizeof(int));
printf("float occupies %d bytes\n",sizeof(float));
printf("double occupies %d bytes\n",sizeof(double));
printf("long double occupies %d bytes\n",sizeof(long double));
return 0;
}
Output
char occupies 1 bytes
int occupies 2 bytes
float occupies 4 bytes
double occupies 8 bytes
long double occupies 10 bytes
2.6 Expressions
In C programming, an expression is any legal combination of operators and operands
that evaluated to produce a value.Every expression consists of at least one operand and can
have one or more operators. Operands are either variables or values, whereas operators are
symbols that represent particular actions.
In the expression x + 5; x and 5 are operands, and + is an operator.

In C programming, there are mainly two types of expressions are available. They are as
follows:
1. Simple expression
2. Complex expression

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

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

Operators provided mainly two types of properties. They are as follows:


1. Precedence and
2. Associativity

Operator Precedence
It definesthe order in which operators in an expression are evaluated depends on their
relative precedence. Example: Let us see x=2+2*2
1st pass- 2+2*2
nd
2 pass- 2+4
3rd pass- 6 that is x=6.

Associativity defines the order in which operators with the same order of precedenceare
evaluated. Let us see x=2/2*2
1st pass-- 2/2*2
2nd pass-- 1*2
3rd pass-- 2that is x=2

The belowtable lists C operators in order of precedence (highest to lowest) and


their associativity indicates in what order operators of equal precedence in an expression are
applied.

S.No Operators Associativity


1 ( ) [ ] → . ++ (postfix) − −(postfix) L to R
++ (prefix) -- (prefix) ! ~ sizeof(type) + (unary) − (unary) R to L
2
&(address) * (indirection)
3 */ % L to R
4 + − L to R
5 <<>> L to R
6 <<= >>= L to R
7 = = != L to R
8 & L to R
9 ^ L to R
10 | L to R
11 && L to R
12 | | L to R
13 ? : R to L
14 = += −= *= /= %= >>= <<= &= ^= |= R to L
15 , L to R

An example ‘C’ program that illustrates the use of expressions


#include<stdio.h>
int main()
{
int a, b=4,c=8,d=2,e=4,f=2;
a=b+c/d+e*f; // expression1
printf(" The value of a is%d\n", a);
a=(b+c)/d+e*f; // expression2
printf("The value of a is%d\n", a);
a=b+c/((d+e)*f); // expression3
printf("The value of a is%d\n", a);
return 0;
}

Output:
The value of a is 16
The value of a is 14
The value of a is 6

2.7 Formatted input and output functions


When input and output is required in a specified format the standard library functions scanf()
and printf() are used

Output function printf( )


printf() is a function that is used to print any data on the video monitor screen. It has the
following form:
printf(“control string”,list_of_variables);
The function accepts two arguments - control string, which controls what gets printed, and
list of variables.
 The control string is all-important because it specifies
o The type of each variable in the list and how user wants it printed. It is also
called as format specifier.
o Characters that are simply printed as they are.
o Control string that begins with a % sign.
o Escape sequences that begin with a \ sign
 List of variables must be separate by comma.
 The number of format specifiers must exactly match the number of variables.

Format specifiers
Format
Data Type Display
specifier
%c char Single character
%c unsigned char
%s Sequence of characters (String)
int Signed integer (both +ve and –ve
%d
values)
%u unsigned int Unsigned integer (only +ve values)
%hd short int Signed short integer
%ld long int Long integer
unsigned long Unsigned long integer (only +ve
%lu int values)
%o int Octal values
%x int Hexa decimal values
%f float Floating-point value
long Double precision floating-point
%lf float/double value
long double Double precision floating-point
%Lf
value
%p pointer Address stored in pointer
%% none Prints %

Flag characters used in printf

Flag Meaning
− Left justify the display
+ Display the positive or negative sign of value
0 Pad with leading zeros
space Display space if there is no sign
The simplest printf statement is
printf(“Welcome to the world of C language”);
When executed, it prints the string enclosed in double quotes on screen.

Examples:
printf(“Result:%d%c%f\n”,12,’a’,2.3);
Result:12a2.3

printf(“Result:%d%c%f\n”,12,’a’,2.3);
Result:12a2.3

printf(“Result:%d\t%c\t%f\n”,12,’a’,2.3);
Result:12 a 2.3
printf(“%6d\n”,1234);
1 2 3 4

printf(“%06d\n”,1234);
0 0 1 2 3 4

printf(“%-6d\n”,1234);
1 2 3 4

printf(“%-06d\n”,1234);
- 0 1 2 3 4

printf(“%2d\n”,1234);
1 2 3 4

printf(“%9.2f\n”,123.456);
0 0 1 2 3 4 . 4 5

char ch=’A’;
printf(“%c\n%2c\n%3c\n”,ch,ch,ch);
A
A
A

printf(“%X\n”,255);
FF

Input function scanf()


C provides scanf( ) function for entering input data. This function accepts all types of data as
input (numeric, character, string). The general form of scanf() is given below

Syntax
scanf(“control string”,variable1,variable2,…,variable n);

This function should have at least two parameters. First parameter is control string which is
conversion specification character. It should be within double quotes. This may be one or
more, it depends on the number of variables. The other parameter is variable names.
Each variable must preceded by ampersand (&) sign. This gives starting address of
the variable name in memory. scanf ( ) uses all the format specifiers used in printf( ) function.
Note: comments are not allowed in scanf()
For example, consider the following simple programs.
#include <stdio.h>
int main()
{
int x;
printf(“Enter number:”);
scanf(“%d”, &x);
printf(“The value of x is %d\n”, x);
return 0;
}
Output
Enter a number: 45
The value of x is 45
For accessing multiple values from keyboard using scanf() function
#include <stdio.h>
int main()
{
int x,y;
printf(“Enter two numbere:”);
scanf(“%d%d”, &x,&y);
printf(“The value of x is %d\n”, x);
printf(“The value of y is %d\n”, y);
return 0;
}
Output
Enter two numbers: 29 47
The value of x is 29
The value of x is 47

2.8 Type Conversion


Type casting:Type casting is a way to convert a variable from one data type to another data
type. It can be of two types:
1. Implicit type casting
2. Explicit type casting

Implicit type casting


When the type conversion is performed automatically by the compiler without
programmer’s intervention, such type of conversion is known as implicit type
conversion or type promotion. In this, all the lower data types are converted to its next
higher data type.
If the both operands are of the same type, promotion is not needed. If they are not,
promotion follows these rules:
 float operands are converted to double.
 char or short are converted to int.
 If anyone operand is double, the other operand is also converted to double, and that
is the type of result.
or
 If anyone operand is long, the other operand is also converted to long, and that is the
type of result.
 If anyone operand is unsigned, the other operand is also converted to unsigned, and
that is the type of result.
The smallest to the largest data types with respect to size are given as follows:
For example:

Fig. Conversion of types in a mixed extresssion

A Sample ‘C’ program that illustares the use implicit type conversion
#include<stdio.h>
int main()
{
int sum, num=17;
char ch='A';
sum=num+ch;
printf("The value of sum=%d\n", sum);
return 0;
}
Output:
The value of sum= 82 i.e. sum=num+ch=>17+65 (ASCII value of ‘A’

Explicit typecasting: Which is intentionally performed by the programmer for his


requirement in a C program?The explicit type conversion is also known as type casting.We
can convert the values from one type to another explicitly using the cast operator as follows:

Syntax
(data_type) expression;

Where, data_type is any valid C data type, and expression may be constant, variable or
expression.

The following rules have to be followed while converting the expression from one type to
another to avoid the loss of information:
1. All integer types to be converted to float.
2. All float types to be converted to double.
3. All character types to be converted to integer.
Let us look at some examples of type casting.

 res = ( int ) 9.5;


9.5 is converted to 9 by truncation then assigned to res.
 res = ( int ) 12.3 / ( int ) 4.2 ;
It evaluated as 12/4 and the value 3 is assigned to res.
 res = ( double ) total / n;
total is converted to double and then division is done in float point mode.
 res = ( int )(a + b);
The value of (a + b) is converted to integer and then assigned to res.
 res = ( int )a + b;
a is converted to int and then added with b.

2. 9 Mathematical Functions in C
The mathematical functions such as sin, cos, sqrt, log etc., are frequently used in
analysis of real-life problems. Most of the C compilers support these basic math functions.
The following Table lists some standard math functions

Function Meaning
Trigonometric
asin(x) Arc sin of x.
acos(x) Arc cosine of x
atan(x) Arc tangent of x
atan2(y,x) Arc tangent of y/x
sin(x) sine of x
cos(x) cosine of x
tan(x) tangent of x
Hyperbolic
sinh(x) hyperbolic sine of x
cosh(x) hyperbolic cosine of x
tanh(x) hyperbolic tangent of x
Other functions
exp(x) e to the power of x (ex)
ceil(x) x rounded up to the nearest integer.
floor(x) x rounded down to the nearest integer
fabs(x) absolute value |x|
log(x) Natural logarithm of x, x>0.
log10(x) Base 10 logarithm x, x>0.
fmod(x,y) Remainder of x/y
sqrt(x) square root of x, x>=0.
pow(x,y) x to the power y.

Note:
1. x and y should be declared as double.
2. In trigonometric and hyperbolic functions, x and y are radians.
3. All the functions return a double.
We should include the line:
#include<math.h>
in the beginning of the program

An example ‘C’ program that illustrates the use mathematical functions


#include <stdio.h>
#include <math.h>
int main()
{
printf("sin 90 = %.0f\n",sin(90));
printf("cos 0= %.0f\n",cos(0));
printf("sqrt(9) = %.0f\n",sqrt(9));
printf("floor(9.56) = %.2f\n",floor(9.56));
printf("ceil(9.56) = %.2f\n",ceil(9.56));
printf("abs(-9) = %.2f\n",fabs(-9));
printf("power(2,3) = %.0f\n",pow(2,3));
printf("Remainder of 9/3 = %.0f\n",fmod(9,3));
return 0;
}

Output
sin 90 = 1
cos 0= 1
sqrt(9) = 3
floor(9.56) = 9.00
ceil(9.56) = 10.00
abs(-9) = 9.00
power(2,3) = 8
Remainder of 9/3 = 0
Control Statements in C
Statements
 The statements of a C program control the flow of program execution.
 A statement is a command given to the computer that instructs the computer to take a
specific action, such as display to the screen, or collect input.
 A computer program consists of a number of statements that are usually executed in
sequence. Statements in a program are normally executed one after another.

Control statements enable us to specify the flow of program control; ie, the order in
which the instructions in a program must be executed. They make it possible to make
decisions, to perform tasks repeatedly or to jump from one section of code to another.

Control statements in C programming language are divided into two types.


1. Selection/ Branching statements (also called Decision making statements) and
2. Iteration/ Looping statements (also called Repetitive statements).

 Branching is deciding what actions to take and


 Looping is deciding how many times to take a certain action.

Selection/ Branching statements are again divided into two types.


1. Conditional statements:(if,if-else, nested if-else, else-if ladder, switch and
conditional expression/conditional operator)
2. Unconditional statements ( break, continue,goto and exit)

Iteration/ Looping(Repetitive) statements are as follows:There are three types of loops in C


programming:
1. while loop
2. do-while loop
3. for loop
Specifying Test Condition for Selection and Iteration
A test condition used for selection and iteration is expressed as a test expression. If an
expression evaluates to true, it is given the value of 1. If a test expression evaluates to false, it
is given the value of 0.
 Relational and Logical operators are available to specify the test condition used in the
control statements of C.
 Relational operators are used to specify individual test expression.
 Logical operators are used to connect more than one test expression.
Relational Operators
To Specify Symbol Logical Operators
Used
Less than < To Specify Symbol
Less than or equal to <= Used
Greater than > Logical AND &&
Greater than or equal >= Logical OR ||
to Logical NOT !
Equal to ==
Not equal to !=

Writing Test Expression


Test condition is specified with test expression. The syntax of the test expression for
specifying the test condition is as follows:
(Variable/ Expression/ Constant) operator ( Variable/ Expression/ Constant)
Some examples of expressions are given below.
1. (num%2==0)
2. (year%4==0)
3. (a>b)
4. (sum==num)
5. (per>=80)
6. (num!=0)
7. (num>10)
8. (num<=10).

3.1 Selection/ Branching statements


The simple if
This is a powerful decision-making statement and is used to control the flow of execution of
statements. It is basically a two-way decision statement and is used in conjunction with an
expression. It takes the following form:

Syntax: Flowchart

if(test expression )
{
statement-block;
}
statement - x;

If the test expression is true then the statement-block will be executed; otherwise the
statement block will be skipped and the execution will jump to the statement-x. Remember,
when the condition is true both the statement-block and the statement-x are executed in
sequence.

Ex 1: Write a program „C‟ to check whether the given number is +ve or –ve using
simple if statement.
#include<stdio.h>
int main()
{
int num;
printf("Enter a number:");
scanf("%d”, &num);
if(num>0)

printf(“%d is a positive number\n”, num);


}
return 0;
}
Output:
Enter a number: 9
9 is a positive number.

The if..else statement


The if..else statement is an extension of the simple if statement. The general form is:
Syntax Flowchart

if(test expression )
{
statement block - 1;
}
else
{
statement block - 2;
}
statement-x;

If the test expression is true, then statement block – 1 is executed and statement block-2 is
skipped. Otherwise, the statement-2 is executed. In both the cases, the control is transferred
subsequently to the statement-x.

Ex 2: Write a program „C‟ to check whether the given number is even or odd using if..else
statement.
#include<stdio.h>
int main()
{
int num;
printf("Enter a number:");
scanf("%d",&num);
if(num%2==0)
printf("%d is even number\n",num);
else
printf("%d is odd number\n",num);
return 0;
}

Output:
Enter a number: 8
8 is even number.

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

Output:
Enter any year: 1996
1996 is leap year.

Nested if-else statement


When a series of decisions are involved, we may have to use more than one if..else statement
in nested form. Nested if means one if statement with in another if statement.

Syntax: Flowchart:
if (test expression 1)
{
if (test expression 2)
{
statement-1;
}
else
{
statement-2;
}
}
else
{
statement-3;
}
statement-x;

If the test expression1 is false, the statement-3 will be executed; otherwise it continues
to perform the second test. If the test expression-2 is true, the statement-1 will be executed.
Otherwise the statement-2 will be executed and then the control is transferred to the
statement-x.

Ex 4: Write a C program to find the biggest among three numbers using nested-if statement.
#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 5 17
17 is the big

Multi-way Branching statements


In some situations we may like to have more than two possible paths for program
flow. In such cases else..if or switch statement may be used.

The if..else..if/Ladder if statement


This is the multi-way selection statement (i.e. used to test multiple conditions). The
syntax is:
if(test expression 1)
{
statements block-1;
}
else if (test expression 2)
{
statements block-2;
}
.....................
.....................
else if (test expression N)
{
statement block-N;
}
else
{
default statements;
}

All the conditions are evaluated one by one starting from top to bottom, if any one of
the condition evaluating to true then statement group associated with it are executed and skip
other conditions. If none of expression is evaluated to true, then the statement or group of
statement associated with the final else is executed.

Flowchart
The following program demonstrates a legal if-else if statement: In this program we
assign grades to students according to the marks they obtained, using else-if ladder statement.

Ex 5: Write a C program to display student grades using else..if 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");
else
printf("Grade: Fail");
return 0;
}

Output
Enter marks of 5 subjects: 90 90 88 86 84
Total marks = 438
Aggregate = 87
Grade: Excellent
The switch statement
A switch statement is also a multi-way decision making statement that is a simplified
version of if..else..if block that evaluates a single variable. The syntax of switch statement is:

switch(variable)
{
case constant 1:
statements;
break;
case constant 2:
statements;
break;
case constant N:
statements;
break;
default:
default statement;
}

When switch statement is executed, A variable successively matched against a list of


integer or character constants. When a match is found, a statement or block of statements is
executed where the default is executed if no matches are found. The default is optional and, if
not present, no action takes place if all matches fail.
When a match is found, the statements associated with that case is executed until the
break is encountered.
A switch statement work with only char and int primitive data types, it also works
with enumerated types and string.

Ex 6: Write a C program to implement simple calculator using switch statement.


#include<stdio.h>
int main()
{
int choice;
int a,b;
printf("Simple Calculator\n");
printf(" \n");
printf("1.Addition\n2.Subtraction\n3.Multiplication\n4.Division\n");
printf("Enter your choice(1..4):");
scanf("%d",&choice);
printf("Enter a,b values:");
scanf("%d%d",&a,&b);
switch(choice)
{
case 1:
printf("%d+%d=%d\n",a,b,a+b);
break;
case 2:
printf("%d-%d=%d\n",a,b,a-b);
break;
case 3:
printf("%d*%d=%d\n",a,b,a*b);
break;
case 4:
printf("%d/%d=%d\n",a,b,a/b);
break;
default:
printf("Invalid choice ... !");
}
return 0;
}

Output
Simple Calculator

1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice(1..4): 2
Enter a,b values: 12 7
12 – 7 = 5

3.2 Looping Structures


The programmer sometimes interested to repeat a set statements a number of times. This
is known as looping in a computer program. A loop is a group of instructions that computer
executes repeatedly while some loop continuation conditions remains true. Two ways of
repetitions are possible:
1. Counter controlled loops
2. Sentinel controlled loops
(In computer programming, data values used to signal either the start or end of a data series
are called sentinels)
Counter controlled loops are sometimes called „definite loops‟ because we know in advance
exactly how many times the loop will be executed.
Sentinel controlled loops are sometimes called „indefinite loops‟ because it is not known in
advance how many times the loop will be executed.
Repetition structure has four required elements:
1. Repetition statement (while, for, do..while )
2. Condition to be evaluated
3. Initial value for the condition
4. Loop termination
C supports the following types of loops:
1. The while loop
2. The do..while loop
3. The for loop
Advantages
 Reduce length of Code
 Take less memory space.
 Burden on the developer is reducing.
 Time consuming process to execute the program is reduced.

The While Loop


The while loop is a pre-test or entry-controlled loop. It uses test expression to control
the loop. The while loop evaluates (checking) the test expression before every iteration of the
loop, so it can execute zero times if the condition is initially false.

The body of the loop will be executed repeatedly till the value of test expression
becomes false (0). The initialization of a loop control variable is generally done before the
loop separately.
syntax:

while (test expression)


{
body of the loop;
}
statement-x;

Flowchart

How while loop works?


 Initially the while loop evaluates (checking condition) the test expression.
 If the test expression is true (nonzero i.e.,1), statements inside the body of while loop
is evaluated. Then, again the test expression is evaluated. The process goes on until
the test expression is false.
 When the test expression is false, the while loop is terminated.

Ex 7: Write a C program to print 1 to 10 numbers using while loop.


#include<stdio.h>
int main( )
{
int n=1;
while(n<=10)
{
printf(“%d\t”,n);
n++;
}
return 0;
}

Output: 1 2 3 4 5 6 7 8 9 10

Ex 8: Write a C program to print reverse of given number using while loop.


#include<stdio.h>
int main( )
{
int n,rem;
printf("Enter a number to reversed:");
scanf("%d",&n);
printf("The reverse number is ");
while(n != 0)
{
rem = n%10;
printf("%d",rem);
n = n/10;
}
printf("\n");
return 0;
}

Output
Enter a number to be reversed: 1234
The reverse number is: 4321

Ex 9: Write a C program to check whether the given number is Armstrong or not.


#include<stdio.h>
int main( )
{
int n,rem,sum=0,temp;
printf("Enter a number:");
scanf("%d",&n);
temp=n;
while(n != 0)
{
rem = n%10;
sum = sum+(rem*rem*rem);
n = n/10;
}
if(sum == temp)
printf("%d is Armstrong\n", temp);
else
printf("%d is not an Armstrong\n", temp);
return 0;
}

Output
Enter a number: 153
153 is Armstrong

Ex 10: Write a C program for sum of individual digits of a number.


#include<stdio.h>
int main()
{
int n,rem,sum=0;
printf("enter a number:\n");
scanf("%d", &n);
while(n != 0)
{
rem=n%10;
sum=sum+rem;
n=n/10;
}
printf("The sum of individual digits is %d", sum);
return 0;
}
Output:
Enter a number: 1234
The sum of individual digits is 10

do..while Statement
do-while loop is similar to while loop, however there is one basic difference between
them. do-while runs at least once even if the test condition is false at first time. Syntax of do
while loop is:
Syntax Flowchart

do
{
body of the loop;
}
while (expression);
statement -x;

How do-while loop works?


 First the code block (loop body) inside the braces ({….}) is executed once.
 Then, the test expression is evaluated (checking condition). If the test expression is
true, the loop body is executed again. This process goes on until the test expression is
evaluated to false (0).
 When the test expression is false, the do...while loop is terminated.
The following example illustrates the use of do-while loop.
#include<stdio.h>
int main()
{
int num=1;
do
{
printf( “ %d\t”, num);
num++;
}while(num<=5);
return 0;
}

Output: 1 2 3 4 5

Comparison between do and while loops


S.No While loop Do-while loop
Condition is checked before entering Condition is checked after executing
1
into loop statements in loop
2 Top-tested /entry-controlled loop Bottom-tested /exit-controlled loop
3 Minimum iterations are zero Minimum iterations are one
4 Maximum iterations are N+1 Maximum iterations are N
General loop statement but well suited
5 General loop statement
for menu-driven applications
6 Non-deterministic loop Non-deterministic loop

The For Statement


It most general looping construct in C. The for loop is commonly used when the
number of iterations are exactly known. The syntax of a for loop is

for(initialization; test expression; increment /decrement/ update)


{
body of the loop;
}

Flowchart
The loop header contains three parts:
o an initialization,
o a test condition, and
o incrementation(++) / decrementation(˗ ˗) /update.

Initialization: This part is executed only once when we are entering into the loop first time.
This part allows us to declare and initialize any loop control variables.

Condition: if it is true, the body of the loop is executed otherwise program control goes
outside the for loop.

Increment or Decrement: After completion of initialization and condition steps loop body
code is executed and then increment or decrements steps is execute. This statement allows to
us to update any loop control variables.

How for loop works?


 First the loop initialization statement is executed.

 Then, the test expression is evaluated. If the test expression is false, for loop is
terminated. But if the test expression is true, codes inside the body of for loop is
executed and the update expression is executed. This process repeats until the test
expression becomes false.

Note: In for loop everything is optional but mandatory to place two semicolons (; ;)

Ex 11: Write a C program to check whether the given number is prime or not.
#include<stdio.h>
int main( )
{
int n,i,fact=0;
printf("Enter a number:");
scanf("%d",&n);
for (i=2;i<n/2;i++)
{
if(n%i == 0)
fact++;
}
if(fact == 0)
printf("%d is Prime\n",n);
else
printf("%d is not a Prime\n",n);
return 0;
}

Output
Enter a number: 13
13 is Prime.
Ex 12: Write a C program to print the factorial of a given number.
#include<stdio.h>
int main( )
{
int n,i;
long int fact=1;
printf("Enter a number:");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
fact = fact*i;
}
printf("Factorial of %d is %ld\n", n, fact);
return 0;
}
Output
Enter a number: 5
Factorial of 5 is 120
Comparison between for and do, while loops
S.No For loop Do-while loop
1 Generally deterministic in nature Non-deterministic in nature
Loop index can be initialized and altered Index will be initialized outside the loop
2
with in loop
Very flexible in nature Not so flexible when compared with for
3
loop
Condition is checked at beginning of the Same in case of while loop. In do loop,
4 loop condition is checked after end of the
loop
Minimum iterations are zero Minimum iterations are zero (while)
5
Minimum iterations are one (do-while)
Pre-test loop: The condition can be tested- At the beginning is called as pre-test or entry-
controlled loop. Example: while and for loops.

Post-test loop: The condition can be tested - At the end is called as post-test or exit-
controlled loop. Example: do-while loop.

Nested loops
Insertion of one loop statement inside another loop statement is called nested loop.
Generally for loops are nested. In C loops can be nested to any desired level. General syntax
for nested for loops are:

for (initialization; test expression; updation) //outer loop


{
for (initialization; test expression; updation) //inner loop
{
body of inner for loop;
}
}
Note: generally nested for loops are used to generate patterns.

Here is an example program that uses nested loops


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

Output:
Enter number of rows: 5
*
* *
* * *
* * * *
* * * * *

Ex 13: Write a C program to print the following pattern


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

Output
Enter number of rows: 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Ex 14: Write a C program to print the Floyd‟s triangle.


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

Output
Enter number of rows: 5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

3.3. Unconditional branching statements


The break statement
In C, 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.
Its syntax is quite simple, just type keyword break followed with a semicolon.
break;
Following figure shows the sequences in break statements

The following example illustrates the use of break;


#include<stdio.h>
int main()
{
int i=1;
while( i <= 5)
{
if (i==3)
break;
printf("%d ", i);
i = i + 1;
}
return 0;
}

Output
1 2

The continue statement


In C, when continue statement is encountered inside a loop, the loop is immediately
terminated, and program control is transferred to nest statement following the loop. The
break statement is widely used with for loop, while loop, do-while loop and switch statement.
Its syntax is quite simple, just type keyword continue followed with a semicolon.
continue;
Following figure shows the sequence of actions in continue statement

The following example illustrates the use of continue;


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

The goto statement


The goto statement is used to transfers control to a specified label. Here label is an
identifier that specifies the place where the branch is to be made. Label can be any valid
variable name that is followed by a colon (:). The label is placed immediately before the
statement where the control has to be transferred.
The syntax of goto statement is:
The goto statement is often combined with if statement to cause a conditional transfer of
control.

The following example illustrates the use of goto;


#include<stdio.h>
int main( )
{
int n,sum=0;
read:
printf("\nEnter a number (999 for exit):");
scanf("%d",&n);
if(n != 999)
{
if(n<0)
goto read; //jump to label - read
sum += n;
goto read; //jump to label - read
}
printf("Sum of the numbers entered by the user is %d\n",sum);
return 0;
}

Output
Enter a number (999 for exit): 1
Enter a number (999 for exit): 3
Enter a number (999 for exit): -1
Enter a number (999 for exit): 7
Enter a number (999 for exit): 999
Sum of the numbers entered by the user is 11
Array
An array is collection of homogeneous elements that are represented under a single variable
name.
(Or)
An array is collection of same data type elements in a single entity.
 It allocates sequential memory locations.
 Individual values are called as elements.

Types of Arrays
We can use arrays to represent not only simple lists of values but also tables of data in two or
three or more dimensions.
1. One – dimensional arrays(1-D)
2. Two – dimensional arrays (2-D)
3. Multidimensional arrays (n-D)

Declaration of One-Dimensional Array


Like any other variables, arrays must be declared before they are used. The general form of
array declaration is
Syntax
datatype array_name[size];

 The data type specifies the type of element that will be contained in the array, such as int,
float, or char or any valid data type.
 The array name specifies the name of the array.
 The size indicates the maximum number of elements that can be stored inside the array.
 The size of array should be a constant value.

For example
int marks[10]; //integer array

The above statement declares a marks variable to be an array containing 10 elements. In


C, the array index (also known as subscript) start from zero. i.e. The first element will be stored
in marks[0], second element in marks[1], and so on. Therefore, the last element, that is the 10th
element, will be stored in marks[9].

Fig. memory representation of an array of elements


Examples
float temp[24]; //floating-point array
Declare the group as an array to contain a maximum of 24 real constants.

char name[10]; //character array


Declare the name as a character array (string) variable that can hold a maximum of 10
characters.

C array indices start from 0. So for an array with N elements, the index that last element is N-1

Valid Statements
 a = marks[0] + 10;
 marks[4] = marks[0] + marks[2];
 marks[2] = x[5] + y[10];
 value[6] = marks[i] * 3;

Example 1: A C program that prints bytes reserved for various types of data and space required
for storing them in memory using array.

#include<stdio.h>
int main()
{
char c[10];
int i[10];
float f[10];
double d[10];
printf("\nThe type char requires %d byte",sizeof(char));
printf("\nThe type int requires %d bytes",sizeof(int));
printf("\nThe type float requires %d bytes",sizeof(float));
printf("\nThe type double requires %d bytes",sizeof(double));
printf("\n%d memory locations are reserved for 10 character elements", sizeof(c));
printf("\n%d memory locations are reserved for 10 integer elements", sizeof(i));
printf("\n%d memory locations are reserved for 10 float elements", sizeof(f));
printf("\n%d memory locations are reserved for 10 double elements", sizeof(d));
return 0;
}

Output
The type char requires 1 byte
The type int requires 2 bytes
The type float requires 4 bytes
The type double requires 8 bytes
10 memory locations are reserved for 10 character elements
20 memory locations are reserved for 10 integer elements
40 memory locations are reserved for 10 float elements
80 memory locations are reserved for 10 double elements

5.1.1 Accessing elements the array


To access all the elements from an array, we must use a loop. That is, we can access all
the elements of an array by varying the value of the subscript into the array. But note that the
subscript must be an integral value or an expression that evaluates to an integral value.

For example
int i ,marks[10];
for (i=0; i<10; i++)
printf(“%d”,marks[i]);

5.1.2 Storing Values in Array


When we declare an array, we are just allocating space for its elements; no values are
stored in the array. There are three ways to store values in an array.
1. Initialize the array elements during declaration.
2. Input values for individual elements from the keyboard.
3. Assign values to individual elements using assignment (=) operator.

Initializing Arrays during Declaration


When an array is initialized, we need to provide a value for every element in the array.
Arrays are initialized by writing:
type array_name[size]={list_of_values};
The values are written within curly brackets and every value is separated by a comma.

For example
int marks[5]={90,87,76,69,82};

While initializing the array at the time of declaration, the programmer may omit the size of the
array. For example,
int marks[]= {98, 97, 90};

Input values from keyboard


An array can be filled by inputting values from the keyboard. In this method, a while or for loop
is executed to input the value for each element of the array. For example:

int i ,marks[10];
for (i=0; i<10; i++)
scanf(“%d”,&marks[i]);

Assigning Values to Individual Elements


The third way is to assign values to individual elements of the array by using the
assignment operator. Any value that evaluates to the data type as that of the array can be
assigned to the individual array element. A simple assignment statement can be written as
marks[3] = 100;
Here, 100 is assigned to the fourth element of the array which is specified as marks[3].

Example 2: Write a C Program to read and display N numbers using an array.


#include <stdio.h>
int main()
{
int i, n, arr[20];
printf("\n Enter the number of elements in the array : ");
scanf("%d", &n);
for(i=0;i<n;i++)
{
printf("\n arr[%d] = ", i);
scanf("%d",&arr[i]);
}
printf("\n The array elements are ");
for(i=0;i<n;i++)
printf("\t %d", arr[i]);
return 0;
}

Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
The array elements are 1 2 3 4 5

Example 3: Write a C Program to print the maximum and minimum element in the array.
#include <stdio.h>
int main()
{
int i, n, a[20], max, min;
printf("Enter the number of elements in the array : ");
scanf("%d", &n);
printf("Enter the elements\n");
for(i=0;i<n;i++)
{
printf("a[%d] = ",i);
scanf("%d",&a[i]);
}
max = min = a[0];
for(i=1;i<n;i++)
{
if(a[i]<min)
min = a[i];
if(a[i]>max)
max = a[i];
}
printf("\n The smallest element is : %d\n", min);
printf("\n The largest element is : %d\n", max);
return 0;
}

Output
Enter the number of elements in the array : 5
arr[0] = 1
arr[1] = 2
arr[2] = 3
arr[3] = 4
arr[4] = 5
The smallest element is : 1
The largest element is : 5

5.1 Searching the Array elements


Searching means to find whether a particular value is present in an array or not. If the
value is present in the array, then searching is said to be successful and the searching process
gives the location of that value in the array. if the value is not present in the array, the searching
is said to be unsuccessful. There are two popular methods for searching the array elements:
1. Linear search
2. Binary search.

Linear Search
Linear search, also called as sequential search, is a very simple method used for searching
an array for a particular value. It works by comparing the value to be searched with every
element of the array one by one in a sequence until a match is found. It is mostly used to search
an unordered list of elements. For example, if an array a[] is declared and initialized as,
int a[] = {10, 8, 2, 7, 3, 4, 9, 1, 6, 5};
and the value to be searched is VAL = 7, then searching means to find whether the value ‘7’ is
present in the array or not. If yes, then it returns the position of its occurrence. Here, POS = 3
(index starting from 0).

Example 4: Write a C Program to search an element in an array using the linear search
technique.
#include <stdio.h>
int main()
{
int a[100],n,i,key,flag=0;
printf("Enter number of elements:");
scanf("%d", &n);
printf("Enter elements\n");
/* Read array elements */
for(i=0;i<n;i++)
{
printf("Enter a[%d]=",i);
scanf("%d", &a[i]);
}
printf("Enter an element to be searched:");
scanf("%d", &key);
/* linear search starts here */
for(i=0;i<n;i++)
{
if(key==a[i])
{
printf("%d is found at position %d\n", key, i);
flag=1;
break;
}
}
if(flag==0)
printf("%d is not found\n",key);
return 0;
}

Output
Enter number of elements: 5
Enter elements
Enter a[0] = 14
Enter a[1] = 5
Enter a[2] = 23
Enter a[3] = 9
Enter a[4] = 15
Enter an element to be searched: 9
9 is found at position 3

Binary Search
Binary search is a searching algorithm that works efficiently with a sorted list.

Example 5: Write a C Program to search an element in an array using binary search.


#include <stdio.h>
int main()
{
int a[25],i,n,key,high,low,mid,flag=0;
printf("\n Enter the number of elements in the array: ");
scanf("%d", &n);
printf("\n Enter the elements\n");
for(i=0;i<n;i++)
{
printf("Enter a[%d]=",i);
scanf("%d", &a[i]);
}
printf("Enter the element to be searched: ");
scanf("%d", &key);
low = 0, high = n-1;
while(high>=low)
{
mid = (low + high)/2;
if (a[mid] == key)
{
printf("\n %d is found at position %d", key, mid);
flag = 1;
break;
}
else if (a[mid]>key)
high = mid-1;
else
low = mid+1;
}
if (flag == 0)
printf("\n %d does not found in the array", key);
return 0;
}
Output
Enter the number of elements in the array: 5
Enter the elements
Enter a[0] = 11
Enter a[1] = 26
Enter a[2] = 32
Enter a[3] = 49
Enter a[4] = 68
Enter the element to be searched: 49
49 is found at position 3

5.2 Sorting
Sorting means arranging the elements of an array in specific order may be either ascending or
descending. There are different types of sorting techniques are available:
1. Bubble sort
2. Selection sort
3. Insert sort
4. Merge sort
5. Quick sort etc.

Bubble sort, sometimes referred to as sinking sort, is a simple sorting algorithm that repeatedly
steps through the list to be sorted, compares each pair of adjacent items and swaps them if they
are in the wrong order.

Example 6: C Program to implement Bubble Sort Technique


#include <stdio.h>
int main()
{
int a[100],n,i,j,temp;
printf("Enter number of elements:");
scanf("%d", &n);
printf("Enter elements\n");
/* Read array elements */
for(i=0;i<n;i++)
{
printf("Enter a[%d]=",i);
scanf("%d", &a[i]);
}
/* bubble sort logic starts from here */
for(i=0;i<n-1;i++)
{
for(j=i+1;j<n;j++)
if(a[i]>a[j]) //> for ascending order, < for descending order
{ Output
temp=a[i]; Enter number of elements: 5Enter
a[i] = a[j]; elements
a[j] = temp; Enter a[0] = 14 Enter
} a[1] = 5 Enter a[2] = 23
} Enter a[3] = 9 Enter a[4]
= 15 Sorted elements ....
5 9 14 15 23
printf("Sorted elements .... \n");
for(i=0;i<n;i++)
printf("%3d",a[i]);
printf("\n");
return 0;
}

Selection sort is a simple sorting algorithm. This sorting algorithm is in-place comparison based
algorithm in which the list is divided into two parts, sorted part at left end and unsorted part at
right end. Initially sorted part is empty and unsorted part is entire list.

Example 7: C program to implement Selection sort technique


#include <stdio.h>
int main()
{
int a[100],n,i,j,temp; Output
printf("Enter number of elements:"); Enter number of elements: 5
scanf("%d", &n); Enter elements
printf("Enter elements\n"); Enter a[0] = 5
/* Read array elements */ Enter a[1] = 3
for(i=0;i<n;i++) Enter a[2] = 9
{ Enter a[3] = 7
printf("Enter a[%d]=",i); Enter a[4] = 2
scanf("%d", &a[i]); Sorted elements....
} 2 3 5 7 9
/* selection sort */
for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[min])
min=j;
}
temp=a[i];
a[i] = a[min];
a[min] = temp;
}
printf("Sorted elements .... \n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
printf("\n");
return 0;
}
5.3 Two Dimensional (2D) Arrays
There could be situations where a table of values will have to be stored. Consider a student table
with marks in 3 subjects.

Student Maths Physics Chemistry


Student #1 89 77 84
Student #2 98 89 80
Student #3 75 70 82

 The above table contains a total of 9 values.


 We can think this table as a matrix consisting of 3 rows and 3 columns.
 Each row represents marks of student # 1 in all (different) subjects.
 Each column represents the subject wise marks of all students.
 In mathematics, we represent a particular value in a matrix by using two subscripts such
as Vij.
 Here V denotes the entire matrix, Vij refers to the value in ith row and jth column.

In the above table V23 refers to the value “80”. C allows us to define such tables of items by using
two-dimensional arrays.

Definition
A list of items can be represented with one variable name using two subscripts and such
a variable is called a two – subscripted variable or a two – dimensional (2D) array.

5.4.1 Declaring 2-D Array


A two-dimensional array is declared as:
data_type array_name[row_size][column_size];
For example, if we want to store the marks obtained by three students in three different
subjects, we can declare a two dimensional array as:
int marks[3][3];
The pictorial form of a two-dimensional array in memory is shown in Figure.
5.4.2 Initializing Two- Dimensional Arrays
Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in curly braces.
int table[2] [3] = {0,0,0,1,1,1};
This initializes the elements of first row to zero and the second row to one.
 This initialization can also be done row by row. The above statement can be equivalently
written as
int table[2][3] = { {0,0,0}, {1,1,1} };
Commas are required after each curly brace that closes of a row, except in case of last
row.

 If the values are missing in an initializer, they are automatically set to zero.
Ex: int table [2] [3] = {
{1,1}, \\ 1 1 0
{2} \\ 2 0 0
};
 When all the elements are to be initialized to zero, the following short-cut method may be
used.
int m[3][5] = { {0}, {0}, {0}};

 The first element of each row is explicitly initialized to zero while the other elements are
automatically initialized to zero.

 The following statement will also achieve the same result


int m[3][5] = { 0 };

5.4.3 Accessing the Elements of Two-dimensional Arrays


Since the 2D array contains two subscripts, we will use two for loops to scan the
elements. The first for loop will scan each row in the 2D array and the second for loop will scan
individual columns for every row in the array.

Example 8: Write a program to print the elements of a 2D array.


#include <stdio.h>
int main()
{
int a[3][3] = {12, 34, 56,32,89,23,44,67,99}; Output
int i, j; 12 34 56
for(i=0;i<3;i++) 32 89 23
{ 44 67 99
for(j=0;j<3;j++)
printf("%d\t", a[i][j]);
printf("\n");
}
return 0;
}

5.4.4 Operations on 2D Arrays


Example 9: Write a C program to print the transpose of a given matrix
#include <stdio.h> int rows, cols, i, j;
int main() /* read the size of a matrix */
{ printf("Enter number of rows and
int a[10][10],trans[10][10]; columns:");
scanf("%d%d", &rows,&cols); {
/* Read the elements of matrix */ for(j=0;j<rows;j++)
printf("Enter elements of matrix\n"); printf("%3d",trans[i][j]);
for(i=0; i<rows;i++) printf("\n");
for(j=0; j<cols;j++) }
{ return 0;
printf("Enter a[%d][%d]=",i,j); }
scanf("%d",&a[i][j]);
} Output
/* Display the matrix A */ Enter number of rows and columns: 3 3
printf("The Matrix A\n"); Enter elements of matrix
for(i=0; i<rows;i++) Enter a[0][0]=4
{ Enter a[0][1]=7
for(j=0; j<cols; j++) Enter a[0][2]=3
printf("%3d",a[i][j]); Enter a[1][0]=9
printf("\n"); Enter a[1][1]=5
} Enter a[1][2]=2
/* Change rows into columns and columns Enter a[2][0]=6
into rows */ Enter a[2][1]=1
for(i=0;i<cols;i++) Enter a[2][2]=8
{ The Matrix A
for(j=0;j<rows;j++) 4 7 3
trans[i][j] = a[j][i]; 9 5 2
// printf("%3d",a[j][i]); 6 1 8
// printf("\n"); Transpose of a given matrix
} 4 9 6
/* Display the transpose matrix */ 7 5 1
printf("Transpose of a given matrix\n"); 3 2 8
for(i=0;i<cols;i++)

Example 10: Write a C program to perform addition or subtraction of two matrices


#include <stdio.h>
int main()
{
int a[10][10],b[10][10],c[10][10];
int rows,cols,i,j;
printf("Enter number of rows and columns (between 1 and 10):");
scanf("%d%d",&rows,&cols);
/* read the elements of first matrix */
printf("Enter elements of first matrix\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
scanf("%d",&a[i][j]);
}
/* read the elements of second matrix */
printf("Enter elements of second matrix\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
scanf("%d",&b[i][j]);
}
/* Display A and B matrices */
printf("The Matrix A\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
printf("%3d",a[i][j]);
printf("\n");
}
printf("The Matrix B\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
printf("%3d",b[i][j]);
printf("\n");
}
/*Add two matrices and print resultant matrix */
printf("The resultant matrix is\n");
for(i=0;i<rows;i++)
{
for(j=0;j<cols;j++)
{
c[i][j]=a[i][j]+b[i][j]; // for subtract, use minus (-) instead of plus (+) sign
printf("%3d",c[i][j]);
}
printf("\n");
}

return 0;
}

Output
Enter number of rows and columns (between 1 and 10): 3 3
Enter elements of first matrix: 1 2 3 4 5 6 7 8 9
Enter elements of second matrix: 1 2 3 4 5 6 7 8 9
The matrix A
1 2 3
4 5 6
7 8 9
The matrix B
1 2 3
4 5 6
7 8 9
The resultant matrix is
2 4 6
8 10 12
14 16 18

Example 11: Write a C program to perform multiplication of two matrices


#include <stdio.h>
int main()
{
int a[10][10],b[10][10],c[10][10];
int m,n,p,q,i,j,k;
printf("Enter number of rows and columns of first matrix(between 1 and 10):");
scanf("%d%d",&m,&n);
printf("Enter number of rows and columns of second matrix(between 1 and 10):");
scanf("%d%d",&p,&q);
if(n==p)
{
/* Read the elements of first matrix */
printf("Enter elements of first matrix\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d",&a[i][j]);
}
/* Read the elements of second matrix */
Print f("Enter elements of second matrix\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
scanf("%d",&b[i][j]);
}
/* Display A and B matrices */
printf("The Matrix A\n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
printf("%3d",a[i][j]);
printf("\n");
}
printf("The Matrix B\n");
for(i=0;i<p;i++)
{
for(j=0;j<q;j++)
printf("%3d",b[i][j]);
printf("\n");
}
/*multiply two matrices and print resultant matrix */
printf("The resultant matrix is\n");
for(i=0;i<m;i++)
{
for(j=0;j<q;j++)
{
c[i][j]=0; /* Initializing resultant matrix elements to zero */
for(k=0;k<p;k++)
c[i][j] += a[i][k]*b[k][j];
printf("%3d",c[i][j]);
}

printf("\n");
}
}
else
printf("Multiplication is not possible\n");
return 0;
}

Output
Enter number of rows and columns of first matrix (between 1 and 10):2 3
Enter number of rows and columns of second matrix (between 1 and 10):3 2
Enter elements of first matrix: 1 2 3 4 5 6
Enter elements of second matrix: 1 2 3 4 5 6
The Matrix A
1 2 3
4 5 6
The Matrix B
1 2
3 4
5 6
The resultant matrix is
22 28
49 64

5.4 Multi – Dimensional Array


A list of items can be represented with one variable name using more than two subscripts and
such a variable is called Multi – dimensional array.

Three Dimensional (3D) Array


A list of items can be represented with one variable name using three subscripts and such a
variable is called Three – dimensional (3D) array.
Syntax
data type array_name [size_of_2d_matrix][row_ size][column_ size];

Initializing 3D Array
Like the one-dimensional arrays, three-dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in braces.

int table[2][2][3] = {0,0,0,1,1,1,6,6,6,7,7,7};

This initializes the elements of first two dimensional (matrix) first row to zero’s and the second
row to one’s and second matrix elements are first row to six’s and the second row to seven’s.
 This initialization is done row by row.
 The above statement can be equivalently written as
int a[2][3] = {{{0,0,0},{1,1,1}},{{0,0,0},{1,1,1}}}
we can also initialize a two – dimensional array in the form of a matrix as shown.
int a[2][3] = {
{
{0,0,0},
{1,1,1}
},
{
{6,6,6},
{7,7,7}
}
};
5.5 Strings
The string in C programming language is actually a one-dimensional array of characters
which is terminated by a null character '\0'. Since string is an array, the declaration of a string is
the same as declaring a char array.

char string1[30];
char str2[7] = “String”;

The following declaration creates string named “str2” and initialized with value “String”. To hold
the null character at the end of the array, the size of the character array containing the string is
one more than the number of characters in the word.

Declaration and Initialization of Strings


The following declaration and initialization create a string consisting of the word "Hello".

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

Another way of Initialization is (shortcut for initializing string)


char greeting[] = "Hello";

Note: The C compiler automatically places the '\0' at the end of the string when it initializes the
array.

The terminating null (‘\0’) is important, because it is the only way the functions that work with a
string can know where the string ends.

Memory Representation of String


char greeting[] = "Hello";

/* Program to demonstrate printing of a Following program illustrates printing


string */ string using ‘\0’.
int main( ) int main( )
{ {
char name[ ] = “Vijayanand" ; char name[ ] = “Vijayanand" ;
int i = 0 ; int i = 0 ;
while ( i <= 9 ) while ( name[i] != ‘\0’ )
{ {
printf ( "%c", name[i] ) ; printf ( "%c", name[i] ) ;
i++ ; i++ ;
} }
return 0; return 0;
} }

And here is the output... And here is the output...


Vijayanand Vijayanand
5.6 Standard Library String Functions
With every C compiler a large set of useful string handling library functions are provided. For
using these functions, we need to include the header file string.h

Function Use
strlen() Finds length of a string
strlwr() Converts a string to lowercase
strupr() Converts a string to uppercase
strcat() Appends one string at the end of another
strcpy() Copies a string into another
strcmp() Compares two strings
strchr() Finds first occurrence of a given character in a string
strstr() Finds first occurrence of a given string in another string
strrev() Reverses the given string

strlen() function
This function counts the number of characters present in a string. Syntax for strlen() function is
given below:
size_t strlen(const char *str);

The function takes a single argument, i.e, the string variable whose length is to be found, and
returns the length of the string passed.

Note: While calculating the length it doesn’t count ‘\0’.

Example 12: C program that illustrates the usage of strlen() function.


#include<stdio.h>
#include<string.h>
int main( )
{
char str[ ] = "Henry" ;
int len1, len2 ;
len1 = strlen ( str ) ;
len2 = strlen ( "Humpty Dumpty" ) ;
printf ( "\nThe string %s length is %d", str, len1 ) ;
printf ( "\nThe string %s length is %d\n", "Humpty Dumpty", len2 ) ;
return 0;
}
Output
The string Henry length is 5
The string Humpty Dumpty length is 13

strcpy( ) function
This function copies the contents of one string into another. Syntax for strcpy() function is given
below.
char * strcpy ( char * destination, const char * source );

 Example
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.
 If destination string length is less than source string, entire source string value won’t be
copied into destination string.
 For example, consider destination string length is 20 and source string length is 30. Then,
only 20 characters from source string will be copied into destination string and
remaining 10 characters won’t be copied and will be truncated.

Example 13: C program that illustrates the usage of strcpy() function.


#include<stdio.h>
#include<string.h>
int main()
{
char source[ ] = "Sayonara" ;
char target[20]= "" ;
strcpy (destination, source ) ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nDestination string = %s", destination ) ;
return 0;
}

Output
Source string = Sayonara
Destinnation string = Sayonara

strcat( ) function
It combines two strings. It concatenates the source string at the end of the destination string.
Syntax for strcat( ) function is given below.

char * strcat ( char * destination, const char * source );

For example, “Bombay” and “Nagpur” on concatenation would result a new string
“BombayNagpur”.

Example 14: C program that illustrates the usage of strcat() function.


#include<stdio.h>
#include<string.h>
int main( )
{
char source[ ] ="Students!" ;
char target[30] = "Hello" ;
strcat ( target, source ) ;
printf ( "\nSource string = %s", source ) ;
printf ( "\nDestination string = %s", target ) ;
return 0;
}
Output
Source string = Students!
Destination string = HelloStudents!

strcmp( ) function
It compares two strings to find out whether they are same or different. The two strings
are compared character by character until there is a mismatch or end of one of the strings is
reached, whichever occurs first.
If the two strings are identical, strcmp( ) returns a value zero. If they’re not identical, it
returns the numeric difference between the ASCII values of the first non-matching pairs of
characters.
Syntax for strcmp( ) function is given below.

int strcmp ( const char * str1, const char * str2

Return Value from strcmp()


Return Value Description
0 if both strings are identical (equal)
<0 if the ASCII value of first unmatched character is less than second.
>0 if the ASCII value of first unmatched character is greater than second.

Note: strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different characters.
Example 15: C program that illustrates the usage of strcmp() function.
#include<stdio.h>
#include<string.h>
int main( )
{
char string1[ ] = "Jerry" ;
char string2[ ] = "Ferry" ; Output
int i, j, k ; 0 4 -32
i = strcmp ( string1, "Jerry" ) ;
j = strcmp ( string1, string2 ) ;
k = strcmp ( string1, "Jerry boy" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
}

Example 16: Program for checking string’s palindrome property.


#include<stdio.h>
#include<string.h>
int main()
{ Output:
char str1[25],str2[25]; Enter a string: madam
int d=0; madam is palindrome
printf("\nEnter a string:");
gets(str1); Some other palindrome strings are:
strcpy(str2,str1); civic, dad, malayalam, mom,wow etc.
strrev(str1);
d= strcmp(str1,str2);
if(d==0)
printf("\n%s is pallindrome",str2);
else
printf("\n%s is not a pallindrome",str2);
return 0;
}

5.7 getchar() and putchar() functions


The getchar() function reads a character from the terminal and returns it as an integer.
This function reads only single character at a time. You can use this method in the loop in case
you want to read more than one characters.
The putchar() function prints the character passed to it on the screen and returns the
same character. This function puts only single character at a time. In case you want to display
more than one characters, use putchar() method in the loop.
#include <stdio.h>
int main( )
{
int ch;
printf("Enter a character:");
ch=getchar();
putchar(ch);
return 0;
}

When you will compile the above code, it will ask you to enter a value. When you will enter the
value, it will display the value you have entered.

5.8 puts() and gets() functions


The gets() function reads a line or multiword string from stdin into the buffer pointed to by s
until either a terminating newline or EOF (end of file).

The puts() function writes the string s and a trailing newline to stdout.
#include<stdio.h>
int main()
{
char str[100];
printf("Enter a string:");
gets( str );
puts("Hello!");
puts(str);
return 0;
}
Output
Enter a string: New horizon
Hello! New horizon

Difference between scanf() and gets()

S.No scanf() puts()


1 It reads single word strings It reads multi-word strings
2 It stops reading characters when it It stops reading characters when it
encounters a whitespace encounters a newline or EOF
3 Example: ise Example: ise students

You might also like