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

Basic Concepts of C Language

The document discusses the basics of C programming including: 1. C is a general-purpose, block-structured, procedural programming language developed in the 1970s. 2. Key aspects of C programming covered include data types, variables, constants, operators, input/output statements, and control flow statements. 3. The compilation process for a C program involves editing, preprocessing, compiling, linking, loading, and executing the code.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
232 views

Basic Concepts of C Language

The document discusses the basics of C programming including: 1. C is a general-purpose, block-structured, procedural programming language developed in the 1970s. 2. Key aspects of C programming covered include data types, variables, constants, operators, input/output statements, and control flow statements. 3. The compilation process for a C program involves editing, preprocessing, compiling, linking, loading, and executing the code.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 127

CS8251

PROGRAMMING IN C
UNIT - 1

BASICS OF C PROGRAMMING
Introduction to programming paradigms - Structure of C
program - C programming: Data Types – Storage classes
- Constants – Enumeration Constants - Keywords –
Operators: Precedence and Associativity - Expressions –
Input / Output statements, Assignment statements –
Decision making statements - Switch statement -
Looping statements – Pre-processor directives -
Compilation process
INTRODUCTION
• C is a
• General-purpose
• Block-structured
• Procedural
• Case-sensitive
• High level programming language
• Developed by Dennis Ritchie
History
• 1960 : -
• ALGOL was found by International group of computer users.
• COBOL was found for commercial application usage.
• FORTRAN was found for scientific applications.
• In 1967: -
• Basic Combined Programming Language (BCPL)
• developed by Martin Richards at Cambridge University.
• a single language which can program all possible applications,
• In 1970: -
• a language called B was developed by Ken Thompson at
AT & T’s Bell Labs.
History
• In 1972: -
• Dennis Ritchie at Bell Labs developed a language with some
additional features of BCPL and B called C.
• In 1978: -
• Publication of The C Programming Language by Kernighan & Ritchie
caused a revolution in the computing world.
• In 1983: -
• the American National Standards Institute (ANSI) established a
committee to provide a modern, comprehensive definition of C. The
resulting definition, the ANSI standard, or "ANSI C", was completed
late 1988.
Programming languages
• Various programming languages
• Machine language
• Assembly language
• High-level language
• Machine language
• Natural language of a particular computer
• Consists of strings of numbers(1s, 0s)
• Instruct computer to perform elementary
operations one at a time
• Machine dependent
Programming languages
• Assembly Language

• English like abbreviations


• Assemblers:
• Translators of programs
• Convert assembly language programs to machine language.

• E.g. add overtime to base pay and store result in gross pay

LOAD BASEPAY

ADD OVERPAY

STORE GROSSPAY
Programming languages
• High-level languages
• To speed up the programming process
• Single statements for accomplishing substantial tasks
• Compilers - convert high-level programs into machine
language

• E.g. add overtime to base pay and store result in gross pay
grossPay = basePay + overtimePay
Basics of C Environment
• Development environment has 6 phases
 Edit - Writing the source code by using some IDE or editor
 Pre-processor - Already available routines

 Compile - translates or converts source to object code for a


specific platform ie., source code -> object code
 Link - resolves external references and produces the
executable module
 Load – put the program into the memory

 Execute – runs the program


Basics of C Environment
Program edited in
Phase 1 Editor Disk Editor and stored
on disk
Preprocessor
Phase 2 Preprocessor Disk program processes
the code
Creates object code
Phase 3 Compiler Disk and stores on disk

Links object code


Phase 4 Linker Disk with libraries and
stores on disk
Basics of C Environment
Primary memory

Phase 5 Loader
Puts program
in memory

Primary memory
Takes each
Phase 6 CPU instruction
and executes it,
storing
new data values
Executing a C Program
Steps involved in execution are

• Creating the program

• Compiling the program

• Linking the program with functions that are needed from the C
library

• Executing the program


Executing a C Program
Edit
Program

Source
Code

Compile

Object
Code

Library Link Object


Files Code Executable
Basics Structure of C Program
Documentation section

Link section

Definition section

Global declaration section

main() function section


{
Declaration part
Executable part
}

Subprogram section
(user defined function)
Simple C Program
/* A first C Program*/

#include <stdio.h>

void main()

{
     printf("Hello World \n");

}
C Character Set
• Characters are the basic building blocks in C program,
equivalent to ‘letters’ in English language
• Characters can be used to form words, numbers and
expressions
• Characters in C are grouped into following categories
• Letters ex:a…z,A…Z
• Digits ex:0…9
• Special characters ex:,,&,@,_,+,-,…..
• White spaces ex:blank space
horizontal tab
new line…….
C Tokens
• In a passage of text, individual words and punctuation marks are
called tokens
• In a C source program, the basic element recognized by the
compiler is the "token."
• C Tokens are
 Keywords - int, float, while
 Identifiers - sum, main
 Constants - 100, -55.5
 Strings - “ABC”, “Hello”
 Operators - +, -, *, /, ++
 Special symbols - {, },[, ]
