0% found this document useful (0 votes)
34 views46 pages

UNIT-1 C Programming

C Programming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
34 views46 pages

UNIT-1 C Programming

C Programming
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 46

21IT2151 Programming in C

UNIT-1 Basics of C Programming


Structure of C program - C programming: Data Types –Keywords – Variables - Operators:
Precedence and Associativity - Expressions – Input / Output statements Decision making
statements - Looping statements – Pre-processor directives - Compilation process. Illustrative
problems: To Check a year is leap year or not, Sum of Digits of a number, Implement
Calculator Program.

1. INTRODUCTION
 C is general-purpose programming language, developed by Dennis Ritchie between
1969 and 1973 at AT&T Bell Labs.
 In 1972, Dennis Ritchie developed C language, combining the features of B and
BCPL language at bell laboratories.
 C is a structured, procedural, case sensitive, portable programming language.
 C is a middle level language.
1.1 Features of C Language
 C is a robust language with rich set of built-in functions and operators.
 Programs written in C are efficient and fast.
 C is highly portable, programs once written in C can be run on another machines
with minor or no modification
 It is a collection of C library functions; User can create their own function and add
it to the C library.
 It is a Procedural Oriented Language.
 Procedural Programming divides the program into procedures, which are also
known as routines or functions, simply containing a series of steps to be carried out.
 It groups the code in function. This modular structure makes code debugging,
maintenance and testing easier.
 It uses top-down approach.
 It does not provide Object Oriented Programming (OOP) concepts.
 It is difficult to relate with real world objects.
2. STRUCTURE OF C PROGRAM
A skeleton of a C program is given below

Comments section/Documentation section


Pre-processor section
Definition section
Global declaration
void main()
{
Local Declaration part;
Executable part;
}
Function1 ()
{
Local Declaration part;
Executable part;
}
FunctionN ()
{
Local Declaration part;
Executable part;
}

Example
//Program for finding area of a circle
#include<stdio.h>
# define pi 3.14
float r = 4.5;
void main()
{
float area;
area=pi*(r*r);
printf("The Area of a circle %f",area);
}
Output:
The Area of a circle 63.584999
2.1 Comment section
Comments used to provide information about lines of code..It is not processed by the
compiler. Two types of comments are
 Single line comments //: used when there is a single line to comment
 Multiline comments /* */: used when there is multiple lines to comment.
2.2 Pre-processor section
 Pre-processor section tells the complier to link the needed header file during compilation
 It starts with pound symbol (#).It is not terminated with semicolon.
 #include<stdio.h>
#include<conio.h>
2.3 Definition Section
This section contains all Symbolic constants
# define PI 3.14
2.4 Global declaration section
It contains variable declaration which can be accessed anywhere within the program.
Example
int a;
main ()
{

}
2.5 main () function
 Each and every C program should have only one main () function.
 The execution of C program begins at this function.
 The main() section is divided into two portions
i) Declaration part: It describes the data that will be used in the function. Data
declared within the function are known as local declaration.
ii) Executable part: contains s set of statements executed by the computer
2.6 User defined function section
 User defined function section or sub-program section contains user defined functions
which are called by main function.
 Each user defined function contains return type, function name and argument list.
Each function performs some specific tasks.
 User defined functions are generally placed immediately after the main () function.
They may appear in any order.
3. C PROGRAMMING: DATA TYPES
Data types simply refer to the type and size of data associated with variables and
functions.
Datatype Keyword used Size in bytes Range Use
Character char 1 -128 to 128 To store Characters
Integer int 2 -32,768 to To store Integers
32,767 numbers
Floating point float 4 3.4*10-38 to To store floating
3.4*1038 point numbers
Double double 8 1.7*10 -308 to To store floating
1.7*10 308 point numbers
Valueless void 0 Valueless -

 Type modifiers: Modifies the basic data type to new data type. It modifies the range and
the arithmetic properties of basic data type. The modifiers are signed, unsigned, short and
long.

Data type Size(bytes) Control Range


[1 byte=8 bits] string
char/signed char 1 %c -128 to 128
int/signed int 2 %d -32,768 to 32,767
float 4 %f 3.4*10-38 to 3.4*1038
double 8 % lf 1.7*10 -308 to 1.7*10 308
unsigned char 1 %c 0 to 255
unsigned int 2 %d 0 to 65535
short int 2 %d -32,768 to 32,767
long int 4 %f 3.4*10-38 to 3.4*1038
long float 8 %lf 1.7*10 -308 to 1.7*10 308
long double 10 %lf 3.4*10-4932 to 1.1*104932

 Derived data type: The data type that is derived from basic data type is called derived data
type. Examples: Arrays, functions and pointers
 User defined data type: The user creates a new data type called as user defined data type.
Example structure, union and enumeration.
 Smaller data types take less memory.
Example1:

