0% found this document useful (0 votes)
77 views

C Programming Basics

Introduction to concepts and parts of computer and concepts of c programming and algorithms in detail

Uploaded by

vaishnavi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
77 views

C Programming Basics

Introduction to concepts and parts of computer and concepts of c programming and algorithms in detail

Uploaded by

vaishnavi
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

UNIT 1

CPU (Central Processing Unit)


• CPU is considered as the brain of the computer.
• It performs all types of data processing operations.
• It stores data, intermediate results and instructions (program).
• It controls the operation of all parts of the computer.
CPU itself has the following three components –

• ALU (Arithmetic Logic Unit)


• Memory Unit
• Control Unit
Primary Unit
The Memory unit can store instructions, data, and intermediate results. This unit supplies
information to other units of the computer when needed. It is also known as internal
storage unit or the main memory or the primary storage or Random Access Memory (RAM).

Its size affects speed, power, and capability. Primary memory and secondary memory are
two types of memories in the computer. Functions of the memory unit are −

• It stores all the data and the instructions required for processing.

• It stores intermediate results of processing.

• It stores the final results of processing before these results are released to an output
device.

• All inputs and outputs are transmitted through the main memory.

Cache Memory
• Cache memory is a very high speed semiconductor device that can speed up the CPU.

• It acts as a buffer between the CPU and the main memory.

• It is used to hold those parts of data and program which are most frequently used by
the CPU.

• The parts of data and programs are transferred from the disk to cache memory by the
operating system, from where the CPU can access them.

Secondary Memory
• The memory is also known as external memory or non-volatile.

• It is slower than the main memory.

Dr.V.Sreenivasulu KMIT Page 1


• It is used for storing data/information permanently.

• CPU directly does not access these memory it access via input-output routines.

• The contents of secondary memories are first transferred to the main memory, and
then the CPU can access it. For example, disk, CD-ROM, DVD, etc.

Control Unit
• This unit controls the operations of all parts of the computer but does not carry out
any actual data processing operations.

• It is responsible for controlling the transfer of data and instructions among other
units of a computer.

• It manages and coordinates all the units of the computer.

• It obtains the instructions from the memory, interprets them, and directs the
operation of the computer.

• It communicates with Input/Output devices for transfer of data or results from


storage.

• It does not process or store data.

ALU (Arithmetic Logic Unit)


This unit consists of two subsections namely,

• Arithmetic Section
• Logic Section
Arithmetic Section
• Function of arithmetic section is to perform arithmetic operations like addition,
subtraction, multiplication, and division.

• All complex operations are done by making repetitive use of the above operations.

Logic Section
Function of logic section is to perform logic operations such as comparing, selecting,
matching, and merging of data.

Operating System
• It is an interface between the user and computer system.

• It hides the details of the hardware resources from the users.

Dr.V.Sreenivasulu KMIT Page 2


• It acts as an intermediary between the hardware and its users, making it easier for
the users to access and use other resources.

• It manages the resources of a computer system.

• It keeps the track of who is using the resource, granting resource requests and
mediating conflicting requests from different programs and users.

Compiler
• A compiler is computer software that translates computer code written in one
programming language into another programming language.

• Compilers are a type of translator that supports digital devices, primarily computers.

• Compilers are primarily used for programs that translate source code from a high-level
programming language to a lower level language to create an executable program

Number System
Decimal Number System
• The number system that we use in our day-to-day life is the decimal number system.
Decimal number system has base 10 as it uses 10 digits from 0 to 9.

• In decimal number system, the successive positions to the left of the decimal point
represent units, tens, hundreds, thousands, and so on.

• Each position represents a specific power of the base (10). For example, the decimal
number 1234 consists of the digit 4 in the units position, 3 in the tens position, 2 in the
hundreds position, and 1 in the thousands position. Its value can be written as

Example 1234 = (1 X 1000) + (2 X 100) + (3 X 10) + (4 X 1)

= 1000 + 200 + 30 + 4

= 1234

Binary Number System


• Uses two digits, 0 and 1

• It is called as base 2 number system

• Each position in a binary number represents a 0 power of the base (2). Example 20

• Last position in a binary number represents a x power of the base (2).

• Example 2x where x represents the last position - 1.


101012= ((1 x 24) + (0 x 23) + (1 x 22) + (0 x 21) + (1 x 20))10

Dr.V.Sreenivasulu KMIT Page 3