Keywords
• Keyword is a reserved word that has a particular meaning in
the programming language.
• Have special meaning to the compiler, cannot be used as
identifiers in our program.
• Keywords serve as basic building blocks for program statement
• Keywords must be written in lowercase
• There are 32 keywords available in C
Some Keywords
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
Identifiers
• Refer to the names of variables, functions and arrays
• User defined names and consist of a letters and digits,
with a letter as a first character
Rules for Identifiers
• First character must be an alphabet
• Must consist of only letters, digits and underscore
• Maximum number of characters is compiler
dependent
• Cannot use a keyword
• Must not contain white space
• Case sensitive
Identifiers
Examples of legal identifier:

Student_age, Item10, counter, number_of_character

Examples of illegal identifier

Student age (embedded blank)

continue (continue is a reserved word)

10thItem (the first character is a digit)

Principal+interest (contain operator character +)


Recommendations for Constructing Identifiers

1. Avoid excessively short and cryptic names such as x or wt.


Instead, use a more readable and descriptive names such as
student_major and down_payment.

2. Use underscores or capital letters to separate words in


identifiers that consist of two or more words. Example,
student_major or studentMajor are much easier to read than
studentmajor.
Data Types
• Data type is one of the most important attributes of an identifier, it
determines the possible values that an identifier can have and the
valid operations that can be applied on it.
• Classification of data types
• Basic Data Types(Primitive or Fundamental)
• Character(char)
• Integer(int)
• Single Precision Floating Point(float)
• Double Precision Floating Point(double)
• No value(void)
• Derived Data Types
• Array Type
• Pointer
• Function type
• User-Defined Data Types
• Structure
• Union
• Enumeration
• Type def
Variables
• An entity whose value can vary(change) during the execution of a
program
• A variable can be placed on both left side and right side of the
assignment operator
• Thus, a variable has both an l-value and an r-value
v = v + 10;

Example
sum, avg_wt, item
VARIABLE DECLARATION
• Declaration of variables should be done in the declaration part of
the program
• Variables must be declared before they are used in the program
• Declaration provides two things:
• Compiler obtains variable name
• Tells the compiler about the data type of the variable being declared
and helps in allocating the memory
VARIABLE DECLARATION
Syntax:
data_type variable_name
Example:
int age;
char ch;
float avg;
int a,b,c;
VARIABLE DECLARATION
Initializing Variables
• Variables declared can be assigned or initialized using an
assignment operator ‘=‘
Syntax:
variable_name = constant;
or
data_type variable_name = constant;
Example:
int age; char ch=‘A’;
age=10; float avg=10.5;
Constants
• Constants refers to fixed values that do not change during the execution a program
• It cannot be placed on the left side of the assignment operator
• Types
• Literal constants
• Integer
• Floating point
• Character
• String
• Qualified constants
• Symbolic constants

Types of Constants
 Numeric Constants

 Integer Constants - 234, 045, 0x2A, 0X3B


 Real Constants- 2.345, 0.64e-2

 Character Constants

 Single Character Constants ‘5’, ‘A’


 String Constants “Hello”
Constants
• Constants refers to fixed values that do not change during the
execution a program
• It cannot be placed on the left side of the assignment operator
• Types
• Literal constants
• Integer -345, 6754
• Floating point 34.67, 2E+10
• Character ‘C’, ‘S’, ‘E’, ‘6’
• String “CSE”, “INDIA”
• Qualified constants
• Symbolic constants
Integer Literal Constant
• Must have at least one digit

• Should not have any decimal point


• Can be either positive or negative

• No special characters and blank spaces are allowed

• Starts with 0, then it is octal number e.g. 023

• Starts with 0x or 0X, then it is hexadecimal number

e.g. 0x23 or 0X23


• Size can be modified by using length modifier
• long - Terminated by l or L e.g. 23l or 23L

• unsigned - Terminated by u or U e.g. 23u or 23U

• float - Terminated by f or F e.g. 23f or 23F


Floating Point Literal Constant

Fractional Form
• Must have at least one digit
• Should have a decimal point
• Can be either positive or negative
• No special characters and blank spaces are allowed
• By default it is assumed to be of type double e.g. 23.45

• Size can be modified by using length modifier


• float - Terminated by f or F e.g. 23.45f or 23.45F
Floating Point Literal Constant

Exponential Form
• Two parts : mantissa part and exponent part separated by e or E
• Mantissa part can be either +ve or –ve
• Mantissa part should have at least one digit

• Mantissa part can have a decimal point but not mandatory


• Exponent part should have at least one digit can be either +ve