#include <stdio.h>
void main()
{
int a=10,b=20,c;
c=a+b;
printf("The sum is %d",c);

}
Output:
The sum is 30

Example2:

#include <stdio.h>
void main()
{
float a=10,b=20,c;
c=a+b;
printf("The sum is %f",c);

}
Output:
The sum is 30.000000
Example 3:
#include <stdio.h>

void main()
{
double a=10,b=20,c;
c=a+b;
printf("The sum is %f",c);

}
Output:
The sum is 30.000000000000000
Example 4:

#include <stdio.h>

void main()
{
char c='d';
printf("The Character is %c",c);

}
Output:
The Character is d

4. KEYWORDS
 Keywords are reserved words whose meaning has already explained to the compiler.
 C is a case sensitive language, all keywords must be written in lowercase.
 Keywords are part of the syntax and they cannot be used as an identifier.
 There are 32 reserved keyword.
 Eg int marks;
int is a keyword
mark is a variable
C Keywords

auto double int struct

break else long switch

case enum register typedef

char extern return union

continue for signed void

do if static while

default goto sizeof volatile

const float short unsigned

5. VARIABLES
A variable is defined as a meaningful name given to the data storage location in computer
memory.
It refers to the address of the memory where data is stored.
int n1=10;
n1 is a variable name that holds a constant 10.
5.1 Rules for defining variables
 Variable name in C can have letters, digits or underscores.
 The first character of the variable must be a letter or an underscore.
 Variable name should not start with digits.
 Both upper and lower case letters are permitted.
 C program is case sensitive. Uppercase letters are not equivalent to lower case letters
 Variable name cannot be a keyword.
Example:
Student_name, student1,_student are valid variable names
The declaration of variable is done before they are used in the program
Syntax:
datatype variablename;
int n1;

datatype var1,var2,…,var;
:int n1,n2,n3,n4;
5.2 Initializing a variable:
A variable can be initialized using assignment operator. Declaration and initialization can
be done in single statement.
Syntax:
datatype variablename = value;
Example: int n1=10;
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=20,c;
clrscr();
c=a+b;
printf("A is %d",a);
printf("\nB is %d",b);
printf("\nThe sum is:%d",c);
getch();

}
Output
A is 10
B is 20
The sum is :30
In C variables are declared at three places
 When the variable is declared inside a function it is known as local variable
 When the variable is declared outside a function it is known as global variables
 When the variable is declared in the definition of function parameters it is known as
formal parameter.
6. OPERATORS: PRECEDENCE AND ASSOCIATIVITY
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. An operator is a symbol that operates on a value or a variable.

Operator precedence and Associativity are two characters of operator and determines the
evaluation order of sun expression in the absence of brackets.

Operator precedence determines which operator is performed first in an expression with more
than one operators with different precedence.
Example:
1+2*3
1 + 2 * 3 is calculated as 1 + (2 * 3) and not as (1 + 2) * 3

Operators Associativity is used when two operators of same precedence appear in an


expression. Associativity can be either Left to Right or Right to Left.

For example: „*‟ and „/‟ have same precedence and their associativity is Left to Right, so the
expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.

 Associativity is only used when there are two or more operators of same precedence.
 All operators with the same precedence have same associativity
 Precedence and associativity of postfix ++ and prefix ++ are different
 Precedence of postfix ++ is more than prefix ++, their associativity is also different.
Associativity of postfix ++ is left to right and associativity of prefix ++ is right to left.
 Comma has the least precedence among all operators

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right


Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Comma , Left to right

6.1 Classification based on Operands


1. Unary operator Example:
Unary operator is operators that act upon a single operand to produce a new value
Example: -8(1 operand)

Operator Meaning
- Minus
++ ++
-- Decrement
& &
Address- of operator Address- of operator

2. Binary operator
A binary operator is an operator that operates on two operands and produces a new value.
Example: a+b (2 operand)

Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modular
&& Logical AND

3. Ternary operator
A Ternary operator is an operator that operates on three operands and produces a new
value. ?:
Example: (a>b)? b:c (3 operand)

6.2 Types of operators


C programming language offers various types of operators having different functioning capabilities.
S.No Types of Operators Description
1 Arithmetic operators +,-,*,/, %
2 Assignment operators =,+=,-=,/=,%=,*=
3 Relational operators >, <, <= , >= , == , !=
4 Logical operators &&, || , !
5 Bit wise operators <<,>> ,~ ,^, &, !
Conditional (ternary)
6 ?:
operators
Increment/decrement
7 ++ , --
operators
8 Special operators &, *, sizeof( )

6.2.1Arithmetic Operators
C Arithmetic operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus in C programs

Arithmetic operation Example value