= 16 + 0 + 4 + 1 + 0
= 2110
Octal Number System
• It uses eight digits, 0,1,2,3,4,5,6,7

• It is also called as base 8 number system

• Each position in an octal number represents a 0 power of the base (8). Example 80

• Last position in an octal number represents a x power of the base (8). Example
8x where x represents the last position – 1

Eg: 125708 = ((1 x 84) + (2 x 83) + (5 x 82) + (7 x 81) + (0 x 80))10

= 4096 + 1024 + 128 + 56 +1

= 530510

Hexadecimal Number System


• It uses 10 digits and 6 letters, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F

• Letters represent the numbers starting from 10 means A = 10. B = 11, C = 12, D =
13, E = 14, F = 15

• It is also called as base 16 number system

• Each position in a hexadecimal number represents a 0 power of the base (16).


Example, 160

• Last position in a hexadecimal number represents a x power of the base (16).


Example 16x where x represents the last position – 1

19FDE16 = ((1 x 164) + (9 x 163) + (F x 162) + (D x 161) + (E x 160))10

= 65536 + 36864 +3840 + 208 + 15

= 10646310

Dr.V.Sreenivasulu KMIT Page 4


Steps to Solve logical and Numerical Problems
1. Write algorithm that compute average of three numbers.
Step 1: Start
Step 2: Read three numbers x,y,z.
Step 3: Compute the sum of x,y and z.
Step 4: Divide the sum by 3.
Step 5: Store the result in variable avg.
Step:6 Print the value of avg.
Step 7: Stop.
2. Write the algorithm for finding the average of n numbers
Step 1: Start
Step 2: Read n numbers from key board
Step 3: Assign the value 0 to count.
Step 4: Assign the value 0 to sum.
Step 5: if the value count is equal to the value n go to the step 10
Step 6: Read the value x.
Step 7: Add the value of x to sum and store into sum variable.
Step 8: Increment the value of count by 1.
Step 9: goto step 5.
Step 10: Divide the sum by n and store the result into variable avg.
Step 11: Print the value of avg.
Step 12: Stop.
3. Write the algorithm the finds the Small and Large values from given set
of numbers.
Step 1: Start
Step 2: Read n numbers
Step 3: Assign 1 to k, a1 to Small and a1 to Large.
Step 4: Increment the value of k by 1.
Step 5: If ( ak < Small) then Small = ak.
Step 6: If ( ak > Large) then MAX = ak.
Step 7: If the value of k is less than n, then go to step 4.
Step 8: Print the values of Small and Large.
Step 9: Stop.
4. Algorithm to find greatest among three given numbers.
Step 1: Start
Step 2: Read three numbers a,b and c.
Step 3: check if (a > b) and (a > c) then a is the biggest
Step 4:Print a

Dr.V.Sreenivasulu KMIT Page 5


Step 5: else if (b > c) then b is the biggest
Step 6: Print b
Step 7: else c is the biggest
Step 8: print c
Step 9: Stop
5. Write an algorithm that finds the Fibonacci Series
Step 1: Start
Step 2: Read the number n.
Step 3: Initialize the value of A with 0 and B with 1.
Step 4: Display the values A and B.
Step 5: Initialize the counter to 2.
Step 6: Compute the next value by adding A and B and store into sum.
Step 7: Display the value of sum.
Step 8: Transfer the value of B to A.
Step 9: Transfer the value of sum to B.
Step 10: Increment the counter by 1.
Step 11: If the value of counter is less than or equal to N then go to step 6.
Step 12: Stop.

Program Design and Structure of a C Program

/* Comments about the program*/


#include<stdio.h>
#include<math.h>
----

#define MAX 25
Global variable declaration part
Void main()
{
Local variables

Executable statements
- --
}
User defines functions
{
Statement

}

Dr.V.Sreenivasulu KMIT Page 6


Introduction to C Programming Language

Properties of a Language

• To be understandable
• Need a structure
• To be meaningful

Basics of a computer

Computer is an electronic device that takes data and instructions as input


from the user and process data and provides the required information –
output.

C Program instructions / Rules

• There should be only one main in every program followed by parenthesis


and it should not be ended by :
• Opening curly braces means starting of a program.
• Each C program instruction is to be terminated by a semicolon.
• At last closing curly braces that indicates end of the program.
• Every character of the instruction is to be in the lower case.
Eg: printf () is different from PRINTF()
• Comments /*….*/ these are ignored by the compiler.
• Using double quotes leaves the quotes and prints the string.
• Kinds of main(), float main(), void main(void), void main(), int main(), char
main().