or –ve
• Exponent part cannot have a decimal point
• No special characters and blank spaces are allowed within the
mantissa and exponent part
Ex: -2.5E12, -2.5e-12, 2e10
Character Literal Constants
• A character literal constant can have one or at
most two characters enclosed within a single
quotes
• Example: ‘A’, ‘a’, ‘\n’
• Types:
• Printable character literal constant
• Non-Printable character literal constant
• Represented with help of escape sequence
• An escape sequence consists of a backward slash(\) followed
by a character and both enclosed by single quotes
• An escape sequence is treated as single character
Escape Sequences
Escape Name Meaning
Sequence
\a Alert Sounds a beep
\b Back space Backs up 1 character
\f Form feed Starts a new screen of page
\n New line Moves to beginning of next line
\r Carriage return Moves to beginning of current line
\t Horizontal tab Moves to next tab position
\v Vertical tab Moves down a fixed amount
\\ Back slash Prints a back slash
\’ Single quotation Prints a single quotation
\” Double quotation Prints a double quotation
\? Question mark Prints a question mark
\0 Null character Prints nothing
Backslash Character Example
Program
Output

deghi
#include<stdio.h>
void main()
Hai Hello
{
printf("\nabc");
printf("\rdef");
printf("\bghi\n");
printf("Hai\tHello");
}
Input and Output Functions

Input and Output Functions

Formatted Unformatted
Functions Functions

getch()
scanf() getche()
printf() getchar()
gets()
putch()
putchar()
puts()
Formatted Functions
Formatted Input:
• Input data is arranged in a particular format
• I/P values are taken by using scanf function
• Syntax:
• scanf(“control string”,arg1,arg2…argn) ;
control string - includes format specifications and optional number
specifying field width and the conversion character %
arg1,arg2,… - address of locations where the data are stored
 Example: scanf(“%3d%2d”,&a,&b);
Formatted Functions
Formatted Output:
• printf statement displays the information required to
user with specified format
• Syntax:

printf(“control string”,arg1,arg2…argn) ;
control string - field format which includes format
specifications and optional number specifying field width
and the conversion character %, blanks, tabs and newline.
arg1,arg2,… - name of the variables
Example: printf(“%d\t%f\n”,sum1,sum2);
An Example Program
# include<stdio.h>
void main()
{
int num1
float num2;
char ch;
printf (“Enter values:”) ;
scanf(“%d%f%c”, &num1, &num2,&ch);
printf (“\nThe Entered Values are:%d %.2f %c”, num1, num2,ch) ;
}

Output 1:
Enter values: 1342 24.2 a
The Entered Values are: 1342 24.20 a
Format for various output
Flag output justification
+ (right justification) - (left justification)
Width Specifier minimum field width for an output value

TYPE FORMAT EXPLANATION

Integer %wd w-width

Float %w.cf w-width


c-no. of digits after decimal point

String %w.cs w-width of total characters


c-no. of characters to display
Example
• INTEGER
printf(“%d”,12345); 12345
printf(“%3d”,12345); 12345
printf(“%7d”,12345); 12345
printf(“%-7d”,12345); 12345
• FLOAT
printf(“%f”,123.45); 123.450000
printf(“%4.2f”,123.45); 123.45
printf(“%9.3d”,12345); 123.450
• STRING
printf(“%s”,”Hello World”); Hello World
printf(“%6.2s”,”Hello World”); He
printf(“%1.2s”,”Hello World”); He
Formatted & unformatted I/O
Fundamental Conversion Symbol+Format
Data Type
Data Type Specifier
Integer short integer %d or %i

short unsigned %u

long signed %ld

long unsigned %lu

unsigned hexadecimal %X or %x

unsigned octal %o
Real float %f or %g
double %lf
Character character %c
string %s
Unformatted Functions
Unformatted Input
getch() & getche()
 read a alphanumeric characters from the standard input
device such as the keyboard
 The character entered is not displayed by getch() function
Example : getch() & getche()

# include<stdio.h>
#include<conio.h>
void main ( )
{
clrscr();
printf (“Enter two alphabets:”) ;
getche();
getch();
}
Output:Enter two alphabets:A
Unformatted Functions
getchar()
• read a character type data from the standard input
device such as the keyboard
• Reads one character at a time till user press the enter
key
Example : getchar()

# include<stdio.h>
#include<conio.h>
void main ( )
{
char c;
clrscr();
printf (“Enter a character:”) ;
c=getchar();
printf(“c=%c”,c);
getch();
}
Output:Enter a character :A
c=A
Unformatted Functions

gets()
• read a string from the standard input device such as the
keyboard until user press the enter key
Example : gets()
# include<stdio.h>
#include<conio.h>
void main ( )
{
char str[10];
clrscr();
printf (“Enter a string:”) ;
gets(str);
printf(“String=%s”,str);
getch();
}
Output:Enter a string :Hello
String=Hello
Unformatted Functions
putch() & putchar()
• Prints any alphanumeric character taken by the
standard input device such as the keyboard
Example:
char ch=‘X’;
putch(ch); or putchar(ch);