operator
+ Addition 2+3 5
- Subtraction 9-2 6
* multiplication 2*3 6
/ Division 9/3 3
% Modulus 9%2 1

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=50,b=10,c;
clrscr();
c=a+b;
printf("The sum:%d",c);
getch();

}
Output:
The sum is 60
6.2.2 Relational Operators
 A relational operator checks the relationship between two operands. If the relation is true, it
returns 1; if the relation is false, it returns value 0.
 Relational operators are used in decision making and loops.
Operator Meaning Example value
> Greater than 2>3 0
< Less than 2<3 1
>= Greater than or equal to 2 >= 3 0
<= Less than or equal to 2 <= 3 1
== Equal to 2 == 3 0
!= Not equal 2!=3 1

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=50,b=10;
clrscr();
printf("%d", a>b);
getch();

}
Output:
1

6.2.3 Logical Operators


 Logical operators combine the result of two or more logical conditions.
 An expression containing logical operator returns either 0 or 1 depending upon whether expression
results true or false.
 Logical operators are commonly used in decision making in C programming.

operator meaning Example value


&& Logical AND (2 > 3)&&(4>1) 0
|| Logical OR (2 >3)||(4>1) 1
! Logical NOT !(2>3) 1

Logical AND Logical OR Logical NOT

C1 C2 C1&&C2 C1 C2 C1||C2 C1 !C1


0 0 0 0 0 0 0 1
0 1 0 0 1 1 1 0
1 0 0 1 0 1
1 1 1 1 1 1
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=9,c;
clrscr();
c=(a<b)||(a>b);
printf("c is %d",c);
getch();
}
Output:
c is 1

6.2.3 Assignment Operators


 An assignment operator is used for assigning a value to a variable.
 The most common assignment operator is =
 Two types
a. Simple Assignment operator
b. Compound Assignment operator

Operator Meaning Example


Simple Assignment operator
= a=5 a=5
Compound Assignment operator
+= a += b a = a+b
-= a -= b a = a-b
*= a *= b a = a*b
/= a /= b a = a/b
%= a %= b a = a%b

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=10;
clrscr();
sum=sum+10;
printf("The sum:%d",sum);
getch();
}

Output:
The sum :20

6.2.4 Increment and Decrement Operators


 Increment ++ increases the value by 1 whereas decrement -- decreases the value by 1.
 These two operators are unary operators, meaning they only operate on a single operand.

Operator Meaning
++a Pre increment
--a Pre decrement
a++ Post increment
a-- Post decrement

Prefix
The operator precedes the operand (e.g., ++a). The value of operand will be altered
before it is used.
Postfix
The operator follows the operand. he value operand will be altered after it is used.
Program
#include <stdio.h>
#include<conio.h>
void main()
{
int c=2;
clrscr();
printf("c=%d\n",c++); //this statement displays 2 then,only incremented by 1to 3.
printf("c=%d",c); //this statement increments 1 to c then,only c is displayed.
getch();
}
Output:
C=2
C=3
6.2.5 Conditional Operator
 Conditional operators return one value if condition is true and returns another value is
condition is false.
 This operator is also called as ternary operator.
 Syntax : (condition? True_value: false_value);

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=2,c;
clrscr();
c=a>b?a:b;
printf("The value of c is %d",c);
getch();
}
Output
The value of c is 10
6.2.6 Bitwise Operators
These operators are used to manipulate data at bit level. It operates on integers only.
operator meaning Example
& Bitwise AND 2 &3
| Bitwise OR 2|3
^ Bitwise XOR 2^ 3
<< Shift left 2 << 3
>> Shift right 2 >>3
~ one‟s compliment ~2

Bitwise AND Bitwise OR Bitwise OR

a b a&b a b a|b a ~a
0 0 0 0 0 0 0 1
0 1 0 0 1 1 1 0
1 0 0 1 0 1
1 1 1 1 1 1

Bitwise XOR

a b a^b

0 0 1

0 1 0

1 0 0

1 1 0

Program
#include<stdio.h>
void main()
{
int a=12,b=25,c;
c=a&b;
printf("The value of c is %d",c);
}
Ouput:
The value of c is 1
E.g. 12 = 00001100 (In Binary)
25 = 00011001 (In Binary)
Bit Operation of 12 and 25
00001100
& 00011001

________
00001000 = 8 (In decimal)
Bitwise OR Operation of 12 and 25
00001100
| 00011001
________
00011101 = 29 (In decimal)
7 << 2 (Shift Left)
0011
1100=12
3 >> 1 (Shift Right)
11 1=1

6.2.7 Special Operators

Operator Meaning
, Comma operators are used to link
related expressions together
& Address of operator
* Pointer to a variable
Sizeof () Returns length of variable in bytes
Program
#include <stdio.h>
int main()
{
int a;
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
return 0;
}

Output:
Size of int = 4 bytes
Size of float = 4 bytes
Size of double = 8 bytes
Size of char = 1 byte

6.2.8 Unary operators

S.NO Operator Meaning