Source Program: The code that we write in English instructions is called


source code. But computer cannot understand that code. It can understand
only binary language means 1s and 0s. It can also be called machine
language. The source code can be converted by using compilation process.

Compilation: In unix, the process can be done using gcc filename.c. After
using the command, the source code can be converted into machine code.

Execution: After successful compilation, it can be executed by using ./a.out


command. Then we can see the output for the program.

Dr.V.Sreenivasulu KMIT Page 7


Sample Program:
#include<stdio.h>
void main()
{
printf(“I am learning C Programming”);
}
Output
I am learning C Programming

Applications

Standalone Applications Web Applications


The application must be installed No need to install any application
into the computer. Example: gmail , facebook,online
Eg; vlc/C language SW/ Powerpoint sbi, irctc, so on.
Format descriptions
%d --- print and scan signed decimal integer.
%u --- print and scan as unsigned decimal integer.
%s --- print and scan a string.
%f --- print and scan a float point number.
%c --- print and scan a character
%e --- print and scan scientific notations
Escape characters
\n --- new line
\t --- horizontal tabular
\v --- vertical tabular
\a --- to beep the speaker

Variables
We can store information in a variable. Named memory location is called a
variable. A variable occupies some memory space.
Eg: Seating arrangement in an examination hall.
Seating arrangement in a cinema theatre.
Identifier: Every variable has some name. It is called identifier.
Declaration of a variable and its Syntax: datatype identifier

Dr.V.Sreenivasulu KMIT Page 8


Eg: int a;
a = 10;
printf(“%d”,a);
Primitive Data Type
signed 2 bytes +ve/-ve values
short
unsigned 2 bytes +ve only

signed 2 /4 bytes +ve/-ve


integer types int
unsigned 2 /4 bytes +ve/-ve

signed 4 bytes +ve/-ve


long
unsigned 4 bytes +ve/-ve
------------------------------------------------------------------------------------------------
signed char 1 byte
char
unsigned char 1 byte
------------------------------------------------------------------------------------------------

float 4 bytes

float double 8 bytes

long double 10 bytes


------------------------------------------------------------------------------------------------
signed declaration
short a;
short int a; for all the control string is:%d
signed short a;
signed short int a;
unsigned declaration
unsigned short a; for the two the control string is: %u
unsigned short int a;

Dr.V.Sreenivasulu KMIT Page 9


Character Set A programming language needs a set of characters to write a
program. This set of characters used in a language is known as its character
set. These characters can be represented in the computer.

Tokens A C program must be a syntactically valid sequence of characters of


the language. In every C program, the most basic element recognized by the

Dr.V.Sreenivasulu KMIT Page 10


compiler is a single character or group of characters called C token. The
compiler first groups the characters into tokens.
A token is an atomic unit of source program. The compiler will not break down
the token any further.
Tokens supported in C can be categorized as keywords, constants, variables,
operators and special characters.

Tokens
Keywords Constants variables Operators Special Characters
Int 3.125 name + #

While 45.456 branch * []


Struct 2e4 marks / {}

Keywords Keywords in C are predefined reserved identifiers that have special


meaning. C strictly prohibits the usage of keywords as identifiers in your
program. The C keywords are listed in the below table. Keywords in C cannot
be redefined but by using preprocessor directives one can substitute a
keyword with a specific text.

Constants: Constants are those that are not changed their values during the
execution of the program. They are:

1. Numeric Constants 2. Character Constants 3. String Constants


Dr.V.Sreenivasulu KMIT Page 11
C Operators
1. Arithmetic Operators +, -, *, /, %, Unary +, -.
2. Assignment Operator =
3. Relational Operator <, >, <=, >=, !=, ==.
4. Increment and decrement Operators ++, --.
5. Logical Operators
! NOT && AND || OR
6. Bitwise Operators
& Bitwise AND
| Bitwise OR
>> Right Shift
<< Left Shift
~ ones complement
7. Conditional Operator ? :
Arithmetic Operators
The arithmetic Operators are used to perform arithmetic operations like
addition, subtraction and division. An arithmetic expression is one which
comprises arithmetic operators and variables or constants.
Unary + or Unary – are defined over a single operand and hence they are
called Unary Operators.
Eg: x = 10;\+x, -x are valied arithmetic expressions.
+x evaluates to 10 only
-x evaluates to -10 only.
Binary Operators: They are defined to over two operands.
A simple arithmetic expression with binary arithmetic operators is of the form.
Operator1 operator operator1
Eg: x – y;
X + 5;
5 * 8;
X / 5;
Y % 2;

