Computer Programming 1st Year 3rd Unit
Computer Programming 1st Year 3rd Unit
History of C language is interesting to know. Here we are going to discuss a brief history of the c
language.
C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T
(American Telephone & Telegraph), located in the U.S.A.
Features of C Language
C is the widely used language. It provides many features that are given below.
1. Simple
2. Machine Independent or Portable
3. Mid-level programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
1
9. Recursion
10. Extensible
1) Simple
C is a simple language in the sense that it provides a structured approach (to break the problem into
parts), the rich set of library functions, data types, etc.
5) Rich Library
C provides a lot of inbuilt functions that make the development fast.
6) Memory Management
It supports the feature of dynamic memory allocation. In C language, we can free the allocated memory
at any time by calling the free() function.
7) Speed
The compilation and execution time of C language is fast since there are lesser inbuilt functions and
hence the lesser overhead.
8) Pointer
C provides the feature of pointers. We can directly interact with the memory by using the pointers.
We can use pointers for memory, structures, functions, array, etc.
9) Recursion
In C, we can call the function within the function. It provides code reusability for every function.
Recursion enables us to use the approach of backtracking.
10) Extensible
C language is extensible because it can easily adopt new features.
2
First C Program
Before starting the abcd of C language, you need to learn how to write, compile and run the first
c program.
1. #include <stdio.h>
2. int main(){
3. printf("Hello C Language");
4. return 0;
5. }
➢ #include <stdio.h> includes the standard input output library functions. The printf() function is
defined in stdio.h .
➢ int main() The main() function is the entry point of every program in c language.
➢ printf() The printf() function is used to print data on the console.
➢ return 0 The return 0 statement, returns execution status to the OS. The 0 value is used for
successful execution and 1 for unsuccessful execution.
Execution Flow
Let's try to understand the flow of above program by the figure given below.
3
1) C program (source code) is sent to preprocessor first. The preprocessor is responsible to convert
preprocessor directives into their respective values. The preprocessor generates an expanded source
code.
2) Expanded source code is sent to compiler which compiles the code and converts it into assembly
code.
3) The assembly code is sent to assembler which assembles the code and converts it into object code.
Now a simple.obj file is generated.
4) The object code is sent to linker which links it to the library such as header files. Then it is converted
into executable code. A simple.exe file is generated.
5) The executable code is sent to loader which loads it into memory and then it is executed. After
execution, output is sent to console.
Structure of C program
Structure of C Program
5.main( ) Function
{
Every C program must have a main() function
5.1 Local Variable section
which is the starting point of the program execution.
5.2 Executable Statements
}
Identifiers
Identifiers are the names given to variables, constants, functions and user-define data. These identifiers
are defined against a set of rules.
When we declare a variable or any function, to use it we must provide a name to it, which identified it
throughout the program
int myvariable=”VEMU”;
Here myvariable is the name or identifier for the variable which stores the value "VEMU" in it.
Character set
The characters are grouped into the following catagories,
1. Letters (all alphabets a to z & A to Z).
2. Digits (all digits 0 to 9).
3. Special characters, ( such as colon :, semicolon ;, period ., underscore _, ampersand & etc).
4. White spaces.
scanf() function
The scanf() function is used for input. It reads the input data from the console.
Synatx: scanf("format string",argument_list);
The scanf("%d",&number) statement reads integer number from the console and stores the given value
in number variable.
The printf("cube of number is:%d ",number*number*number) statement prints the cube of number on
the console.
Output
enter first number:9
enter second number:9
sum of 2 numbers:18
Variables
A variable is a name of the memory location. It is used to store data. Its value can be changed,
and it can be reused many times.
It is a way to represent memory location through symbol so that it can be easily identified.
Syntax: type variable_list;
Here, a, b, c are variables. The int, float, char are the data types. We can also provide values while
declaring the variables.
6
1. int a=10,b=20;//declaring 2 variable of integer type
2. float f=20.8;
3. char c='A';
1. int a; 1. int 2;
2. int _ab; 2. int a b;
3. int a30; 3. int long;
Types of Variables
1. local variable
2. global variable
3. static variable
4. automatic variable
5. external variable
Local Variable
A variable that is declared inside the function or block is called a local variable. It must be
declared at the start of the block.
You must have to initialize the local variable before it is used
1. void function1()
2. {
3. int x=10;//local variable
4. }
7
Static Variable
A variable that is declared with the static keyword is called static variable.It retains its value
between multiple function calls.
1. void function1()
2. {
3. int x=10;//local variable
4. static int y=10;//static variable
5. x=x+1;
6. y=y+1;
7. printf("%d,%d",x,y);
8. }
If you call this function many times, the local variable will print the same value for each function call,
e.g, 11,11,11 and so on. But the static variable will print the incremented value in each function call,
e.g. 11, 12, 13 and so on.
Automatic Variable
All variables in C that are declared inside the block, are automatic variables by default. We can
explicitly declare an automatic variable using auto keyword.
1. void main()
2. {
3. int x=10;//local variable (also automatic)
4. auto int y=20;//automatic variable
5. }
External Variable
We can share a variable in multiple C source files by using an external variable. To declare an external
variable, you need to use extern keyword.
extern int x=10;//external variable (also global)
1. #include "myfile.h"
2. #include <stdio.h>
3. void printValue()
4. {
5. printf("Global variable: %d", global_variable);
6. }
8
Data Types
A data type specifies the type of data that a variable can store such as integer, floating, character, etc.
Types Data Types
Basic Data Type int, char, float, double
Derived Data Type array, pointer, structure, union
Enumeration Data Type enum
Void Data Type void
Let's see the basic data types. Its size is given according to 32-bit architecture.
9
Keywords
A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There
are only 32 reserved words (keywords) in the C language.A list of 32 keywords in the c language.
Precedence of Operators
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operator direction to be evaluated; it may be left to right or right to left.
int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated before + (additive
operator). The precedence and associativity of operators.
Constants
Constants are also like normal variables. But, only difference is, their values cannot be modified by the
program once they are defined.
• Constants refer to fixed values. They are also called as literals
• Constants may be belonging to any of the data type.
Syntax: const data_type variable_name; (or) const data_type *variable_name;
Types of Constants:
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants
float (10.456789)
Real or Floating point constants doule (600.123456789)
11
Hexadecimal constant int (Example: 0x90 /*starts with 0x*/)
1. Integer Constants :
➢ An integer constant must have at least one digit.
➢ It must not have a decimal point.
➢ It can either be positive or negative.
➢ No commas or blanks are allowed within an integer constant.
➢ If no sign precedes an integer constant, it is assumed to be positive.
➢ The allowable range for integer constants is -32768 to 32767.
2. Real Constants:
➢ A real constant must have at least one digit
➢ It must have a decimal point
➢ It could be either positive or negative
➢ If no sign precedes an integer constant, it is assumed to be positive.
➢ No commas or blanks are allowed within a real constant.
Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
12
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
Output:
13
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
Do you know how to use C token in real time application programs? We have given simple real
time application programs where C token is used. You can refer the below C programs to know how to
use C token in real time program.
2. Identifiers in C Language:
• Each program elements in a C program are given a name called identifiers.
• Names given to identify Variables, functions and arrays are examples for identifiers. eg. x is a name
given to integer variable in above program.
Rules for Constructing Identifier Name:
1. First character should be an alphabet or underscore.
2. Succeeding characters might be digits or letter.
3. Punctuation and special characters aren’t allowed except underscore.
4. Identifiers should not be keywords.
Operators and Expressions
➢ The symbols which are used to perform logical and mathematical operations are called C
operators.
➢ These operators join individual constants and variables to form expressions.
➢ Operators, functions, constants and variables are combined together to form expressions.
➢ Consider the expression A + B * 5. where, +, * are operators, A, B are variables, 5 is constant
and A + B * 5 is an expression.
15
Types of C Operators
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
Arithmetic Operators:
Arithmetic operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus.
+ (Addition) A+B
– (Subtraction) A-B
* (multiplication) A*B
/ (Division) A/B
% (Modulus) A%B
Example Program
#include <stdio.h>
Void main()
{
int a=40,b=20, add,sub,mul,div,mod;
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf("Addition of a, b is : %d\n", add);
printf("Subtraction of a, b is : %d\n", sub);
printf("Multiplication of a, b is : %d\n", mul);
printf("Division of a, b is : %d\n", div);
printf("Modulus of a, b is : %d\n", mod);
}
16
Output
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
Assignment Operators:
• The values for the variables are assigned using assignment operators.
• For example, if the value “10” is to be assigned for the variable “sum”, it can be assigned as “sum =
10;”
• There are 2 categories of assignment operators in C language. They are,
1. Simple assignment operator (Example: =)
2. Compound assignment operators ( Example: +=, -=, *=, /=, %=, &=, ^= )
Operators Example/Description
sum = 10;
= 10 is assigned to variable sum
sum += 10;
+= This is same as sum = sum + 10
sum -= 10;
-= This is same as sum = sum – 10
sum *= 10;
*= This is same as sum = sum * 10
sum /= 10;
/= This is same as sum = sum / 10
sum %= 10;
%= This is same as sum = sum % 10
sum&=10;
&= This is same as sum = sum & 10
sum ^= 10;
^= This is same as sum = sum ^ 10
17
Example Program For Assignment Operators:
• In this program, values from 0 – 9 are summed up and total “45” is displayed as output.
Assignment operators such as “=” and “+=” are used in this program to assign the values and to sum up
the values.
# include <stdio.h>
int main()
{
int Total=0,i;
for(i=0;i<10;i++)
1
{
Total+=i; // This is same as Total = Toatal+i
}
printf("Total = %d", Total);
}
OUTPUT:
Total = 45
Relational Operators:
Relational operators are used to find the relation between two variables. i.e. to compare the
values of two variables in a C program.
Operators Example/Description
== x == y (x is equal to y)
!= x != y (x is not equal to y)
18
Note: double equal sign (= =) should be used to compare 2 values. We should not single equal sign (=).
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}
Output:
m and n are not equal
Logical Operators:
• These operators are used to perform logical operations on the given expressions.
• There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and
logical NOT (!).
Operators Example/Description
(x>=10)||(y>=10)
|| (logical It returns true when at-least one of the condition is
OR) true
!((x>5)&&(y<5))
It reverses the state of the operand “((x>5) &&
(y<5))”
! (logical If “((x>5) && (y<5))” is true, logical NOT
NOT) operator makes it false
19
Example Program For Logical Operators:
#include <stdio.h>
int main()
{
int m=40,n=20;
int o=20,p=30;
if (m>n && m !=0)
{
printf("&& Operator : Both conditions are true\n");
}
if (o>p || p!=20)
{
printf("|| Operator : Only one condition is true\n");
}
if (!(m>n && m !=0))
{
printf("! Operator : Both conditions are true\n");
}
else
{
printf("! Operator : Both conditions are true. " \
"But, status is inverted as false\n");
}
}
Output:
&& Operator : Both conditions are true
|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is inverted as false
• In this program, operators (&&, || and !) are used to perform logical operations on the given
expressions.
• && operator – “if clause” becomes true only when both conditions (m>n and m! =0) is true. Else,
it becomes false.
• || Operator – “if clause” becomes true when any one of the condition (o>p || p!=20) is true. It
becomes false when none of the condition is true.
• ! Operator – It is used to reverses the state of the operand.
• If the conditions (m>n && m! =0) is true, true (1) is returned. This value is inverted by “!”
operator.
• So, “! (m>n and m! =0)” returns false (0).
20
Bit Wise Operators:
• These operators are used to perform bit operations. Decimal values are converted into binary values
which are the sequence of bits and bit wise operators work on these bits.
• Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR), <<
(left shift) and >> (right shift).
Truth Table for Bit Wise Operation & Bit Wise Operators:
x = 00101000
y= 01010000
21
Note:
• Bit wise NOT : Value of 40 in binary is 00000000000000000000000000000000
00000000000000000010100000000000. So, all 0’s are converted into 1’s in bit wise NOT
operation.
• Bit wise left shift and right shift : In left shift operation “x << 1 “, 1 means that the bits will be
left shifted by one place. If we use it as “x << 2 “, then, it means that the bits will be left shifted by
2 places.
In this example program, bit wise operations are performed as shown above and output is displayed in
decimal format.
#include <stdio.h>
int main()
{
int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
AND_opr = (m&n);
OR_opr = (m|n);
NOT_opr = (~m);
XOR_opr = (m^n);
printf("AND_opr value = %d\n",AND_opr );
printf("OR_opr value = %d\n",OR_opr );
printf("NOT_opr value = %d\n",NOT_opr );
printf("XOR_opr value = %d\n",XOR_opr );
printf("left_shift value = %d\n", m << 1);
printf("right_shift value = %d\n", m >> 1);
}
Output:
AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20
false.
• This operator is also called as ternary operator.
22
Syntax : (Condition? true_value: false_value);
Example: (A > 100? 0: 1);
• In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else
conditional statements.
Example Program For Conditional/Ternary Operators:
#include <stdio.h>
int main()
{
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
}
Output:
x value is 1
y value is 2
Increment/decrement Operators
• Increment operators are used to increase the value of the variable by one and decrement operators
are used to decrease the value of the variable by one in C programs.
• Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: – -var_name; (or) var_name – -;
• Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
In this program, value of “i” is incremented one by one from 1 up to 9 using “i++” operator and output
is displayed as “1 2 3 4 5 6 7 8 9”.
#include <stdio.h>
int main()
{
23
int i=1;
while(i<10)
{
printf("%d ",i);
i++;
}
}
Output:
123456789
#include <stdio.h>
int main()
{
int i=20;
while(i>10)
{
printf("%d ",i);
i--;
}
}
Output:
20 19 18 17 16 15 14 13 12 11
Below table will explain the difference between pre/post increment and decrement operators
Operator Operator/Description
24
Post decrement operator value of i is decremented after
(i–) assigning it to variable i
#include <stdio.h>
int main()
{
int i=0;
while(++i < 5 )
{
printf("%d ",i);
}
return 0;
}
Output:
1234
• Step 1 : In above program, value of “i” is incremented from 0 to 1 using pre-increment operator.
• Step 3 : Then, this incremented value “1” is assigned to the variable “i”.
• Above 3 steps are continued until while expression becomes false and output is displayed as “1 2 3
4”.
Example Program for Post – Increment Operators:
#include <stdio.h>
int main()
{
int i=0;
while(i++ < 5 )
{
printf("%d ",i);
}
return 0;
}
Output:
12345
25
• Step 1 : In this program, value of i “0” is compared with 5 in while expression.
• Step 3 : Then, this incremented value “1” is assigned to the variable “i”.
• Above 3 steps are continued until while expression becomes false and output is displayed as “1 2 3
4 5”.
• Step 1 : In above program, value of “i” is decremented from 10 to 9 using pre-decrement operator.
• Step 3 : Then, this decremented value “9” is assigned to the variable “i”.
• Above 3 steps are continued until while expression becomes false and output is displayed as “9 8 7
6”.
26
}
Output:
98765
• Step 3 : Then, this decremented value “9” is assigned to the variable “i”.
• Above 3 steps are continued until while expression becomes false and output is displayed as “9 8 7
6 5”.
Special Operators:
Below are some of the special operators that the C programming language offers.
Operators Description
In this program, “&” symbol is used to get the address of the variable and “*” symbol is used to
get the value of the variable that the pointer is pointing to. Please refer C – pointer topic to know more
about pointers.
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
27
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
Output:
50
sizeof() operator is used to find the memory space allocated for each C data types.
#include <stdio.h>
#include <limits.h>
int main()
{
int a;
char b;
float c;
double d;
printf("Storage size for int data type:%d \n",sizeof(a));
printf("Storage size for char data type:%d \n",sizeof(b));
printf("Storage size for float data type:%d \n",sizeof(c));
printf("Storage size for double data type:%d\n",sizeof(d));
return 0;
}
Output:
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8
• Constants are also like normal variables. But, only difference is, their values can’t be modified by
the program once they are defined.
• Syntax:
const data_type variable_name; (or) const data_type *variable_name;
2. Volatile Keyword:
• When a variable is defined as volatile, the program may not change the value of the variable
explicitly.
• But, these variable values might keep on changing without any explicit assignment by the program.
These types of qualifiers are called volatile.
• For example, if global variable’s address is passed to clock routine of the operating system to store
the system time, the value in this address keep on changing without any assignment by the
program. These variables are named as volatile variable.
• Syntax:
volatile data_type variable_name; (or) volatile data_type *variable_name;
29
Storage place: CPU memory
Initial/default value: Zero
Scope: local
static Life: Retains the value of the variable between different function calls.
NOTE:
• For faster access of a variable, it is better to go for register specifiers rather than auto specifies.
• Because, register variables are stored in register memory whereas auto variables are stored in main
CPU memory.
• Only few variables can be stored in register memory. So, we can use variables as register that are
used very often in a C program.
#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
auto int i = 0 ;
printf ( "%d ", i ) ;
i++;
}
Output:
0000
2. Example Program For Static Variable :
Static variables retain the value of the variable between different function calls.
30
#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
static int i = 0 ;
printf ( "%d ", i ) ;
i++;
}
Output:
0123
The scope of this extern variable is throughout the main program. It is equivalent to global
variable. Definition for extern variable might be anywhere in the C program.
#include<stdio.h>
int x = 10 ;
int main( )
{
extern int y;
printf("The value of x is %d \n",x);
printf("The value of y is %d",y);
return 0;
}
int y=50;
Output:
The value of x is 10
The value of y is 50
31
• Register variables are also local variables, but stored in register memory. Whereas, auto variables
are stored in main CPU memory.
• Register variables will be accessed very faster than the normal variables since they are stored in
register memory rather than main memory.
But, only limited variables can be used as register since register size is very low. (16 bits, 32 bits or 64
bits)
#include <stdio.h>
int main()
{
register int i;
int arr[5];// declaring array
arr[0] = 10;// Initializing array
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d \n", i, arr[i]);
}
return 0;
}
Output:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
Control Statements
A statement is a part of your program that can be executed. That is, a statement specifies an
action. Statements generally contain expressions and end with a semicolon. Statements that are written
individually are called Single/Simple statements. Statements that are written as a block are called
Block/Compound statements. A block begins with an open brace {and ends with a closing brace}.
32
➢ Selection / Branch / Decision making / Conditional statements
➢ Loop/ Iteration/ Repetitive statements
➢ Jump / Control transfer statements
➢ Expression Statements
➢ Block statements/ compound statements
Selection Statements:
A selection statement checks the given condition and decides the execution of statements after
the success or failure of the condition. C supports two selection control statements if and switch.
1. If statement
2. Switch Statement
1. If statement:
The if statement is a decision making statement that allows the computer to evaluate an
expression (condition) first and depending on the result of the condition i.e. true or false, it transfers the
control to a particular statement.
Simple if Statement
The simple if statement contains only one condition, if the condition is true, it will execute the
statements that are present between opening and closing braces. Otherwise it will not execute those
statements.
Syntax: Example:/* to check whether a num is Less than 100 or not */
if(condition) #include<stdio.h>
Single-statement #include<conio.h>
OR void main()
if(condition) {
{ int a;
Statement-block clrscr();
} printf("enter an integer ");
scanf("%d",&a);
if(a<=10)
printf("%d is less than 100",a);
getch();
}
33
If...else Statement
This statement is used to define two blocks of statements in order to execute only one block. If
the condition is true, the block of if is executed; otherwise, the block of else is executed.
Syntax: Example:
if (condition) to check whether the given num is a
{ positive number or a negative number
True Block Statements; #include<stdio.h>
------------- #include<conio.h>
} void main()
else {
{ int n;
False Block Statements; clrscr();
------------ printf("enter any number ");
} scanf("%d",&n);
if(n>=0)
{
printf("\n %d is a positive number",n);
}
else
{
printf("\n %d is a negative number",n);
}
getch();
}
34
Nested if –else Statement
When an If statement is placed in another if statement or in else statement, then it is called nested
if statement. The nested if-else is used when a series of decisions are involved. In a nested if-else, an
else statement always refers to the nearest if statement which is within the same block as the else and
that is not already associated with an else.
Syntax: Example: Write a program to finding
greatest among three numbers
if (condition) #include<stdio.h> #include<conio.h>
{ void main()
if(condition) {
{ int a,b;
True Block Statements; clrscr();
------------- printf("enter any two number ");
} scanf("%d%d",&a,&b);
} if(a>b)
else {
{ if(a>c)
False Block Statements; printf(“ %d is greatest”,a);
------------ else
} printf(“ %d is greatest”,c);
}
else
{
if(b>c)
printf(“ %d is greatest”,b);
else
printf(“ %d is greatest”,c);
}
getch();
}
If..Else Ladder Statement
35
The if-else ladder is used when multipath (multiple) decisions are involved.
A multipath decision is a chain of if-elses in which the statement associated with each else is an if-
statement.
Syntax: Example:
Write a program to test whether the given
if(condtion1) number is a single digit or a double digit or
{ a trible digit or more than three digits.
statements1;
} #include<stdio.h>
else if(condition2) #include<conio.h>
{ void main()
statements2; {
} int n;
else if(condition3) clrscr();
{ printf("enter any number");
statements3; scanf("%d",&n);
} if(n>=0 && n<=9)
| printf("\n %d is a single digit number",n);
| else if(n>=10 && n<=99)
| printf("\n %d is a double digit number",n);
else if(conditionN) else if(n>=100 && n<=999)
{ printf("\n %d is a trible digit number",n);
statementsN; else
} printf("\n %d is more than three digits",n);
else getch();
{ }
statements;
}
2. Switch Statement
C has a built-in multiple-branch selection statement, called switch, which successively tests the
value of an expression against a list of integer or character constants. When a match is found, the
statements associated with that constant are executed.
Syntax: Example:
36
case value2: #include<conio.h>
statements2; void main()
break; {
| char ch;
| clrscr();
| printf("enter any single character:");
case valueN: scanf("%c",&ch);
statementsN; switch(ch)
break; {
default: case 'a':
statements; printf("%c is a vowel",ch);
} break;
case 'e':
printf("%c is a vowel",ch);
break;
case 'i':
printf("%c is a vowel",ch);
break;
case 'o':
printf("%c is a vowel ",ch);
break;
case 'u':
printf("%c is a vowel",ch);
break;
default:
printf("\n %c is not a vowel",ch);
}
getch();
}
The expression must evaluate to an integer type. Thus, you can use character or integer values,
but floating point expressions, for example, are not allowed. The value of expression is tested against
the values, one after another, of the constants specified in the case statements. When a match is found,
the statement sequence associated with that case is executed until the break statement or the end of the
switch statement is reached.
The default statement is executed if no matches are found. The default is optional, and if it is
not present, no action takes place if all matches fail. Technically, the break statements inside the switch
statement are optional. They terminate the statement sequence associated with each constant. If the
break statement is omitted, execution will continue on into the next case's statements until either a break
or the end of the switch is reached.
Difference between if & Switch
37
Loop/ Iteration Statements
1. While loop
2. do while loop
3. For loop
In C, and all other modern programming languages, iteration statements (also called loops) allow
a set of instructions to be repeatedly executed until a certain condition is reached. Based on position of
loop, loop statements are classified into two types:
1. entry-controlled loop (pre-test loop)- while, for
2. exit-controlled loop (post-test loop)- do while
1. While loop
While is pre tested/ entry controlled loop statement i.e first condition is checked & body of loop is
executed.
Syntax: Example:Write a program to print first 25
natural numbers
initialization; #include<stdio.h> #include<conio.h>
while(test condition) void main()
{ {
Statements; int n;
Increment / Decrement operation; clrscr();
} n=1;
while(n<=25)
{
printf("%3d",n);
n=n+1;
}
getch();
}
38
➢ The initialization is an assignment statement that is used to set the loop control variable.
➢ The condition is a relational expression that determines when the loop exits.
➢ The increment/decrement defines how the loop control variable changes each time the loop is
repeated.
2. do while loop
Do While is post tested/ exit controlled loop statement i.e first body of loop is executed & finally
condition is checked. Even though condition is false, it will execute the body of loop statements at least
once.
Syntax: Example:
39
Difference between while/for & do while:
➢ In while, if the condition is false, it will never execute the loop statements.
➢ But in do-while, even though condition is false, it will execute the loop statements at least once.
##include<stdio.h> ##include<stdio.h>
#include<conio.h> #include<conio.h>
void main() void main()
{ {
int n; int n;
clrscr( ); clrscr( );
n=1; n=1;
while(n>10) do
{ {
printf(“%d\n”,n); printf("%d",n);
n=n+1; n=n+1;
} } while(n>10);
getch( ); getch();
} }
output: No output because condition is false output: it prints 1 even though condition is false
40
3. for loop
For is pre tested/ entry controlled loop statement i.e first condition is checked &
body of loop is executed.
Syntax: Example:
For (initialization; condition; increment Write a program to print first 10
/ decrement operation ;) numbers
{ #include<stdio.h>
list of statements #include<conio.h>
} void main()
{
int i;
clrscr();
for(i=1; i<=10; i++)
{
printf(“%d\t”,i);
}
getch();
}
However, if condition section is omitted, the for loop becomes an endless loop, which is called an
infinite loop. When the condition is absent, it is assumed to be true. The for statement may have an
initialization and increment/decrement sections. But C programmers more commonly use for (;;)
1. Return Statement
A return may or may not have a value associated with it. A return with a value can be used only
in a function with a non-void return type. In this case, the value associated with return becomes the
return value of the function. A return without a value is used to return (exit) from a void function. The
general form of the return statement is return; (OR) return expression;
The expression may be a constant, variable, or an expression. The expression is present only in
non-void function. In this case, the value of expression will become the return value of the function. The
expression is not present in void function.
2. Break Statement
The break statement has two uses
a) To terminate a case in the switch statement.
b) To force immediate termination of a loop, bypassing the normal loop conditional test. The general
form of the break statement is break keyword followed by semicolon
break;
3. Continue Statement
During the 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 another similar statement called the continue
statement.
However, unlike the break which causes the loop to be terminated, the continue causes the loop
to be continued with the next iteration after skipping any statements in between. In while and do-while
loops, continue causes the control to go to directly to the test condition and then to continue the iteration
process. In the case of for loop, continue causes the control to go to the increment/decrement section of
the loop and then to test condition. The general form of the continue statement is continue keyword
followed by semicolon
continue;
Example:
Write a program to illustrate break
#include<stdio.h>
#include<conio.h>
Void main ()
{
int i;
clrscr();
for(i=1; i<=10; i++)
{
if(i==6)
break;
printf(“%d\t”,i);
}
getch();
}
Output: 1 2 3 4 5
42
Example:
#include<stdio.h>
#include<conio.h>
Void main ()
{
int i;
clrscr();
for(i=1; i<=10; i++)
{
if(i==6)
continue;
printf(“%d\t”,i);
}
getch();
}
Output: 1 2 3 4 5 7 8 9 10
4. goto Statement
The goto statement is used to branch from one point (statement) to another in the program.
The goto statement requires a label in order to identify the place where the branch is to be made. A label
is a valid identifier followed by a colon. The label is placed immediately before the statement where the
control is to be transferred. Furthermore, the label must be in the same function as the goto that uses it –
we can’t jump between functions.
C functions are basic building blocks in a program. All C programs are written using functions to
improve re-usability, understandability and to keep track on them. You can learn below concepts of C
functions in this section in detail.
Definition:
A large C program is divided into basic building blocks called C function. C function contains
set of instructions enclosed by “{ }” which performs specific operation in a C program. Actually,
Collection of these functions creates a C program.
USES OF C FUNCTIONS:
➢ C functions are used to avoid rewriting same logic/code again and again in a program.
➢ There is no limit in calling C functions to make use of same functionality wherever required.
➢ We can call functions any number of times in a program and from any place in a program.
➢ A large C program can easily be tracked when it is divided into functions.
➢ The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve
the functionality and to improve understandability of very large C programs.
44
➢ The value of “m” is passed as argument to the function “square”. This value is multiplied by
itself in this function and multiplied value “p” is returned to main function from function
“square”.
#include<stdio.h>
float square ( float x ); // function prototype, also called function declaration
int main( ) // main function, program starts from here
{
float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
n = square ( m ) ; // function call
printf ( "\nSquare of the given number %f is %f",m,n );
}
float square ( float x ) // function definition
{
float p ;
p=x*x;
return ( p ) ;
}
Output:
Enter some number for finding square
2
Square of the given number 2.000000 is 4.000000
Call By Value:
➢ In call by value method, the value of the variable is passed to the function as parameter.
➢ The value of the actual parameter cannot be modified by formal parameter.
➢ Different Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.
Note:
➢ Actual parameter – This is the argument which is used in function call.
➢ Formal parameter – This is the argument which is used in function definition
45
#include<stdio.h>
void swap(int a, int b); // function prototype, also called function declaration
int main()
{
int m = 22, n = 44;
// calling swap function by value
printf(" values before swap m = %d \n and n = %d", m, n);
swap(m, n);
}
void swap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}
Output:
values before swap m = 22
and n = 44
values after swap m = 44
and n = 22
Call By Reference:
➢ In call by reference method, the address of the variable is passed to the function as parameter.
➢ The value of the actual parameter can be modified by formal parameter.
➢ Same memory is used for both actual and formal parameters since only address is used by both
parameters.
#include<stdio.h>
void swap(int *a, int *b); // function prototype, also called function declaration
int main()
{
int m = 22, n = 44;
// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
46
swap(&m, &n);
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
printf("\n values after swap a = %d \nand b = %d", *a, *b);
}
Output
values before swap m = 22 and n = 44
values after swap a = 44 and b = 22
All functions can be called either with arguments or without arguments in a C program. These
functions may or may not return values to the calling function. Now, we will see simple example C
programs for each one of the below.
1. C function with arguments (parameters) and with return value.
2. C function with arguments (parameters) and without return value.
3. C function without arguments (parameters) and without return value.
4. C function without arguments (parameters) and with return value.
function declaration:
int function ( int );function call: function (
a );
function definition:
int function( int a )
{
statements;
1. With arguments and with return a;
return values }
function declaration:
void function ( int );function call: function(
a );
function definition:
2. With arguments and without void function( int a )
return values {
47
statements;
}
function declaration:
void function();function call: function();
function definition:
void function()
3. Without arguments and {
without statements;
return values }
function declaration:
int function ( );function call: function ( );
function definition:
int function( )
{
statements;
4. Without arguments and with return a;
return values }
NOTE:
➢ If the return data type of a function is “void”, then, it can’t return any values to the calling
function.
➢ If the return data type of the function is other than void such as “int, float, double etc”, then, it
can return values to the calling function.
48
// Accessing each variable
printf("value of arr[%d] is %d\n",i,arr[i]);
}
printf("value of str is %s\n",str);
printf("\n ***values after modification***\n");
a= function(a, &arr[0], &str[0]);
printf("value of a is %d\n",a);
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d\n",i,arr[i]);
}
printf("value of str is %s\n",str);
return 0;
}
int function(int a, int *arr, char *str)
{
int i;
a = a+20;
arr[0] = arr[0]+50;
arr[1] = arr[1]+50;
arr[2] = arr[2]+50;
arr[3] = arr[3]+50;
arr[4] = arr[4]+50;
strcpy(str,"\"modified string\"");
return a;
}
Output:
***values before modification***
value of a is 20
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
value of str is “fresh2refresh”***values after modification***
value of a is 40
value of arr[0] is 60
value of arr[1] is 70
value of arr[2] is 80
value of arr[3] is 90
49
value of arr[4] is 100
value of str is “modified string”
Output:
value of a is 20
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
value of str is “vemu”
Output:
values : a = 50 and b = 80
Preprocessor Directives
The C preprocessor is a macro processor that is used automatically by the C compiler to transform your
program before actual compilation (Proprocessor direcives are executed before compilation.). It is called
a macro processor because it allows you to define macros, which are brief abbreviations for longer
constructs. A macro is a segment of code which is replaced by the value of macro. Macro is defined
by #define directive.
Preprocessing directives are lines in your program that start with #. The # is followed by an identifier that
is the directive name. For example, #define is the directive that defines a macro. Whitespace is also
allowed before and after the #.
The # and the directive name cannot come from a macro expansion. For example, if foo is defined as a
macro expanding to define, that does not make #foo a valid preprocessing directive.
All preprocessor directives starts with hash # symbol
List of preprocessor directives
1. #include
2. #define
3. #undef
4. #ifdef
5. #ifndef
6. #if
7. #else
8. #elif
9. #endif
10. #error
11. #pragma
1. #include
The #include preprocessor directive is used to paste code of given file into current file. It is used
include system-defined and user-defined header files. If included file is not found, compiler renders error.
It has three variants
52
#include <file>
This variant is used for system header files. It searches for a file named file in a list of directories
specified by you, then in a standard list of system directories.
#include "file"
This variant is used for header files of your own program. It searches for a file named file first in
the current directory, then in the same directories used for system header files. The current directory is the
directory of the current input file.
#include anything else
This variant is called a computed #include. Any #include directive whose argument does not fit
the above two forms is a computed include.
2. Macro's (#define)
Let's start with macro, as we discuss, a macro is a segment of code which is replaced by the value
of macro. Macro is defined by #define directive.
Syntax: #define token value
There are two types of macros:
1. Object-like Macros
2. Function-like Macros
Object-like Macros
The object-like macro is an identifier that is replaced by value. It is widely used to represent
numeric constants
Syntax: #define PI 3.1415
Here, PI is the macro name which will be replaced by the value 3.14. Let's see an example of
Object-like Macros
#include <stdio.h>
#define PI 3.1415
main()
{
printf("%f",PI);
}
Output: 3.140003.1400
Function-like Macros
The function-like macro looks like function call.
#define MIN(a,b) ((a)<(b)?(a):(b))
Here, MIN is the macro name. Let's see an example of Function
#include <stdio.h>
#define MIN(a,b) ((a)<(b)?(a):(b))
void main()
{
printf("Minimum between 10 and 20 is: %d\n", MIN(10,20));
}
Output: minimum between 10 and 20 is: 10
53
Preprocessor Formatting
A preprocessing directive cannot be more than one line in normal circumstances. It may be split
cosmetically with Backslash-Newline. Comments containing Newlines can also divide the directive into
multiple lines.
for example, you can split a line cosmetically with Backslash-Newline anywhere
/*
*/#/*
*/defi\
Ne FO\
0 10\
20
is equivalent into #define FOO 1020
3. #undef
To undefine a macro means to cancel its definition. This is done with the #undefdirective.
#undef token
55