Output: X
Unformatted Functions
puts()
• prints the string or character array
Example : puts()
# include<stdio.h>
#include<conio.h>
void main ( )
{
char str[10];
clrscr();
printf (“Enter a string:”) ;
gets(str);
printf (“Entered string:”) ;
puts(str);
getch();
}
Output:Enter a string :Hello
Entered string:Hello
Operators
• An operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations

Types of Operators
 Arithmetic Operators +, -, *, /, %
 Relational Operators <, <=, >, >=, ==, !=
 Logical Operators &&, ||, !
 Assignment Operators =
 Increment and Decrement Operators ++,--
 Conditional Operators ?=
 Bitwise Operators &,|, ^, <<, >>
 Special Operators ,, sizeof, &, * ., ->
Properties Of Operators
• Precedence
• Associativity
Precedence:
• Priority allotted to the operator
Ex: 8+9*2-10
=8+18-10
=26-10
=16
Associativity:
• Expression having operators with equal precedence
• associativity property decides which operation is performed first
Types:Left to Right Right to left
12*4/8%2 x=8+5%2
= 48/8%2 =8+1
= 6%2 =9
=0
Arithmetic Operators
C Operation Algebraic C

Addition (+) f+7 f+7

Subtraction (-) p–c p–c

Multiplication (*) bm b*c

Division (/) x/y x/y

Modulus (%) r mod s r%s