Example for Arithmetic Operators


+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50

Dr.V.Sreenivasulu KMIT Page 12


/ Division 10 /5 2
% Remainder 10%5 0

Precedence and Associativity


Precedence Level Operators Associativity
I Unary +, Unary - R -> L
II *, /, % L -> R

III +, - L -> R

Example on Operator Precedence in Arithmetic Operators

#include<stdio.h>
void main()
{
int a = 6, b = 8, c = 2, d, x, y, z;
d = -a + b * c;
x = (a + b) * c;
y = a * b / c;
z = a * (b / c);

printf(“ -%d + %d * %d = %d \n”,a,b,c,d);


printf(“ (%d + %d) * &d = %d\n”,a,b,c,x);
printf(“ %d * %d / %d = %d\n”, a,b,c,y,);
printf(“ %d * (%d / %d) = %d\n”,a,b,c,z);
}
Shorthand Arithmetic Assignment Operators
x = 20;
x = x + 10; // 10 is added with x value
x += 10;// the same as the above evaluation.

In the same way

x = x – 10 can be written as x -= 10;

x = x * 10 can be written as x *= 10;

Dr.V.Sreenivasulu KMIT Page 13


x = x / 10 can be written as x /= 10;

x = x % 10 can be written as x % = 10;

Relational Operators

Relational Operators are used to construct relational expressions that are


used to compare tow numeric values or numeric expressions. A relational
expression is of the form

Syntax: Operand1 Operator Operand2

Eg: 10 < 20, 20 > 10, 10 == 10

Program on Relational Operators


#include<stdio.h>
void main()
{
int a = 2, b = 3, c, d, p, q, r, s;
printf(“Enter two numbers \ n”);
scanf(“%d%d”,&a,&b);
c = a < b;
d = a <= b;
p = a > b;
q = s >= b;
r = a == b;
s = a != b;
printf(“Less than : (%d < %d) = %d\n”, a, b, c);
printf(“D value is: (%d ,= %d) = %d” a, b, d);
printf(“ P value is (%d > %d) = %d\n”, a, b, p);
printf(“The value of r is: (%d == %d) = %d ”, a, b, r);
printf(“ Not Equal to (%d != %d) = %d\n”,a,b,s);
}

Increment and Decrement Operators

Dr.V.Sreenivasulu KMIT Page 14


The unary increment or decrement operators are used for integer type of
variables only. They are not applicable for constants or expressions. The
integer variable includes character types.

Postfix increment or decrement operates when applied to a variable in an


expression. Current value of the variable is used to evaluate an expression
and after evaluation the variable value will be incremented or decremented.

Prefix increment of decrement when applied to a variable in an expression


first. The variable value will be incremented or decremented by one. Then the
modified value of the variable is used in evaluation expression.

Example Program 1

#include<stdio.h>
void main()
{
int i=10, j, k;
j = i++;
printf(“%d\t%d\n”,i, j);

k = ++i;
printf(“%d\t%d\n”,k,i);
}
Example Program2
void main()
{
int i =10, j, k;
j = i--;
printf(“%d\t%d\n”, i, j);
k = --i;
printf(“%d\t%d\n”, i, k);
}
Logical AND and Logical OR

Logical && or Logical || can give whether the statements are true or false.
They don’t support mathematical values.

Dr.V.Sreenivasulu KMIT Page 15


If both operand are true, the result of the logical && statement will be true.
Otherwise, result will be false. Moreover, while evaluating the logical &&, if the
first operand is false, the second operand will not be evaluated.

Similarly, the result of the logical || will be true if at least one of the operands
is true. Moreover, while evaluating the logical OR operation if the first operand
is identified to be true then the second operand will not be evaluated.

Without using logical significance, in place of Logical && and Logical || we


can use *, +, however, the reverse is not possible. That is in arithmetic
statements in place of *, + we can not use logical && and Logical ||.

Logical Not (!) negates the value.

A B A && B A || B

F F F F

F T F T

T F F T

T T T T

Check the logical values