1 + Unary plus operator; indicates positive value
2 - Unary minus operator; negatesan expression
3 ++ Increment operator; increments a value by 1
4 -- Decrement operator; decrements a value by 1
5 ! Logical complement operator; inverts the value of a Boolean.
6 & Addressof operator
7 sizeof() Returns length of variable in bytes

7. EXPRESSIONS – INPUT / OUTPUT STATEMENTS


7.1 Expression

Expression is a sequence of operands and operators that specifies the computation of the
value.
Example: a=2+3
2, 3 operands
+ = operator
Simple Expression:
If it has only one operator then it is called simple expression.
Example a=2+3
Compound Expression:
If it has more than one operator then it is called Compound expression
Example: A=2+3*5\4

7.2 Input and Output Statements


2.3.1 Streams
Streams acts in two ways. It is a source of a data as well as destination of data programs
input and output data from a stream.
We can input/output from the keyboard/monitor or from any file.
Keyboard Input stream Data gets stored in
variable

Monitor Output stream Data from memory

Input and output streams


The input/output functions in „C‟ is classified into two types
i) Formatted Input/output functions
ii) Unformatted Input/output functions

7.2.1 Formatting Input / Output


 C supports two formatting functions printf and scanf.
 When I/P & O/P is required in a specified format then the standard library functions
scanf( ) & printf( ) are used.
 printf is used to convert data stored in the program into text stream for output to the
monitor
 Scanf is used to convert text stream from the keyboard to data values and store them
in a program variables.
 These functions are collectively known as Standard I/O Library and is in stdio.h
header file.
 Formatted input, output functions can be used to read and write all types of data
values.

printf ( )
 The printf function stands for print formatting.
 It is used to display information required by the user and also prints the values of the
variables.
Syntax:
printf (“The text to be printed“);
printf (“control string”, var1,var2,…,varn);
 Some printf statements may contain only a text string that has to be displayed on the screen.
 The control string may also contain text to be printed, specific format specifier and escape
sequence include \n,\t,\r,\a etc.

scanf ()
 The function scanf () stands for scan formatting.
 It is used to read formatted data from the keyword.
 It ignores any blank spaces, tabs, new lines entered by the user.
Syntax:
scanf(“control string”,&var1,&var2….,&varn);

Example:
int age;
scanf(“%d”,age);

 control string specifies type and format of the data that has to be obtained from
the keyboard and stored in the memory location of the variable.& is a unary
operator, stores the value in the address of a variable
 Basic control string

Data type Control String/Format Specifier


int %d
float %f
char %c
string %s

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
clrscr();
printf("Enter the number");
scanf("%d",&num);
printf("The number is %d",num);
getch();
}
Output:
Enter the number 45
The number is 45
7.2.2 Unformatted Input /Output function
 It does not require any format specifier.
 It works with character data type.
 They are used when I/P & O/P is not required in a specific format.
 C has 3 types I/O functions.
a) Character I/O
b) String I/O
c) File I/O

a) getchar() and putchar():


getchar():It read a single character from the keyword.
putchar():It prints single character on the screen at a time.
Syntax
char variablename = getchar();
putchar(variablename);

Example
char ch;
a=getchar();
putchar(a);
Progrm
#include<stdio.h>
#include<conio.h>
void main()
{
char a;
clrscr();
printf("Enter the charcter\n");
a=getchar();
putchar(a);
}
Output:
Enter the Character
a
a

b) gets() and puts()


gets():It accepts any line of string including spaces from input devices. It stops reading
only when the enter key is pressed.
puts():displays the string on the output screen
Syntax
gets(variablename);
puts(variablename);
Example:
gets(a);
puts(a);

Program
#include<stdio.h>
#include<conio.h>
void main()
{
char a[10];
clrscr();
printf("Enter the string\n");
gets(a);
puts("The string is");
puts(a);
getch();
}
Output:
Enter the string
C programming
The string is
C programming

c) getch() and putch()


getch(): getch() is used to get a character from keyboard but does not echo to the output screen.
putch(): putch() is used to writes a character directly on the output screen.

Syntax:
char variablename=getch();
putch(variablename);
Example:
char ch;
ch= getchar();
putch(ch);
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter the character \n");
ch= getchar();
printf("\nEntered charcter is\n");
putch(ch);
getch();
}
Output:
Enter the character
A
Entered character is
A
c) getche(): getche() reads a single character from the keyboard and echoes it to the output
screen
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
char ch;
clrscr();
printf("Enter the string");
ch= getche();
printf("Input char %c",ch);
getch();
}
Output:
Enter the string t
Input char t.

7.2.3 Difference between scanf() and gets()