Arithmetic Operators Example
Program d = x / y;
#include <stdio.h> printf(“d = %d\n",d);
#include <conio.h> r = x % y;
void main() printf("r = %d\n",r);
{ }
int x,y, a,s,m,d,r;
clrscr(); Output
printf(“Enter two numbers:”); Enter two numbers:10 20
scanf(“%d%d”,&x,&y); a = 30
a = x + y; s = -10
printf(“a = %d\n",a); m = 200
s = x - y; d=0
printf(“s = %d\n",s); r = 10
m = x * y;
printf(“m = %d\n",m);
Relational Operators
• Greater than >
• Less than <
• Greater than or equal to >=
• Less than or equal to <=
• Equal to ==
• Not equal to !=

Condition true return 1


Condition false return 0
Relational Operators Example
Program
#include<stdio.h>
r=(x<y);
#include<conio.h>
printf("%d\n",r);
void main()
r=(x<=y);
{
printf("%d\n",r);
int x,y,r;
}
clrscr();
printf(“Enter 2 nos. x & y:”);
scanf(“%d%d”,&x,&y);
Output
r=(x==y);
Enter 2 nos. x & y: 10 20
printf("%d\n",r);
0
r=(x!=y);
1
printf("%d\n",r);
0
r=(x>y);
0
printf("%d\n",r);
1
r=(x>=y);
1
printf("%d\n",r);
Logical Operators

Operator Example Meaning

(Condition1) && Both conditions should


&& (Logical AND)
(Condition2) satisfy to proceed

Either one condition


(Condition1) ||
|| (Logical OR) satisfied proceed to
(Condition2)
next operation

The condition not


! (Logical NOT) !(Condition1) satisfied proceed to
next operation
Logical Operators
Example

if ((x>20) && (x<100)) printf("x is inside open interval


20-100");

if ((x<5) || (x>20)) printf("x is not inside closed interval 5-20");

if (!(x>20)) printf("x is smaller or equal to 20");


Logical Operators Example
//Greatest of 3 numbers using
Output
logical operators

#include<stdio.h>
Enter 3 nos. x ,y,z: 40 20 30
#include<conio.h>
x is greatest
void main()
{
int x,y,z;
Enter 3 nos. x ,y,z: 10 40 30
clrscr();
y is greatest
printf(“Enter 3 nos. x ,y,z:”);
scanf(“%d%d%d”,&x,&y,&z);
if((x>y)&&(x>z))
Enter 3 nos. x ,y,z: 10 20 30
z isprintf(“x
greatestis greatest”);
if((y>x)&&(y>z))
printf(“y is greatest”);
if((z>x)&&(z>y))
printf(“z is greatest”);
}
Assignment operators
Operator Example Meaning

= a=b a=b

+= 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
Increment/Decrement
operators
Operator Example Meaning

First does the operation


++ a++ and increments the value

First Increments the value


++ ++a
and does the operation

First does the operation


-- a-- and decrements the
value

First decrements the


-- --a value and does the
operation
Increment/Decrement
operators
Program
void main() Output
{
int c; 5
c = 5; 5
printf(“%d\n”, c); 6
printf(“%d\n”, c++);
printf(“%d\n\n”, c); 5
c = 5; 6
printf(“%d\n”, c); 6
printf(“%d\n”, ++c);
printf(“%d\n”, c);
}
c=10
x=c++ + ++c;
x=? C=?
Conditional Operator
Conditional Operator (?:) is ternary operator (demands 3 operands),
and is used in certain situations, replacing if-else condition phrases.
Conditional operator’s syntax is:

condition?expression1:expression2;

If condition is true, expression1 is executed.


If condition is false, expression2 is executed.

Example:

int a, b, c;
...
c = a > b ? a : b; // if a>b "execute" a, else b and assign the result to c
Bitwise Operators
Operator Meaning

& Bitwise AND

| Bitwise OR

^ Bitwise XOR

~ One’s Complement

<< Left Shift

>> Right Shift


Bitwise Operators Example
Let A=0x56 and B=0x32

A | B ( Bitwise OR )
A & B ( Bitwise AND )
0101 0110
0101 0110
0011 0010
0011 0010
---------------------
---------------------
0111 0110
0001 0010
---------------------
---------------------

~ A ( Complement )
A ^ B ( Bitwise XOR ) 0101 0110
0101 0110 ---------------------
0011 0010 1010 1001
--------------------- ---------------------
0 1 1 0 0 10 0
---------------------
Bitwise Operators Example
Let A=0x56

A << 2 ( Left Shift )

0 1 0 1 0 1 1 0 << 2  0 1 0 1 0 1 1 0 0 0 ( 0x158 )

A >> 2 ( Right Shift )

0 1 0 1 0 1 1 0 >> 1  0 1 0 1 0 1 1 ( 0x2B)

NOTE:
For multiply given number by two, left shifted by one time, i.e., a<<1
For divide given number by two, right shifted by one time, i.e., a>>1
Bitwise Operators Example
Write a program to shift inputed data by three bits left and right
Program
void main()
{
int x,y;
clrscr();
printf(“Enter value of x:”);
scanf(“%d”,&x);
y=x<<3;
printf(“Left shifted data=%d”,y);
printf(“Right shifted data=%d”,x>>3);
}
Output: Enter value of x:16
Left shifted data=128
Right shifted data=2
Special Operators
• C supports some special operators such as comma operator, size of
operator, pointer operators (& and *) and member selection operators (.
and ->).
• The size of and the comma operators are discussed here. The remaining
operators will see in pointer chapter
Comma Operator
• The comma operator can be used to link related expressions together. A
comma-linked list of expressions are evaluated left to right and value of
right most expression is the value of the combined expression.
Example
 value = (x = 10, y = 5, x + y);
 for (n=1, m=10, n <=m; n++,m++)
 t = x, x = y, y = t;
Special Operators
Sizeof Operator
• The operator sizeof gives the size of the data type or variable in
terms of bytes occupied in the memory. The operand may be a
variable, a constant or a data type qualifier.
• The size of operator is normally used to determine the lengths of
arrays and structures when their sizes are not known to the
programmer. It is also used to allocate memory space dynamically to
variables during the execution of the program.
Example
int sum;
m = sizeof(sum);  2

n = sizeof(long int);  4
k = sizeof(235L);  4
Expressions
Arithmetic Expressions

• An expression is a combination of variables constants and operators


written according to the syntax of C language.

Algebraic
C Expression
Expression

axb–c a*b–c

(m + n) (x + y) (m + n) * (x + y)

3x2 +2x + 1 3*x*x+2*x+1


Expressions
Evaluation of Expressions
• Expressions are evaluated using an assignment statement of the form
Variable = expression;
Variable is any valid C variable name.
The expression is evaluated first and then replaces the previous value
of the variable on the left hand side.
All variables used in the expression must be assigned values before
evaluation is attempted.

Example
x=a*b–c
y=b/c*a
z = a – b / c + d;
Decision Making - Branching
• Decision making statements are used to skip or to execute a group of
statements based on the result of some condition.
• The decision making statements are,
− simple if statement
− if…else statement
− nested if
− else … if ladder
− switch statement
− goto
• These statements are also called branching statements
Simple if statement
Syntax:
if(condition)
{
Statements;
}

False
if(condition)

True (Bypass)

Statements;
Simple if - Example
# include <stdio.h> Output
void main ()
{ Type a number -50
     int number;   The absolute value is 50
     printf("Type a number:");  
     scanf("%d",&number);  
     if (number < 0)  
      number = -number; 
     printf ("The absolute value is %d",number);  
}
if - else statement
Syntax:

if(condi False
tion)
if(condition)
{ True
True block statements;
} True Block False Block
Statement Statements
else
{
False block statements;
}
if – else Example
# include <stdio.h>
Output
void main ()
{
Type a number 50
The
     int
number
num;  is positive
     printf ("Type a number:");  
     scanf ("%d", &num);  
     if (number < 0)  
      printf(“The number is negative”); 
     else
printf(“The number is positive”); 
}
if – else Example
#include<stdio.h>
Output
void main()
{ Enter a number 125
Int num; The number is ODD
printf ("Enter a number:");
scanf ("%d",&num);
if (num%2==0)
printf ("The number is EVEN.\
n");
else
printf ("The number is ODD.\n");
}
Nested if Statement
• if statement may itself can contain another if statement is known as nested if
statement.
Syntax:
if(condition1)
{
if(condition2)
{
True block statement of condition1 & 2;
}
else
{
False block statement of condition2;
}
}
else
{
False block statements of condition1;
}
Nested if Statement
False
condition1
True
False
if(condition2) False Block Statements of
True condition 1;
True Block Statements of
condition 1 & 2; False Block Statements of
condition 2;
Nested if Example
Output
# include <stdio.h>
void main()
{ Enter 3 numbers:10 25 20
int n1,n2,n3,big;   The largest number is: 25
    printf (“Enter 3 numbers:");
    scanf ("%d %d %d", &n1,&n2,&n3);
   if (n1 > n2)  
     {
if(n1 > n3)
big = n1;
      else
big = n3;
}
if(n2 > n3)
big = n2;
else
big = n3;
printf(“The largest number is: %d”,big);
}
Else - if Ladder Statement
Syntax
if (condition1)
statement block 1;
else if (condition2)
statement block 2;
else if (condition3)
statement block 3;
:
:
else if (condition)
statement block n;
else
default statement;
Else - if Ladder Statement
True
If(condition1)
False
True
Else if(condition2)
False Statements1;
True
Else if(condition3)
False Statements2;

Default Statements;
Statements3;
Else - if Ladder Example
#include <stdio.h>
voidOutput
main ()
{
int mark;
Enter mark: 75
printf ("Enter mark:");
Distinction
scanf ("%d", &mark);
if (mark <= 100 && mark >= 70)
printf ("\n Distinction");  
else if (mark >= 60)
printf("\n First class");
else if (mark >= 50)
printf ("\n Second class");
else
printf ("Fail");
}
Switch Statement
Syntax
switch ( expression )
{
case value1: program statement;
......
break;
case value2: program statement;
.......
break;
…….
…….
case valuen: program statement;
.......
break;
default: program statement;
.......
break;
}
Switch Statement
Switch (Expression)

Case 1 Statements

Case 2 Statements

Case 3 Statements

Case 4 Statements
Switch Statement Example
#include <stdio.h> break;
void main ()        case '/':
{  if (num2 != 0)
   int num1, num2, result; result = num1 / num2;
   char operator; break;
   printf ("Enter two numbers:");      default:
   scanf ("%d %d", &num1, &num2);           printf ("\n unknown operator");
   printf ("Enter an operator:");           break;
   scanf ("%c", &operator); }
   switch (operator) printf (“Result=%d", result);
   { }
       case '+':
      result = num1 + num2; break; Output
       case '-':
      result = num1 - num2; Enter two numbers:10 20
      break; Enter an operator:+
       case '*': Result=30
result = num1 * num2;
Switch Statement Example
#include<stdio.h> case 'i': count++;
#include<conio.h> break;
#include<string.h> case 'o': count++;
void main() break;
{ case 'u': count++;
char st[100]; break;
int i,count=0; }
clrscr(); }
printf("Enter line of text:"); printf("\n Number of vowels: %d",count);
gets(st); getch();
for(i=0;st[i]!='\0';i++) }
{
switch(st[i]) Output
{
case 'a': count++; Enter line of text: Hello World
break; Number of vowels: 3
case 'e': count++;
break;
goto statement
•The goto statement used to transfer the program control unconditionally from
one statement to another statement.
•The general usage is as follows:

goto label; Label:


………… ………… ..............
…………
………… …………
………… …………
Label: Statement; goto label;
…………

•The goto requires a label in order to identify the place where the branch is to
be made.
•A label is a valid variable name followed by a colon.
goto statement example
#include <stdio.h> Output
void main ()
{    Enter a number:5
int n, sum = 0, i = 0;

      printf ("Enter a number:"); 1+2+3+…+5=15

      scanf ("%d", &n);

    inc: i++;

      sum += i;

      if (i < n)
goto inc;

      printf ("\n 1+2+3+…+%d = %d",n,sum)

     }
Looping statements
• The test may be either to determine whether the i has repeated the
specified number of times or to determine whether the particular
condition has been met.
• Type of Looping Statements are

• while statement
• do-while statement

• for statement
while statement
Syntax
While
False
(test
condition)
while (test condition)
{ True

body of the loop;


Body of the i;
}
while statement example
#include<stdio.h> Output
void main() Enter a number: 275
{ Sum of digits of a number=14
int n,x,sum=0;
printf("Enter a number: ");
scanf("%d",&n);
while(n>0)
{
x=n%10;
sum=sum+x;
n=n/10;
}
printf("Sum of digits of a number=%d",sum);
}
while statement example
#include<stdio.h> if(sum==temp)
void main() printf("%d is an Armstrong number“
{ ,temp);
int num,r,sum=0,temp; else
printf("Enter a number: "); printf("%d is not an Armstrong number“
scanf("%d",&num); ,temp);
temp=num; }
while(num!=0)
{ Output
r=num%10; Enter a number: 275
sum=sum+(r*r*r); 275 is an Armstrong number
num=num/10;
} Enter a number: 153
153 is an Armstrong number
do..while statement
• Since the body of the i is executed first and then the i condition is
checked we can be assured that the body of the i is executed at least
once.
Syntax
do
{
body of the loop;
}
while (test condition);
do..while statement
do

Body of the loop

True While
(test
condition)

False
do..while statement example
#include<stdio.h> Output
void main() Enter the number:275
{ Reversed number is 572
int num=0, rev_num=0;
printf(“Enter the number:”);
scanf(“%d”,&num);
do
{
ld=num%10;
rev_num=rev_num*10+ld;
num=num/10;
} while(num>0);
printf(“\nReversed number is %d”,rev_num);
}
while and do..while comparison
While Do…while
1) Syntax: 1) Syntax:
while(condition) do
{ {
Body of the loop Body of the loop
} }while(condition);
2) This is decision making and 2) This is also -decision making
looping statement and looping statement
3) This is the top tested loop 3) This is the bottom tested loop
4) Loop will be executed atleast
4)Loop will not be executed if the
once even though the condition is
condition is false in first check
false in first check
for statement
■ The for loop is most commonly and popularly used looping statement in C. The
for loop allows us to specify three things about the loop control variable i in a
single line. They are,
■ Initializing the value for the i
■ Condition in the i counter to determine whether the loop should continue or
not
■ Incrementing or decrementing the value of i counter each time the program
segment has been executed.
Syntax
for(initialization; test condition;increment/decrement)
{
body of the loop;
}
for statement
Initialization;