#include<stdio.h>
void main()
{
int x = 10, y = 7, a, b, c;
(x * y) ? printf(“Evaluated\n”) : printf(“Not Evaluated\n”);
(x && y)? printf(“Evaluated\n”):printf(“Not Evaluated\n”);
a = x * y;
b = x && y;
c = !a;
printf(“%d\t%d\n”, a, b);
printf(“The value of c : %d”, c);
}

Dr.V.Sreenivasulu KMIT Page 16


Command Line Arguments

It is possible to pass some values from the command line to C programs


during execution. These values are called command line arguments and
many times they are important especially to control a program from outside
instead of hard coding those values inside the code.

Dr.V.Sreenivasulu KMIT Page 17


The command line arguments are handled using main() function arguments
where argc refers to the number of arguments passed, and argv[] is a pointer
array which points to each argument passed to the program. Following is a
simple example which checks if there is any argument supplied from the
command line and take action accordingly –

// Command line arguments


#include<stdio.h>
#include<stdlib.h>

int main(int n, char *num[])


{
int x,y,z;
if(n > 2)
{

int x = atoi (num[1]);


int y = atoi (num[2]);
int z = atoi (num[3]);
printf("%d\t%d\t%d\n", x, y, z);
}
else
{
printf("Insufficient Input values\n");
}
return 0;
}

Bitwise Operators
C has a distinction of supporting special operators known as bitwise operators
for manipulation of data at bit level. The ability provided by the bitwise
operators to deal with data items at bit level will in turn help us to perform
low level functions. These operators will work on only integers.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
~ One’s Complement
<< Shift Left
>> Shift Right
Bitwise AND
Dr.V.Sreenivasulu KMIT Page 18
Syntax: Operand1 & Operand2

Where operand1 and operand2 are integer expressions. The value of the
expression would also be integer. If the corresponding bits of operand1 and
operand2 are both 1’s then the bits in the corresponding position of the result
would be 1, otherwise it would be be 0.
P Q P|Q
0 0 0
0 1 0
1 0 0
1 1 1

// Bitwise AND & Operator


#include<stdio.h>
void main()
{
int x = 5;
int y = 4;
int z;
z = x & y;
printf("The value of z is \t%d\n",z);
}

Bitwise OR
Syntax Operand1 | Operand2

where operand1 and operand2 are integer expressions. The value of the
expression will also be an integer. If the corresponding bits of operand1 and
operand2 are both 0s, then the bit in the corresponding position of the result
would be 0. Otherwise, it will be 1.

P Q P|Q
0 0 0
0 1 1
1 0 1
1 1 1

// Bitwise AND & Operator


#include<stdio.h>

Dr.V.Sreenivasulu KMIT Page 19


void main()
{
int x = 5;
int y = 4;
int z;
z = x | y;
printf("The value of z is \t%d\n",z);
}

Bitwise Exclusive OR
Syntax Operand1 ^ Operand2

where operand1 and operand2 are integer expressions. The value of the
expression will also be an integer. If any one of the bits of operand1 and
operand2 is 1 then the bit in the corresponding position of the result will be 1,
otherwise it will be 0.
P Q P|Q
0 0 0
0 1 1
1 0 1
1 1 0
// Bitwise AND & Operator
#include<stdio.h>
void main()
{
int x = 5;
int y = 4;
int z;
z = x ^ y;
printf("The value of z is \t%d\n",z);
}

Bitwise Shift Left (<<)

The bitwise shift left operator is used to shift the given number of bits of an
integer towards left. The vacant positions on the right of the integer will be
filled with zeros. The syntax is as follows.

Syntax Operand << x


Dr.V.Sreenivasulu KMIT Page 20
where x is the number of bits of operand to be shifted towards left.

Example:

int x = 5;

Binary Equivalent of x 0000 0000 0000 0101

After x << 4 0000 0000 0101 0000

Bitwise Shift Right (>>)

The bitwise shift right operator is used to shift the given number of bits of an
integer towards right. The vacant positions on the left of the integer will be
filled with zeros. The syntax is as follows.

Syntax Operand >> x

where x is the number of bits of operand to be shifted towards right.

Example:

int x = 5;

Binary Equivalent of x 0000 0000 0000 0101

After x >> 2 0000 0000 0000 0001

Bitwise Complement (~)

The bitwise one’s complement operator is used to invert the bits of an integer.
That is, it replaces all ones by zeroes and all zeroes by ones of an integer.