S.No scanf() gets()
1 It does not read blank spaces in It reads string with blank
between the string space
2 Example: Example:
Input: Hello world Input: Hello world
Output: Hello Output:Hello world
9.3.6 Difference between printf() and puts()
S.No printf() puts()
1 In printf() we use \n to move the In puts() it automatically
cursor to next line moves the cursor to next line
9.3.7 Difference between getch() and getche()
S.No getch() getche()
1 getch() is used to get a character getche() reads a single
from keyboard but does not echo character from the keyboard
to the output screen. and echoes it to the output
screen
9.3.8 Difference between getchar() and getch()
S.No getchar() getch()
1 After reading the character from After reading the character
keyboard, it is kept in buffer. from keyboard, it display and
After pressing ENTER key it is it never waits for enter key to
displayed on the screen pressed
8. DECISION MAKING STATEMENTS
 The order in which program statements are executed is known as flow of control.
 By default program control flows sequentially from top to bottom.
 C supports two types of decision control statements that can alter the flow of a sequence of
instruction.
i) Conditional branching
ii) Unconditional branching
8.1 Conditional branching

 The conditional branching statements help to jump from one part of the program to another
depending on a whether a particular condition is satisfied or not.
 These decision control statements include
i) if statement
ii) if else statements
iii) if else if statement
iv) nested if else
v) switch

8.1.1 if statement
 It is a simple decision making statement. It executes only true condition statements.
 It checks for the condition .If the condition is true, if block statements are executed.

Syntax

if (condition)
{
statements;
}

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
printf("Enter the number");
scanf("%d",&a);
if(a>=0)
{
printf("%d is a positive number ",a);
}
}
Output:
Enter the number
12
12 is a positive number
8.1.2 if..else statement
 It is also called as two way decision statement
 If the condition is true, if block statements are executed and else block is skipped.
 If the condition is false, else block is executed and if block is skipped.
Syntax
if(condition)
{
Statements;
}
else
{
Statements;
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("Enter the number");
scanf("%d",&a);
if(a>=0)
{
printf("\n %d is a positive number ");
}
else
{
printf("\n %d is a negative number");
}

getch();
}
Output:
Enter the number
-12
12 is a negative number
8.1.3 if else if statement
 It is known as multiway decision making statement.

 Each and every else block have if statement except last else block.

 Syntax
if( condition)
{
Statements;
}
else if(condition)
{
Statements;
}
else if(condition)
{
Stateemnts;
}
else
{
Statements;
}
Program:
#include<stdio.h>
#include<conio.h>
void main()
{
int num;
printf("Enter any number");
scanf("%d",&num);
if(num==0)
{
printf("The numeber is zero");
}
else if(num>0)
{
printf("The number is positive");
}
else
{
printf("The numeber is negative");
}
}
Output:
Enter any number -2
The number is negative
8.1.4 Nested if..else
An if statement or if..else statement in another if..else statement is called as Nesting
and the statement is called nested if..else statements.
syntax
if(condition1)
{
if(condition2)
{
true Statement of condition2;
}
else
{
False Statement of condition 2;
}
}
else
{
False Statement of condition 1;
}
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a=10,b=20,c=40;
if((a>b)&&(a>c))
{
printf("%d is greatest",a);
}
else
{
if(b>c)
{
printf("%d is greatest",b);
}
else
{
printf("%d is greatest",c);
}
}

}
Output:
40 is greatest

8.1.4 Switch Statement


 It is a multiway decision making statement. The selection is based on the valued in the
switch statement.
 When there are more conditions, it becomes too difficult and complicate to use if and if.
else statement
Syntax
switch(expression)
{
case constant1 :
statement block1;
break;
case constant2:
statement block2;
break;
.
. .
default :
default block;
break;
}

 Expression value must be integer or character.


 Each case label should be followed with a constant
 Case labels must end with a colon
 Each case block and default block must be terminated with break statements
 No case constants are identical
 The default label is optional and can be placed anywhere in the switch statement.
 There can be only one default statement in a switch statement.
 C permits nested switch statement.
 The value of switch expression is compared with the case constant expression from top
to bottom.

Program
#include<stdio.h>
#include<conio.h>
void main()
{
int i=1;
switch(i)
{
case 1:
printf("One”);
break;
case 2:

printf("Two”);
break;
default:
printf(“Above Three”);
}
getch();
}
Output:
One
Unconditional Statements
Jump statements are used to transfer the control from one part of the program to another part. The
various jump statements in C are as under:-
1. break statement
2. continue statement
3. goto statement
4.return statement

break statement:-
break statement is used inside the loops or switch statement.
This statement causes an immediate exit from the loop or the switch case block in which it appears.
It can be written as break;

9. LOOPING STATEMENTS
Iteration is a process of repeating the same set of statements again and again until
specified condition becomes false
There are 3 types
i) for
ii) while
iii) do-while
Loops are classified as
 Counter controlled loops
 Sentinel controlled loops