Increment/Decrement;

Body of the loop

True
test condition

False
for statement example
// Number 1 to 10 divisible by 2 but not
Output
divisible by 3 and 5

#include<stdio.h>
2
void
4 main()
{8
int i;
for(i=1;i<=10;i++)
{
if(i%2==0&&i%3!=0&&i%5!=0)
printf("%d\n",i);
}
}
for statement example
//12+22+32+…. n2
Output
#include<stdio.h> //<math.h>
void main()
Enter the number:5
{
Sum of series=55
int n, i,sum=0;
printf(“Enter the number:”);
scanf(“%d”, &n);
for(i=1;i <= n;i++)
{
sum = sum + i*i; //pow(i,2)

}
printf(“Sum of series=%d”,sum);
}
break statement
■ Sometimes while executing a loop it becomes desirable to skip a part of
the loop or quit the loop as soon as certain condition occurs.

■ For example consider searching a particular number in a set of 100


numbers. As soon as the search number is found it is desirable to
terminate the loop.

■ C language permits a jump from one statement to another within a loop


as well as to jump out of the loop.

■ The break statement allows us to accomplish this task. A break statement


provides an early exit from for, while, do and switch constructs.

■ A break causes the innermost enclosing loop or switch to be exited


immediately.
break statement
#include<stdio.h> Output
void main()
{ Enter the marks, -1 to end:
int mark, i=0,sum=0;
float avg; 55
printf(“Enter the marks, -1 to end:”); 22
while(1) 11
{ 66
scanf(“%d”, &mark); -1
if(mark == -1)
The average marks is:38.500000
break;
sum+=mark;
i++;
}
avg=(float)sum/i;
printf(“\nThe average marks is: %f”, avg);
}
continue statement
■ During loop operations it may be necessary to skip
a part of the body of the loop under certain
conditions.