int x = 5;

Binary Equivalent of x 0000 0000 0000 0101

After ~ x 1111 1111 1111 1010

Conditional Operators

Dr.V.Sreenivasulu KMIT Page 21


The conditional Operator (? :) is used to construct conditional expressions. It
is somewhat the substitute of if .. else construct. The format of ternary /
conditional operator is as follows.

Expression = expression-1 ? expression-2 : expression-3;

In the above format, first expression is evaluated if it is true, then the value of
expression-2 is assigned to expression otherwise, the value of expression-3 is
assigned to expression.
Example: int x = 5, y = 10, large;
Large = (x > y) ? x : y;
Program
#include<stdio.h>
void main( )
{
int x, y, large;
printf(“Enter x value and y value..”);
scanf(“%d%d”,&x,&y);
large = (x > y) ? x: y;
printf(“The large value is %d”, large);
}

Conditional Branching and Loops


The conditional statements are mainly used for decision making. The following
statements are used to perform the task of the conditional operations.

i. Single way selection


ii. Two way selection
iii. Multiway selection

Single way Selection ( simple if statement)

The if statement is used to control the flow of statements. The general form of
if statement is
If ( Conditional - expression)

Dr.V.Sreenivasulu KMIT Page 22


{
Statements;

}
Statement;

Example: Find out the given number is a positive or not.

#include<stdio.h>
void main( )
{
int number;
printf(“ Enter a number …”);
scanf(“%d”,&number);
if (number > 0)
{
Printf(“The given one is a positive number\n”);
}
}
Two Way Selection

It is very clear that the simple if statement will not sufficient to implement
selection which involves complex conditions. We can use variation of if
structures depending on the degree of the complexity of the conditions to be
checked.
if( conditional - expression)
{
Statement block1;
}
else
{
statement- block2;
}
statements;
.
.
.

Dr.V.Sreenivasulu KMIT Page 23


If conditional – expression evaluates to true, statement – block2 will be
executed. Statement block2 is skipped. If it evaluated false, statement –
block2 will be executed. If block statement are skipped.

Example. Read marks of a student then determine whether he passed or failed


the examination. Consider pass mark is 35.
#include<stdio.h>
void main()
{
int marks;
printf(“Enter marks of a student…”);
scanf(“%d”, &marks);
if( marks >= 35)
{
printf(“The student is passed\n”);
}
else
{
printf(“The student is failed\n”)
}
}

if ..else

If execution of a block of statements is conditional, we can use one if


statement. What if the conditional execution of the block is itself conditional?
Here we need to enclose one if statement within another if statement. On the
similar manner, we can even enclose on if..else within another if..else.

Here, on if..else is enclosed within another if..else. the ei..else which enclosed
another is called outer if. The if..else which is enclosed within another is called
inner if..else. statement – 1, statement – 2 and statement – 3 are three block of
statements for execution proceeds.

Example: A Program that reads marks of a student that determines whether he


got first class, second class, third class or failed.
#include<stdio.h>
void main( )
Dr.V.Sreenivasulu KMIT Page 24
{
int marks;
printf (“Enter marks of a student…” );
scanf (“%d”, &marks);
if (marks > 35 )
{
if (marks >= 60 )
printf(“First Class\n”);
else if(marks>50 ) prinf(“Second Class\n”);
else printf(“Third Class\n”);
}
else printf(“Failed\n”);
return 0;
}

else if ladder

There is another way of putting ifs together when multipath decisions are
involved. A multipath decision is a chain of ifs in which the statement
associated with each else is an if.

if (conditional – expression)
statement1
else if ( conditional – expression 2)
statement - 2
else if (conditional – expression 3)
statement - 3
else if (conditional – expression 4)
statement - 4
else default-statement;
statement – x;