Counter controlled loops
The number of iterations is known in advance. They use a control variable called loop
counter.
Also called as definite repetitions loop.
E.g: for
Sentinel controlled loops
The number of iterations is not known in advance. The execution or termination of the
loop depends upon a special value called sentinel value.
Also called as indefinite repetitions loop.
E.g: while

9.1 for loop:

 It is a repetitive control structure. It executes set of statements repeatedly until the


condition is false
 Number of iteration known in advance

Syntax:

for(initialization; condition; increment/decrement)


{
body of the loop;
}

Initialization section: It is used to initialize the staring value of the loop counter
Condition: The expression is evaluated.
1.if it evaluates true, body of the loop is executed
2. if it evaluates false, program control is transferred to statements present next to
the for loop
Increment/decrement: After the execution of body of the loop, increment and decrement of loop
counter is performed.

Execution of for loop


1. Initialization section is executed only once.
2. Condition is evaluated
a. If it is true, loop body is executed.
b. If it is false, loop is terminated
3. After the execution of loop, the manipulation expression is evaluated.
4. Steps 2 & 3 are repeated until step 2 condition becomes false.
Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf("The numbers are");
for(i=1;i<=4;i++)
{
printf("\n%d",i);
}
getch();
}
Output:
The numbers are
1
2
3
4
Example: To find the sum of n natural number. 1+2+3…+n
#include<stdio.h>
#include<conio.h>
main()
{
int n, i, sum=0;
clrscr();
printf(“Enter the value for n”);
scanf(“%d”,&n);
for(i=1;i<=n;i++)
{
sum=sum+i;
}
printf(“Sum=%d”, sum);
getch();
}
Output:
Enter the value for n 4
sum=10

9.2. While loop


 They are also known as Entry controlled loops because here the condition is
checked before the execution of loop body.
 The condition is checked first, if it is true it executes the body of the loop until the
condition becomes false.
 The number of iteration need not be known in advance

Syntax
while(condition)
{
Statements;
}

Example:
#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf("The numbers are");
i=1;
while(i<4)
{
printf("\n%d",i);
i++;
}
getch();
}

Output:
The numbers are
1
2
3
9.3 do..while loop

 They are also known as Exit controlled loops because here the condition is checked after
the execution of loop body.
 The body of the loop is executed first and test condition is checked at the end of the loop.
 The body of the loop is executed atleast once even if the condition is false.
Number of iteration need not be known in advance

Syntax
do
{
Statements

}while(condition);

Example:

#include<stdio.h>
#include<conio.h>
void main()
{
int i;
clrscr();
printf("The numbers are");
i=1;
do
{
printf("\n%d",i);
i++;

} while(i<4);
getch();
}
Output:
The numbers are
1
2
3
9.4 Nested loops
If the body of a loop contains another iteration statement, then we say that the loops are nested.
Loops within a loop are known as nested loop.
While do…while
The condition is checked at the beginning The condition is checked at the end
The condition must be initially true The condition need not be initially true
It may or may not be executed at least once It may be executed at least once
It is an entry controlled loop It is an exit controlled loop
10. PRE-PROCESSOR DIRECTIVES
 The C pre-processor is a micro processor that is used by compiler to transform source
code before compilation. It is called micro pre-processor because it allows us to add
macros.
 Pre-processor directives are executed before compilation. Before a C program is
compiled in a compiler, source code is processed by a program called pre-processor.
 This process is called pre-processing.
 Commands used in pre-processor are called pre-processor directives and they begin with
“#” symbol.
The preprocessor operates under the following preprocessor directives.
i. File Inclusion
ii. Macro Substitution
iii. Conditional inclusion

10.1. File Inclusion


This is used to include an external file, which contains functions or some other macro
definitions to our source program, so we need not rewrite functions and macros in our source
program.
The #include <filename> tells the compiler to look for the directory where system header files
are held.
The #include "filename" tells the compiler to look in the current directory from where program
is running
Syntax
#include <filename.h>
filename.h is the name of the file,that can be included in our source program.
The #include preprocessor is used to include header files to C programs. For example,
#include <stdio.h>
Example
#include <stdio.h>
#include <math.h>
stdio.h file because printf() function is defined in this file.
#include<stdio.h>
int main()
{
printf("Hello C");
return 0;
}

Output:
Hello C
10.2. Macro Substitutions
This is used to define symbolic contants in the source program. The identifier or
string or integer defined is replaced by macro substitution.
Syntax:
#define identifier string/integer
The preprocessor accomplish the task specified in „#define‟ statement.
#define age 20
#define CITY“CHENNAI”

Example
#include <stdio.h>
#define PI 3.1415
int main()
{
float radius, area;
printf("Enter the radius: ");
scanf("%f", &radius);

area = PI*radius*radius;

printf("Area=%f",area);
return 0;
}

Output:
Enter the radius: 5
Area=78.537498