■ Like the break statement C supports similar


statement called continue statement.

■ The continue statement causes the loop to be


continued with the next iteration after skipping any
statement in between.
continue statement
#include < stdio.h > Output
void main() Enter the integer:11 22 33 -1
{ You have entered a negative number
int i, num, sum=0;
44
printf(“Enter the integer:”);
for (i = 0; i < 5; i++) Sum of positive numbers entered =110
{
scanf(“%d”, &num);
if(num < 0)
{
printf(“You have entered a negative number\n”);
continue;
}
sum+=num;
}
printf(“Sum of positive numbers entered = %d”,sum);
}
break and continue comparison
Break Continue

1) Syntax: 1) Syntax:
break; continue;
2) Takes the control to outside of 2) Takes the control to beginning
the loop of the loop
3) It is used in switch statement 3) It is not used in switch
statement
4) Example: 4) Example:
for(i=0;i<n;i++) for(i=0;i<n;i++)
{ {
if(i==3) if(i==3)
break; continue;
} }
Preprocessor Directives
•The preprocessor is a program that processes the source program
before it is passed to the compiler.
•The preprocessor directives are always preferably initialised at the
beginning of the program before the main(). It is begins with a symbol
#(hash)

• #define directive
• #include directive
• #ifdef directive Conditional compilation
• #ifndef directive
•#undef directive directives
• #error directive
#define directive
The syntax of #define directive is as follows
#define identifier substitute
or
#define identifier(arg1…argN) substitute
Ex:
#define PI 3.14
void main()
OUTPUT
{
float r,area;
printf(“Enter radius:”); Enter radius:7
scanf(“%f”,&r); Area=153.86
area=PI*r*r;
printf(“Area=%.2f”,area);
}
#define directive example
#include<stdio.h>
#include<conio.h> OUTPUT
#define PI 3.14 Enter the radius of the circle:7
void main() The circumference of the circle is 43.96
{ The area of the circle is 153.86
int r;
float cir,area;
printf(“Enter the radius of the circle:");
scanf("%d",&r);
cir=2*PI*r;
area= PI *r*r;
printf("The circumference of the circle is %0.2f",cir);
printf(“The area of the circle is %0.2f",area);
getch();
}
#define directive example
#include<stdio.h>
#define SQR(x) (x*x) OUTPUT
void main() Enter the radius of the circle:7
{ The circumference of the circle is 43.96
int r; The area of the circle is 153.86
float cir,area;
printf(“Enter the radius of the circle:");
scanf("%d",&r);
cir=2*PI*r;
area= PI*SQR(r);
printf("The circumference of the circle is %0.2f",cir);
printf(“The area of the circle is %0.2f",area);
getch();
}
#undef directive
The syntax of #undef directive is as follows
#undef identifier_macro_template substitute
Ex:
#define PRINT printf(“Hello\n”)
void main()
{
int i;
PRINT; OUTPUT
#undef PRINT printf(“Hello\n”)
PRINT; Error
}
#include directive
• The #include directive loads the specified file in the current
program
The syntax of #include directive is as follows
#include “filename”
#include <filename>

The file is included in the double quotations marks indicating that


the search for the file is made in the current directory and in the
standard directories
#include ”abc.h”
The file is included in the angle brackets indicating that the search
for the file is made only in the standard directories
#include <stdio.h>
#ifdef directive
The syntax of #ifdef directive is as follows
#ifdef identifier
{
statement1;
statement2;
}
#else
{
statement1;
statement2;
}
#endif
#ifdef directive example
Ex: OUTPUT
#define LINE 1
void main() This is line number one
{
clrscr();
#ifdef LINE
printf(“This is line number one”);
#else
printf(“This is line number not one”);
#endif
getch();
}
#ifndef directive
The syntax of #ifndef directive is as follows
#ifndef identifier
{
statement1;
statement2;
}
#else
{
statement1;
statement2;
}
#endif
#ifndef directive example
Ex: OUTPUT
#define LINE 1
void main() This is line number one
{
clrscr();
#ifndef LINE
printf(“This is line number not one”);
#else
printf(“This is line number one”);
#endif
getch();
}
#error directive
• The #error is used to display user defined message during
compilation of the program

The syntax is as given below

#if !defined (identifier)


#error <ERROR MESSAGE>
#endif
#error directive
Ex:
OUTPUT
#define B 1
void main()
MACRO A IS NOT DEFINED
{
clrscr();
#if !defined (A)
#error MACRO A IS NOT DEFINED
#else
printf(“Macro found”);
#endif
getch();
}
Storage Classes
• The scope and lifetime depends on the storage class of the variable in
C language.

• The area or block of the C program from where the variable can be
accessed is known as the scope of variable

• The lifetime of the variable retains a given value during the execution
of the program.

• The variables can be any one of the four storage classes:


1. Automatic Variables
2. External variable
3. Static variable
4. Register variable.
Automatic Variables
• Automatic variables are declared inside a particular function and
they are created when the function is called and destroyed when the
function exits.

• Automatic variables are local or private to a function in which they


are defined.

• By default all variables declared without any storage specification is


automatic.
Automatic Variables Example
#include<stdio.h> void function2()
void function1(); {
void function2(); int m=100;
void main() function1();
{ printf(“%d\n”,m);
int m=1000; }
function2();
printf(“%d\n”,m);
}
Output
void function1()
10
{ 100
int m=10; 1000
printf(“%d\n”,m);
}
External Variables
• Global variables are usually declared in the beginning of the main
program ie., before the main() program

• However c provides a facility to declare any variable as global and


this is possible by using the keyword storage class extern.

• The external declaration does not allocate storage space for the
variables.

• If it has to be used in other functions then again it has to be re-


declared in that function also.
External Variables Example
• Example:
File2 (add.h)
File1int(ex.c)
extern a;
#include
void add() ”add.h”
{ int a;
printf(“XXX”);
void main()
{ a+=150;
}
a=10;
printf(“%d”,a);
Output
add();
10 printf(“%d”,a);
XXX
}
160
Static Variables
• The value given to a variable declared by using keyword static persists
until the end of the program.

• A static variable is initialized only once, when the program is


compiled. It is never initialized again.
Static variables Example
#include<stdio.h>
void main() Output:
{
1
int j;
2
for(j=1;j<=3;j++)
3
stat();
}

void stat()
{
static int x;
x=x+1;
printf(“x=%d\n”,x);
}
Register variables Example
#include<stdio.h>
int main() Output:
{ 1
register int j; 2
for(j=1;j<=3;j++) 3
printf(“%d\n”,j);
return 0;
}

You might also like