Programming in C Language
Programming in C Language
Programming is the technique of developing logic and logic is the science of reasoning.
A set of instruction which describes the steps to be followed to carry out an activity is called Algorithm.
The task of writing a computer program involves going through several stages. So the habit of writing the
algorithm is reduce the labor behind writing a program to solve a problem.
Flowcharts
A flowchart is a graphical representation of the sequence of operations for the solution of a problem
.Program flowcharts show the sequence of instructions written in a single program or subroutine. These
sequences are represented by using some standard symbols.
Output
Data Flow
Since a flowchart shows the flow of operations in a pictorial form any error in the logic of the procedure
can be detected easily. Once the flowchart is ready, the programmer can concentrate on coding the
operators in each box of the flowchart in terms of the statements of the programming language. This will
easily create an error free program.
Language is nothing but a means of communication between two objects. Similarly a computer language
is a standardized communication technique for expressing instructions to a computer system. A language
is used to develop a software.
Basically computer languages can be classified into three types viz. Machine Level Language, Assembly
Level Language, High Level Language.
Computer Language
Machine Level Language: This is the only language that a computer can understand and is a
combination of 0 and 1. Whatever we provide as input to the computer system they are converted into
the form of 0 and 1. These are called as binary states in a computer system.
Assembly Level Language: This is a symbolic language that is used to develop programs that must
go through assembler to be converted into a machine code.
High Level Language: These languages are written as English-like instructions that guide the computer
what to do and how to do it. Unlike the above two languages, these languages are hardware independent.
They can be run on any system that has a translator (compiler or interpreter) for that particular
language.E.g. C++, Java, C# etc.
N.B. A computer can only understand Machine Level Language. It cannot understand either Assembly
Level Language or High Level Language. We can easily understand high level and assembly level
languages but it is very difficult for us to understand machine level language. So a translator is required
which can convert assembly and high level languages into the machine level languages. These translators
are assembler, compiler and interpreter.
C LANGUAGE
C is considered as a middle level language as it contains features of both high level and
assembly level language.
It is the mother of many high level languages such as C++, Java etc.
Programs written in C are efficient and fast.
C is a highly portable language as the programs written in C can be executed in any
computer with little or no modification.
This language was developed at Bell Laboratories of USA in early 1970 by a system programmer named
Dennis Ritchie. Hence Dennis Ritchie is considered as the father of C language.
A variable is an identifier that is used to represent some specified type of data. The data is the constant.
It is like a container which can store many things. In this case the container is the variable as it can store
different things but the things that are stored are constants. For example we put water in a glass, in this
case the glass is the variable and water is constant.
DATA TYPES
Data types refer to the type of container in which the data can be stored.
Data types can be broadly classified as Primary and secondary data types.
Data Types
Primary Secondary
Integer Array
Float Pointer
Character Structure
Union
Enumeration
OPERATORS IN C
The operators that operate with a single operand are called Unary Operators. E.g. – (Subtraction
Operator).
The operators that operate with two operands are called Binary Operators. Almost all the operators are
Binary. E.g. +, -, *, /, %, etc.
The operators that operate with three operands are called Ternary operators. There is only a single
ternary operator in C. It is ? :.
Arithmetic Operators:
The operators that are used to perform all the arithmetic operations are called arithmetic operators. It
includes +, -, *, /, %.
+ Add 5+5 10
- Subtract 10-5 5
/ Divide 20/3 6
* Multiply 5*4 20
% Remainder of division 20 % 3 2
+ Operator: This is called the addition operator and is used to add two numbers. It is a binary operator as
it requires two operands. E.g. to add 3 and 5 we write 3+5.
- Operator: This is called the minus operator or subtraction operator and is used to subtract two
numbers. It can be also used to negate a number. It can behave both as a unary and Binary operator E.g. to
add 3 and 5 we write 3-5, to negate a number (say 3) we write (-3 )
* Operator:This is called the multiplication operator and is used to multiply two numbers. It is a binary
operator as it requires two operands. E.g. to multiply 3 and 5 we write 3*5.
/ Operator:This is called the division operator and is used to divide one number with the other. It is
binary as it requires 2 operands. It operates as
In other words, this operator gives the quotient of any integer division.
% Operator: This is called the modulus operator or remainder operator. It gives the remainder of any
division operation and can be used only in case of integer or character (ASCII Value) and cannot be used
with float data type.E.g. 9%2 = 1, because when we divide 9 by 2 we get 4 as the quotient and 1 as the
remainder. But 9.0 % 2 or 9%2.0 is not possible.
There are three logical operators in C. They are &&, || and !. These operators operate with Boolean values
(True or False) and also return a Boolean value. True is represented by a non-zero value and false is
represented by zero.
Operators Description
These operators can be best explained by a table called the Truth Table. All the logical operators along
with their truth tables are explained as follows:
&& Operator: This is called the AND operator. It is binary and returns TRUE (non-zero value) only if both
the operands are TRUE. In all other cases it returns a FALSE (zero value). The truth table is as:
A Operator B Result
|| Operator: This is called the OR operator. It is binary and returns TRUE (non-zero value)if any of the
operand is TRUE. It returnsFALSE (zero value) only if both the operands are FALSE. The truth table is as:
A Operator B Result
Operator A Result
! True(1) False(0)
! False(0) True(1)
Relational Operators:
The operator = is referred to as the assignment operator. It is used to assign the value on its right hand
side to a variable on its left hand side. The right side of the assignment operator can be a variable or a
constant but the left side can only be a variable.
y=x =>> means we are assigning the value of x (which is 1) to the variable y. Now y also
contains 1.
Input / Output Handling in C refer to the methods in which a user can provide input to the computer
system and receive output from the computer system. The functions that are used to receive output from
the computer system is printf ()and that for input is scanf ()
Control Characters in C
CHARACTER MEANING
\n New line, moves the cursor to the beginning of the next line
Format Specifiers in C
The characters that are used to specify what data type is given as input and what data type is received as
output are called format Specifiers. They are written by using the % character. There are several format
Specifiers in C as follows:
CHARACTER MEANING
%c Character
%d Decimal Integer
%f Float
%e Float
%g Float
%o Octal Integer
%s Strings
%x Hexadecimal integer
Control Instructions in C
The instructions that determine the flow of control in a program are called control instructions. In other
words, they specify the order in which the various instructions in a program are to be executed by the
computer.
The sequence control instructions are used in those cases where the instructions in a program are to be
executed in the order in which they appear in the program.
The Decision control instructions are used in those cases where the instructions in a program are to be
executed based on a particular condition. They are implemented using if, if…else, if…elif…else and nested
if…else.
The Case control instruction is similar to Decision Control instruction but here decision is taken from
multiple cases. They are implemented using switch…case statement.
The Loop control instructions are used in those cases where a block of statement is to be executed
repeatedly based on a condition. They are implemented using loops viz. while, do…while and for loops.
Simple Programs in C
C program requires a compiler to compile. We assume that a compiler has been already installed in the
machine in which you are typing the program. There are several compilers which we can use. The syntax
of writing a C program for all of them is almost the same. Here we are considering Borland C compiler.
1. Write a Program (WAP) in C to display “Most welcome to the vast world of C”.
Sol.
#include<stdio.h>
void main()
{
printf (“Most welcome to the vast world of C”);
}
stdio.h=> It refers to standard input output header file. This is a special type of file that
includes all the instructions for taking input and receiving output
from the computer system.
#include => It is a preprocessor directive that is used to include a header file in
our program. Here since we are to include stdio.h file we have used
#include<stdio.h>
main () =>Execution of a C program starts from main function. This function returns
nothing to the OS and so we have written void before main(). The
curly braces ({}) is referred to as the block of the main() function.
printf () => It is also a function and is used to provide output of the program.
The words written inside double quotes (“”) are displayed as they
appear on the output screen. Every statement in C ends with a
semicolon (;).
Decision Control Statements are used to control the flow of program's execution based on a particular
condition. C supports the following decision control instructions:
if structure
The ifstructure performs an indicated action only when the condition is True; otherwise the action is
skipped. The statements in the If Block will be executed if the condition in If is True.
Syntax:
if(<condition>)
Statement;
OR
if (<condition>)
{
Statement1; if Block
Statement2;
…
}
e.g.:
if (average>75)
Grade = ‘A’;
OR
if (average>75)
{
Grade = ‘A’;
printf (“Very good grade = %d”, Grade);
}
if...else structure
The if...else structure allows the programmer to specify that a different action is to be performed when
the condition is True than when the condition is False. If the condition is TRUE the statements in the if-
block will be executed otherwise the statements in the else-block will be executed.
if (<condition>)
{
Statement1; if Block
Statement2;
…
}
OR
If (average>50)
{
Res=’P’;
printf(“Pass”);
}
Else
{
Res=’F’;
printf(“Fail”);
}
if...elseif structure
Syntax:
if< condition 1 >
Statements;
else if < condition 2 >
Statements;
else if < condition 3 >
Statements;
else
Statements;
OR
if (<condition>)
{
Statement1;
Statement2;
…
}
else if (<condition>)
{
Statement1;
Statement2;
…
}
else if (<condition>)
{
Statement1;
Statement2;
…
e.g.: Assume you have to find the grade using nested if and display in a text box
This control instruction allows a user to make a decision from a number of choices. It is implemented by
using switch-case-default statement.
Switch-case is an extension of if-else statement. It allows us to make a decision from a number of choices.
It is properly called switch-case-default statement.
switch (exp)
{
case<constant1>:
Statement;
break;
case<constant2>:
Statement;
break;
case<constant3>:
Statement;
break;
case<constant4>:
Statement;
break;
default:
Statement;
}
Where exp must be an integer or character constant or a variable that evaluates to an integer or
character.
E.g.
#include<stdio.h>
void main()
{
int n;
printf(“Please input a number”);
scanf(“%d”, &n);
switch (n)
{
case 1:
printf(“One”);
case 2:
printf(“Two”);
case 3:
printf(“Three”);
case 4:
printf(“Four”);
default:
printf(“No Match Found”);
}
}
In the above example if the user
Inputs 1 then output will be One Two Three Four No Match Found
Inputs 3 then output will be Three Four No Match Found.
Inputs anything other than 1 to 4 then output will be No Match Found.
Since no break statement is used in the cases so the output appears in the above format.
#include<stdio.h>
void main()
{
int n;
printf(“Please input a number”);
scanf(“%d”, &n);
switch (n)
{
case 1:
printf(“One ”);
break;
case 2:
printf(“Two ”);
break;
case 3:
printf(“Three ”);
break;
case 4:
printf(“Four ”);
Limitations of switch-case:
Although switch-case is considered as an extension of if-else, however it has several limitations. They are
as:
The case statements can contain only contain either an integer or character constant or
an expression that evaluates to one of these constants. It cannot be used with float.
Cases can never have variable expression or relational expression or logical expression.
E.g. i<=10, i && j or i+3 etc cannot be used. But 4+6 or 6/2 etc can be used.
Multiple cases cannot use the same expression. E.g.
Switch(a)
{
Case 3:
…
Case 3:
…
} cannot be used
INCREMENT / DECREMENT
Increment means increasing the value of a variable while decrement means decreasing the value of a
variable. They are represented using the increment (++) and decrement (--) operators.
Pre-increment / Pre-decrement
If we use the increment operator before the variable then it is called Pre-increment. E.g. ++x. Similarly for
pre-decrement we write --x.
Post-increment / Post-decrement
If we use the increment operator after the variable then it is called Post-increment. E.g. x++. Similarly for
Post-decrement we write x--.
Each loop in C has two sections viz. Condition and Body of the loop. Based on the position of their position
loops can be classified into 2 types viz.
While loop
Do…While loop
For loop
Loops
For loop
In such a loop the body of the loop is executed In such a loop the body of the loop is executed
i)
after testing the condition before testing the condition
iii) E.g. While loop and for loop. E.g. do-while loop
Initialization.
Termination
While Loop
Thewhile Loop is used to execute statements until a certain condition is TRUE. This is the most simple
loop construct. It is an entry-controlled loop as it evaluates a test expression before allowing entry into
the body of the loop.
If the condition is False on the first iteration or pass, the statements in the body of the loop will never be
executed.
Initialize Counter;
while (Termination condition)
{
Statement 1;
Body of Statement2;
loop …………..
Increment / Decrement counter;
}
For example the following program prints Welcome to loop 10 times on the screen using while Loop:
#include<stdio.h>
void main()
{
int i=1; -------------> Initialization
while(i<=10)-------------> Termination Condition
{
printf(“Welcome to loop”);
i=i+1;-------------->Increment
}
}
Here the variable i is the counter variable. It is initialized to the value 1. The while loop then tests the
condition (i<=10).Since the condition is true, the body of the loop gets executed. The increment statement
then increments the value of i to 2 and the loop starts the next iteration. This continues till the condition
(i<=10) in while remains TRUE.
Do...While loop
The Do…Whileloop isan exit-control loop as it first executes the statements and then tests the condition
after each execution. Although if the condition is false for the first time, the body of the loop will get
executed at least once.
Initialize Counter;
do
{
Statement 1;
Body of Statement2;
loop …………..
Increment / Decrement counter;
}
while (Termination condition);
Here the variable i is the counter variable. It is initialized to the value 1. The do while loop first executes
the body of the loop and then tests the condition. If the condition is TRUE it will proceed for the next
iteration, otherwise the loop will get terminated. This continues till the condition (i<=10) in while
remains TRUE.
For Loop
The For Loop is the most popular looping construct in C. It is an Entry-controlled loop. It makes a
program compact by combining all the three basic parts of a loop (viz. initialization, termination
condition and increment or decrement) in a single line. These parts are separated by a semi colon (;).
For example the following program prints Welcome to loop 10 times on the screen using for Loop:
#include<stdio.h>
void main() Initialization
{ Termination Condition
int i; Increment
for (i=1 ; i<=10 ; i++)
{
printf(“Welcome to loop”);
}
}
There are two statements that can be used with loops. They are:
Break.
Continue.
The break statement is used in a loop to bring the control out of a loop. When the break statement is
encountered in a loop the control comes out from the body of the loop. It can be used with while, do-while
and for loops.
Continue statement
It is used to bypass the remainder of the current pass through a loop. The loop does not terminate when a
continue statement is encountered. Rather the remaining statements are skipped and the computation
proceeds to the next iteration through the loop. It can be include in a while, do-while and for loop.
ARRAYS IN C
An array is a group of elements of similar data type that share a common name occupying contiguous
blocks of memory and are differentiated from one another by their positions in the array. They are
referred to as derived data type in C.
The elements in an array are accessed by the position of the elements in the array. It is called index or
subscript of the array.
One-dimensional Array
Multi-dimension Array
One-dimensional Array
E.g.
int x[5];
Multi-dimensional Array
Arrays having more than one dimension are called multi-dimensional array. There are several types of
Multi-dimensional such as two-dimensional array or 2D-Array.
2D-Arrays are also called matrix since the elements are stored in rows and columns in a row-major
fashion.
E.g.:
int x[4][3];
A string is nothing but an array of characters that ends with a NULL character (\0).
scanf() :scanf(“%s”, str); will take a string as input from the user and then store its
contents in str.
gets(): gets(str); will take a string as input from the user and then store its contents in
str.
printf() :printf(“%s”, str); will display the contents stored in the string str.
puts(): puts(str); will display the contents stored in the string str.
strlen()
strcmp()
strcpy()
strcmp()
strcat()
To use all these functions we have to use the header file <string.h>.
FUNCTIONS
A function is a self contained block of statement that performs a coherent or specific task of some kind.
Every C program is a collection of several functions.
The function declaration or function prototype is used to tell the compiler that we are using a specified
function in our program.
The function call is used to call a function from the body of another function. The function that calls
another function is called a calling function and the function that is being called is called a called
function.
The function definition is used to specify the tasks that the function should perform.
To transfer the value of a variable of one function to a variable of another function we have to pass the
arguments between the functions.
There are two ways to pass values of variable between function. They are:
Call by value: Here the values of arguments are passed directly between functions.
Call by Reference: Here addresses of the arguments are passed between functions.
Recursive function:
A function is called recursive if a statement within the body of a function calls itself again and again. It is
also called “circular definition”. Recursion is the process of defining a function in terms of itself.
POINTERS IN C
They are nothing but variables that can store the address of another variable. In other words, a pointer
variable points to the variable whose address is stored in it.
There are basically 2 operators that are used with pointers. They are-
STRUCTURE IN C
It is a user-defined heterogeneous data-type where we can store elements of different data type. In other
words, structure is nothing but an array of heterogeneous data type.
A structure is declared using the keyword struct. The members of a structure are accessed using the dot
(.) operator.
Syntax:
struct<structure-name>
{
Data-type member-1;
Data-type member-2;
Data-type member-3;
};
Example:
#include<stdio.h>
void main()
{
struct Test
{
int x;
float y;
};
struct Test tt;
tt.x=10;
tt.y = 9.8;
printf(“%d,%d”,tt.x,tt.y);
}
In the above example, Test is the name of structure with 2 members x of type int and y of type float. tt is
the variable of type struct Test. To access the members of tt we have used the dot(.) operator along with
it.
*****THE END*****