3.Conditional Inclusion:
These are used to control the preprocessor with conditional statements.
Example:
#ifdef P
printf(“PENTIUM”);
#else printf(“”CELERON);
#endif

Some preprocessor directives are:


preprocessor Directive Function
#include Used to include a file.
#define Used to define symbolic constant
#ifdef Used to test macro definition
#else Used to specify alternative in #ifdef
#undef Used to undefined a macro.

Example Program

#include <stdio.h>
#define height 100
#define number 3.14
#define RAJU 100

void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);

#ifdef RAJU
printf("RAJU is defined. So, this line will be added in this C file\n");
#else
printf("RAJU is not defined\n");
#endif
printf("First defined value for height : %d\n",height);

#undef height // undefining variable

#define height 600 // redefining the same for new value


printf("value of height after undef & redefine:%d",height);
}

Output:
value of height : 100
value of number : 3.140000
RAJU is defined. So, this line will be added in this C file
First defined value for height : 100
value of height after undef & redefine : 600

11. COMPILATION PROCESS.


 C is a Compiled Language .C program must run through C Compiler that can create an
executable file to be run by the computer.
 C Program is human readable. The executable file is machine readable.
 The compiler translates the source code into object code. The Object code contains
instruction for the processor to execute.
 The object file is not an executable file. The object file is processed with another special
program called a linker to produce an executable or runnable file.
 There is different compiler for different programming language but same linker is used
for object file.
 The process of converting the source code into object code is called compiling. Compiler
converts source file to object code and save as separate file with an extension .obj.
 If there is an error in the source code, it does not compile source code and indicates error.
 A C program contains predefined function. The necessary libraries are linked to the
object code file by the linker and produce .exe file is called linking. The executable files
are executed by the machine.
 System loader loads the .exe file in the main memory for the execution of the program.
Overview of Compilation and Execution process

Compiler Object Linker


Source file Executable
files
file

Library
files

Elaborate compilation before execution

Pre- Compiler Object Linker


Source Executable
Processor files
File file

Library
Library
Files
files

The compilation process is done in two steps.


i) The pre-processor reads the source file as text and produce another text file as output.
Source code lines which begins with the # symbol are actually not written in C but in
pre-processor language. The output of pre-processor is a text file which does not contain
any pre-processor statements. The file is ready to be processed by the compiler and
produces an object file.
ii) The linker combines the object file with library routines to produce final executable file.
Modular Programming-The complete compilation and execution process
In modular programing language the source code is divided into two or more source files.
All the source files are compiled separately and producing multiple object file. The object files
are compiled by the linker to produce an executable files

Pre- Compile Object


Source
Processor r files
file

Executabl
Library Linker e file
Library
Files Files

Pre- Compile Object


Source
Processor r files
file

Library
Files

Compilation and Linking process


There are 4 regions of memory which are created by a compiled C program. They are,

1. First region – This is the memory region which holds the executable code of the program.
2. 2nd region – In this memory region, global variables are stored.
3. 3rd region – stack
4. 4th region – heap
Compiling

 The process of converting the source code into object code is called compiling. Compiler
converts source file to object code and save as separate file with an extension .obj.
 If there is an error in the source code, it does not compile source code and indicates error.
Linking

 A C program contains predefined function. The necessary libraries are linked to the object code
file by the linker and produce .exe file. The executable files are executed by the machine.

Executing

 System loader loads the .exe file in the main memory for the execution of the program.
12. ILLUSTRATIVE PROBLEMS:
a. To Check a year is leap year or not
#include<stdio.h>
#include<conio.h>
void main()
{
int year;

printf("Enter a year: ");


scanf("%d", &year);

if(((year%4==0) && ((year%400==0) || (year%100!=0))


{
printf("%d is a leap year", year);
}
else
{
printf("%d is not a leap year", year);
}
getch();
}

Output:

Case 1

Enter a year: 2014


2014 is not a leap year
Case 2

Enter a year: 2012


2012 is a leap year

b. Sum of Digits of a number


#include<stdio.h>
void main()
{
int i,num,sum=0;
printf("enter the number");
scanf("%d",&num);

while(num>0)
{
i=num%10;
sum=sum+i;
num=num/10;
}

printf("Sum of digit is %d",sum);


getch();
}
Sample output:
Enter a number: 123
Sum of digits of number: 6

c. Program for simple calculator

#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,c,op;
clrscr();
printf("Arithmetic operation\n");
printf("1.Add\n2.Sub\n3.Multiply\n4.Division");
scanf("%d",&op);
printf("Enter two numbers\n");
scanf("%d%d",&a,&b);
switch(op)
{
case 1:
c=a+b;
printf("The addition of two number %d",c);
break;
case 2:
c=a-b;
printf("The subtraction of two number %d",c);
break;
case 3:
c=a*b;
printf("The product of two number %d",c);
break;
case 4:
c=a/b;
printf("The division of two number %d",c);
break;
}
getch();
}
Output:
Arithmetic operation
1.Add
2.Sub
3.Multiply
4.Division
Enter the option
1
Enter two numbers
4
5
The addition of two number 9

Sample programs

1. Write a C program to find print number 10 to 1

#include<stdio.h>
# include<conio.h>
void main()
{
int i = 1;
for (i = 10; i >= 1; i--)
{
printf("%d", i);
}
getch();
}

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

2.C program to find whether a given number is odd or even

#include<stdio.h>
void main()
{
int number;
printf("Enter any integer: ");
scanf("%d",&number);

if(number % 2 ==0)
printf("%d is even number.",number);
else
printf("%d is odd number.",number);
}

Sample output:
Enter any integer: 78
78 is even number.

Enter any integer: 47


47 is odd number.

3.C program to check whether a given integer is positive or negative

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

printf("Enter a number \n");


scanf("%d", &number);

if (number >= 0)
printf("%d is a positive number \n", number);
else
printf("%d is a negative number \n", number);
}