Example: Read marks of a student and determine whether he got first class,
second class, third class or failed.
void main()
{
int marks;
printf(“Enter marks of a students..”);

Dr.V.Sreenivasulu KMIT Page 25


scanf (“%d”, & marks);
if ( marks >= 60) printf(“First Class”);
else if (marks >= 50) printf(“Second Class”);
else if( mark >= 35) printf(“Third Class”);
else printf(“Failed”);
}
Switch case
Whenever we want to check more possible conditions for a single variable, a
number of statements are necessary. For example, to check the category of
employee, the following code has to be used.
if (category == 1)
printf(“Principal”);
if (category == 2)
printf(“Professor”);
if (category == 3)
printf(“Associate Professor”);
if (category == 4)
printf(“Assistant Professor”);
It seems to be repeatedly, we have used if statements and also code has been
length. A switch case is an alternative for it which reduces the size of the code.
A general format of switch case
switch(Condition)
{
case value-1: statement 1;
break;
case value-2: statement 2;
break;
case value-3: statement 3;
break;
case value-4: statement 4;
break;
default: statement n;
}
How to execute
1. First the conditional expression is evaluated then it nust return a
constant value. The constant value can be numeric or character.
2. The result of expression is checked against the constant values like
statement 1, statement2 so on and finally matches the value. If any one
Dr.V.Sreenivasulu KMIT Page 26
is matched, the execution starts. At last by seeing the break statement in
that block, the control comes out of that block.

Example: Add two numbers using switch case.

void main( )
{
int x, y, z, ch;

printf (“Enter X and Y values…”);


scanf (“%d%d”,&x.&y);
printf (1.Addition 2. Subtraction 3. Multiplication 4. Division);
printf (“Select a choice…”);
scanf (“%d”, &ch);

switch ( ch )
{
case 1: z = x + y;
break;

case 2: z = x - y;
break;

case 1: z = x * y;
break;

case 1: z = x / y;
break;

default: printf (“Invalid choice”);

Dr.V.Sreenivasulu KMIT Page 27


While – loop
The C language has the ability to repeat some calculation or sequence of
instructions over and over again. Each time, it uses different data. The
iterative structure consists of entry point that includes initialization of
variable, a loop continuation condition, a loop body and an exit point. The
statements that permit C language to perform iterations are:

i. while loop
ii. for loop
iii. do..while

While loop

The statements in the while block may be a single statement or a block of


statements that are to be repeatedly executed as long as the condition is true.
When the condition becomes false, the control comes out of the while block.

Three things to be carefully observed;

i. initialization
ii. condition
iii. increment/decrement
Example1: A program that prints numbers from 1 to n;

#include<stdio.h>
void main( )
{
int num,i;
printf (“Read n from the key board”);
scanf(“%d”,&num);
i=1;
printf(“Printing numbers from 1 ot %d”, num);
while(i < num)
{
printf(“%d”, i);
i++;

Dr.V.Sreenivasulu KMIT Page 28


}
}
Example1: A program that prints numbers from n to1;
#include<stdio.h>
void main( )
{
int num,i;
printf (“Read n from the key board”);
scanf(“%d”,&num);
i = num;
printf(“Printing numbers from 1 ot %d”, num);
while( i > 0)
{
printf(“%d”, i);
i--;
}
}
Do…while loop
The structure of do..while loop is similar to while loop. The difference is that in
case of do..while loop the expression is evaluated after the body of loop is
executed. If it is false, then it will be terminated. It means the loop is executed
at least once irrespective of the condition.
Do
{
Statements;
}while(condition-expression);

Example: Read n numbers and print all from 1 to n;


#include<stdio.h>
void main( )
{
int num,i;
printf (“Read n from the key board”);
scanf(“%d”,&num);
i=1;
printf(“Printing numbers from 1 ot %d”, num);
do

Dr.V.Sreenivasulu KMIT Page 29


{
printf(“%d”, i);
i++;
} while(i < num);

}
For loop
The for loop is most common in major programming languages. However, the
for loop in C language is very flexible and very powerful. Generally, the for loop
is used to repeat the execution of a statement for fixed number of times.

The general form of the loop is


for (initialization: condition-expression;increment)
{
Statement-block;
}
statement – x;
Execution sequence of the for loop
1. Initialization statement is executed.
2. Conditional-expression is evaluated.
3. If the conditional – expression evaluates to true, the statement in the body
of the loop will get executed.
4. Control goes to the increment/decrement statement to execute.
5. It repeats as long as the condition is true.
6. If it fails, the control comes of the loop.

Example: To find the factorial of a number


#include<stdio.h>
void main( )
{
int num, i, fact =1;
printf (“Enter a number …”);
scanf (“%d”,&num);

for (i = 1; i <= n; i++)


{
fact = fact * I;
}

Dr.V.Sreenivasulu KMIT Page 30


printf(“ Factorial of %d is %d”, num, fact);
}

===

Dr.V.Sreenivasulu KMIT Page 31

You might also like