Output:
Enter a number: 12
12 is a positive number

4. C program to find greatest of 3 numbers


#include<stdio.h>
void main()
{
int a, b, c;

printf("\nEnter value of a, b & c : ");


scanf("%d %d %d", &a, &b, &c);

if ((a > b) && (a > c))


printf("\na is greatest");

else if ((b > c) )


printf("\nb is greatest");

else
printf("\nc is greatest");

Output:

Case1:

Enter value of a, b & c : 10 20 30

c is greatest

Case2:

Enter value of a, b & c : 30 20 10

a is greatest
Case3:

Enter value of a, b & c : 20 100 80

b is greatest

6.Factorial program in c

#include<stdio.h>
void main()
{
int i=1,f=1,num;

printf("Enter a number: ");


scanf("%d",&num);

for(i=1;i<num;i++)
{
f=f*i;
}

printf("Factorial of %d is: %d",num,f);


getch();
}

Sample output:
Enter a number: 5
Factorial of 5 is: 120

7.Program to find the given number prime or not


#include<stdio.h>
#include<conio.h>
void main()
{
int i,n,count=0;

printf("enter the number");


scanf("%d",&n);

for (i=1;i<=n;i++)
{
if(n%i==0)
{
count++;
}
}

if (count==2)
printf("is prime");
else
printf("not a prime");
getch();
}

Output:
enter the number :4
not a prime

8. Program to Check Armstrong Number

#include<stdio.h>
int main()
{
int i,num,n1,n=0;
printf("enter the number");
scanf("%d",&num);
n1=num;
while(num>0)
{
i=num%10;
n=n+i*i*i;
num=num/10;
}
if(n1==n)
{
printf("Armstrong number");
}
else
{
printf("Not an armstrong number");
}
}

Output:
enter the number 153
153
Armstrong number
enter the number 123
Not an armstrong number
9 .C program to generate fibonacci series.
Fibonacci series is a sequence of numbers in which next number in the sequence is obtained by
adding previous two numbers. For example 0, 1, 1, 2, 3, 5, 8, 13.

#include<stdio.h>
#include<conio.h>
void main()
{
int first=0,second=1,third,i,n;
printf("Enter the limit”);
scanf("%d",&n);
printf("\n%d %d",first,second);
for(i=2;i<n;++i)
{
third=first+second;
printf(" fibonacci series%d",third);
first=second;
second=third;
}
getch();
}
Output:
Enter the limit:5
fibonacci series :0 1 1 2 3

11.PROGRAM TO REVERSE THE GIVEN NUMBER


#include<stdio.h>
#include<conio.h>
void main()
{
int num,rev=0;
clrscr();
printf("Enter a number :");
scanf("%d",&num);
while(num>0)
{
rev=rev*10+num%10;
num=num/10;
}
printf("\nreverse= %d",rev);
getch();
}
Output:

Enter a number :789


reverse= 987

12. Program for Palindrome number

#include<stdio.h>
#include<conio.h>
void main()
{
int num,rev=0,n;
clrscr();
printf("Enter a number :");
scanf("%d",&num);
n=num;
while(num>0)
{
rev=rev*10+num%10;
num=num/10;
}
if(n==rev)
{
printf("The number is palindrome");
}
else
{
printf("The number is not a palindrome");
}
getch();
}
Output:
Enter a number :456
The number is not a palindrome
Enter a number :121
The number is palindrome
15. Sum of n numbers

#include <stdio.h>
void main()
{
int n, sum = 0, i;

printf("Enter the number of integers you want to add\n");


scanf("%d", &n);

printf("Enter %d integers\n",n);

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


{

sum = sum + i;
}
printf("Sum of entered integers = %d\n",sum);
}

Output:

Enter the number of integers you want to add

3
Enter 3 integers

Sum of entered integers = 6

You might also like