Introduction To Computer Programming
Introduction To Computer Programming
COMPUTER PROGRAMMING
TUTORIAL
Dr. TIRUS MUYA
0|Page S C S 1 0 1 b y Dr. T I R U S M U Y A
Welcome to C Programming Language
Why do we use C?
Who invented C?
Following are the softwares and applications used to create and execute C
programs...
1. Turbo C -
2. Turbo C++ -
3. GNU C -
4. Code Blocks -
5. Net Beans –
Computer Languages
Generally, we use languages like english, hindi, telugu etc., to make communication
between two persons. That means, when we want to make communication between
two persons we need a language through which persons can express their feelings.
Similarly, when we want to make communication between user and computer or
between two or more computers we need a language through which user can give
information to computer and vice versa. When user wants to give any instruction to
the computer the user needs a specific language and that language is known as
Computer languages are the languages through which user can communicate
with the computer by writing program instructions.
Every computer programming language contains a set of predefined words and a set
of rules (syntax) that are used to create instructions of a program.
Over the years, computer languages have been evolved from Low Level to High Level
Languages. In the earliest days of computers, only Binary Language was used to write
programs. The computer languages are classified as follows...
Low Level language is the only language which can be understood by the
computer. Binary Language is an example of low level language. Low level language
is also known as Machine Language. The binary language contains only two symbols
1 & 0. All the instructions of binary language are written in the form of binary
numbers 1's & 0's. A computer can directly understand the binary language. Machine
language is also known as Machine Code.
As the CPU directly understands the binary language instructions, it does not
requires any translater. CPU directly starts executing the binary language
instructions, and takes very less time to execute the instructions as it does not
requires any translation. Low level language is considered as the First Generation
Language (1GL).
Advantages
Disadvantages
Middle level language is a computer language in which the instructions are created
using symbols such as letters, digits and special characters. Assembly language is an
example of middle level language. In assembly language, we use predefined words
called mnemonics. Binary code instructions in low level language are replaced with
mnemonics and operands in middle level language. But computer can not understand
mnemonics, so we use a translator called Assembler to translate mnemonics into
binary language. Assembler is a translator which takes assembly code as input and
produces machine code as output. That means, computer can not understand middle
level language, so it needs to be translated into low level language to make it
understandable by the computer. Assembler is used to translate middle level
language to low level language.
Advantages
Disadvantages
High level language is a computer language which can be understood by the users.
High level language is very similar to the human languages and have a set of grammar
rules that are used to make instructions more easily. Every high level language have
a set of predefined words known as Keywords and a set of rules known as Syntax to
create instructions. High level language is more easier to understand for the users
but the computer can not understand it. High level language needs to be converted
into low level language to make it understandable by the computer. We
use Compiler or interpretor to convert high level language to low level language.
Languages like COBOL, FORTRAN, BASIC, C ,C++, JAVA etc., are the examples of high
level languages. All these programming languages use human understandable
language like english to write program instructions. These instructions are converted
to low level language by the compiler so that it can be understood by the computer.
Disadvantages
The following figure provides few key points related to the computer languages.
From the above figure, we can observe the following key points...
• The programming languages like C, C++, Java etc., are written in High level
language which is more comfortable for the developers.
• High level language is more closer to the users.
• Low level language is more closer to the computer. Computer hardware can
understand only the low level language (Machine Language).
• The program written in high level language needs to be converted to low level
language to make communication between the user and the computer.
• Middle level language is not closer to both user and computer. We can
consider it as a combination of both high level language and low level
language. When we execute a C program it undergoes with following
process…
Generally, program development life cycle contains 6 phases, they are as follows….
• Problem Definition
• Problem Analysis
• Algorithm Development
• Coding & Documentation
• Testing & Debugging
• Maintenance
1. Problem Definition
In this phase, we define the problem statement and we decide the boundaries of the
problem. In this phase we need to understand the problem statement, what is our
requirment, what should be the output of the problem solution. These are defined
in this first phase of the program development life cycle.
3. Algorithm Development
During this phase, we develop a step by step procedure to solve the problem using
the specification given in the previous phase. This phase is very important for
program development. That means we write the solution in step by step statements.
During this phase, we check whether the code written in previous step is solving the
specified problem or not. That means we test the program whether it is solving the
problem for various input data values or not. We also test that whether it is providing
the desired output or not.
6. Maintenance
During this phase, the program is actively used by the users. If any enhancements
found in this phase, all the phases are to be repeated again to make the
enhancements. That means in this phase, the solution (program) is used by the end
user. If the user encounters any problem or wants any enhancement, then we need
to repeat all the phases from the starting, so that the encountered problem is solved
or enhancement is added.
Design Strategies
a) Top-Down Strategy
The top-down strategy uses the modular approach to develop the design of a system.
It is called so because it starts from the top or the highest-level module and moves
towards the lowest level modules.
In this technique, the highest-level module or main module for developing the
software is identified. The main module is divided into several smaller and simpler
submodules or segments based on the task performed by each module. Then, each
submodule is further subdivided into several submodules of next lower level. This
b) Bottom-Up Strategy
Bottom-Up Strategy follows the modular approach to develop the design of the
system. It is called so because it starts from the bottom or the most basic level
modules and moves towards the highest level modules.
In this technique,
a) The modules at the most basic or the lowest level are identified.
b) These modules are then grouped together based on the function performed
by each module to form the next higher-level modules.
c) Then, these modules are further combined to form the next higher-level
modules.
d) This process of grouping several simpler modules to form higher level modules
continues until the main module of system development process is achieved.
This section is used to provide small description of the program. The comment lines
are simply ignored by the compiler that means they are not executed. In C, there
are two types of comments.
1. Single Line Comments: Single line comment begins with // symbol. We can
write any number of single line comments.
2. Multiple Lines Comments: Multiple lines comment begins with /* symbol
and ends with */. We can write any number of multiple lines comments in a
program.
In a C proogram, the comment lines are optional. Based on the requirment, we write
the comments. All the comment lines in a C program just provide the guidelines to
understand the program and its code.
Preprocessing commands are used to include header files and to define constants.
We use #include statement to include header file into our program. We
use #define statement to define a constant. The preprocessing statements are used
Global declaration is used to define the global variables, which are common for all
the functions after its declaration. We also use the global declaration to declare
functions. This global declaration is used based on the requirment.
Every C program must write this statement. This statement (main) specifies the
starting point of the C program execution. Here, main is a user defined method
which tells the compiler that this is the starting point of the program execution.
Here, int is a datatype of a value that is going to return to the Operating System
after completing the main method execution. If we don't want to return any value,
we can use it as void.
The open brase indicates the begining of the block which belongs to the main
method. In C program, every block begins with '{' symbol.
In this section, we declare the variables and functions that are local to the function
or block in which they are declared. The variables which are declared in this section
are valid only within the function or block in which they are declared.
In this section, we write the statements which perform tasks like reading data,
displaying result, calculations etc., All the statements in this section are written
according to the requirment.
The close brase indicates the end of the block which belongs to the main method.
In C program every block ends with '}' symbol.
This is the place where we implement the userdefined functions. The userdefined
function implementation can also be performed before the main method. In this
case, the user defined function need not to be declared. Directly it can be
implemented, but it must be before the main method. In a program, we can define
as many userdefined functions as we want. Every user defined function needs a
function call to execute its statements.General rules for any C program
C Character Set
Every C program contains statements. These statements are constructed using words
and these words are constructed using characters from C character set. C language
character set contains the following set of characters...
1. Alphabets
2. Digits
3. Special Symbols
Alphabets
C language supports all the alphabets from english language. Lower and upper case
letters together supports 52 alphabets.
Digits
Digits - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special Symbols
C language supports rich set of special symbols that include symbols to perform
mathematical operations, to check conditions, white spaces, back spaces and other
special symbols.
Every character in C language has its equivalent ASCII (American Standard Code for
Information Interchange) value.
1. Keywords
2. Identifiers
3. Operators
4. Special Symbols
5. Constants
6. Strings
7. Data values
Keywords
Keywords are the reserved words with predefined meaning which already
known to the compiler
Properties of Keywords
The following table specifies all the 32 keywords with their meaning...
11 | P a g e S C S 1 0 1 b y Dr. T I R U S M U Y A
C Identifiers
int marks;
char studentName[30];
The following are the commonly used rules for creating identifiers for better
programming...
Datatypes
Data used in c program is classified into different types based on its properties. In c
programming langauge, datatype can be defined as a set of values with similar
characteristics. All the values in a datatype have the same properties.
Datatypes in c programming language are used to specify what kind of value can be
stored in a variable. The memory size and type of value of a variable are determined
by varible datatype. In a c program, each variable or constant or array must have a
datatype and this datatype specifies how much memory is to be allocated and what
type of values are to be stored in that variable or constant or array. The formal
definition of datatype is as follows...
Primary Datatypes
The primary datatypes in C programming language are the basic datatypes. All the
primary datatypes are already defined in the system. Primary datatypes are also
called as Built-In datatypes. The following are the primary datatypes in c
programming lanuage...
1. Integer Datatype
2. Floating Point Datatype
3. Double Datatype
4. Character Datatype
Integer datatype is a set of whole numbers. Every integer value does not have the
decimal value. We use the keyword "int" to represent integer datatype in c. We use
the keyword int to declare the variables and to specify return type of a function.
The integer datatype is used with different type modifiers like short, long, signed
and unsigned. The following table provides complete details about integer datatype.
Floating point datatypes are set of numbers with decimal value. Every floating point
value must contain the decimal value. The floating point datatype has two
variants...
• float
• double
Character Datatype
The following table provides complete information about all the datatypes in c
programming language...
The void datatype means nothing or no value. Generally, void is used to specify a
function which does not return any value. We also use the void datatype to specify
empty parameters of a function.
Enumerated Datatype
Derived Datatypes
Derived datatypes are user-defined data types. The derived datatypes are also called
as user defined datatypes or secondary datatypes. In c programming language, the
derived datatypes are created using the following concepts...
• Arrays
• Structures
• Unions
• Enumeration
Variables
Variables in c programming language are the named memory locations where user
can store different values of same datatype during the program execution. That
means, variable is a name given to a memory location in which we can store different
values of sasme datatype. In other words a variable can be defined as a storage
container to hold values of same datatype during the program execution. The formal
definition of datatype is as follows...
A variable name may contain letters, digits and underscore symbol. The following
are the rules to specify a variable name...
Declaration Syntax:
datatype variableName;
Example
int number;
The above declaration tells to the compiler that allocate 2 bytes of memory with
the name number and allows only integer values into that memory location.
Constants in C
A constant is a named memory location which holds only one value throughout
the program execution.
Integer constants
A floating point constant must contain both integer and decimal parts. Some times
it may also contain exponent part. When a floating point constant is represented in
exponent form, the value must be suffixed with 'e' or 'E'.
Example
Character Constants
Example
'A'
'2'
'+'
String Constants
OR
Example
const int x = 10 ;
Example Program
#include <stdio.h>
void main(){
int i = 9 ;
const int x = 10 ;
i = 15 ;
x = 100 ; // creates an error
printf("i = %d\nx = %d", i, x ) ;
The above program gives an error because we are trying to change the constant
variable value (x = 100).
We can also create constants using '#define' preprocessor directive. When we create
constant using this preprocessor directive it must be defined at the beginning of the
program (because all the preprocessor directives must be written before the gloabal
declaration).
We use the following syntax to create constant using '#define' preprocessor
directive...
#define PI 3.14
Example Program
#include <stdio.h>
#define PI 3.14
void main(){
int r, area ;
area = PI * (r * r) ;
Output Functions in C
1. printf()
2. putchar()
3. puts()
4. fprintf()
printf() function
The printf() function is used to print string or data values or combination of string
and data values on the output screen (User screen). The printf() function is built-in
function defined in a header file called "stdio.h". When we want to use printf()
function in our program we need to include the respective header file (stdio.h)
using #include statement. The printf() function has the following syntax...
Syntax:
printf("message to be display!!!");
#include <stdio.h>
void main(){
}
Output:
Hello! Welcome to btechsmartclass!!!
In the above example program, we used the printf() function to print a string on to
the output screen.
The printf() function is also used to display data values. When we want to display
data values we use format string of the data value to be display.
Syntax:
printf("format string",variableName);
Example Program
#include <stdio.h>
void main(){
int i = 10;
float x = 5.5;
printf("%d %f",i, x);
}
Output:
10 5.5
In the above example program, we used the printf() function to print data values of
variables i and x on to the output screen. Here i is a integer variable so we have
used format string %d and x is a float variable so we have used format string %f.
The printf() function can also used to display string along with data values.
Syntax:
#include <stdio.h>
void main(){
int i = 10;
float x = 5.5;
printf("Integer value = %d, float value = %f",i, x);
}
Output:
Integer value = 10, float value = 5.5
In the above program we are displaying string along with data values.
Every function in C programming language must have a return value. The printf()
function also have integer as return value. The printf() function returns an integer
value equalent to the total number of characters it has printed.
Example Program
#include <stdio.h>
void main(){
int i;
i = printf("btechsmartclass");
printf(" is %d number of characters.",i);
}
Output:
btechsmartclass is 15 number of characters.
#include <stdio.h>
void main(){
printf("Welcome to ");
printf("btechsmartclass ");
printf("the perfect website for learning");
}
Output:
In the above program, there are 3 printf() statements written in different lines but
the output is displayed in single line only.
To display the output in different lines or as we wish, we use some special characters
called escape sequences. Escape sequences are special characters with special
functionality used in printf() function to format the output according to the user
requirment. In C programming language, we have the following escape sequences...
#include <stdio.h>
void main(){
printf("Welcome to\n");
printf("btechsmartclass\n");
printf("the perfect website for learning");
}
Output:
Welcome to btechsmartclass the perfect website for learning
putchar() function
The putchar() function is used to display single character on the output screen. The
putchar() functions prints the character which is passed as parameter to it and
returns the same character as return value. This function is used to print only single
charater. To print multiple characters we need to write multiple times or use a
looping statement. Consiider the following example program...
#include <stdio.h>
void main(){
char ch = 'A';
putchar(ch);
puts() function
The puts() function is used to display string on the output screen. The puts()
functions prints a string or sequence of characters till the newline. Consiider the
following example program...
#include <stdio.h>
void main(){
char name[30];
printf("\nEnter your favourite website: ");
gets(name);
puts(name);
}
Output:
Enter your favourite website: www.mut.ac.ke
www.btechsmartclass.com
fprintf() function
The fprintf() function is used with the concept of files. The fprintf() function is used
to print a line into the file. When you want to use fprintf() function the file must be
opened in writting mode.
Input Functions in C
1. scanf()
2. getchar()
3. getch()
4. gets()
5. fscanf()
scanf() function
The scanf() function is used to read multiple data values of different data types from
the keyboard. The scanf() function is built-in function defined in a header file called
"stdio.h". When we want to use scanf() function in our program, we need to include
the respective header file (stdio.h) using #include statement. The scanf() function
has the following syntax...
scanf("format strings",&variableNames);
Example Program
#include <stdio.h>
void main(){
int i;
printf("\nEnter any integer value: ");
scanf("%d",&i);
printf("\nYou have entered %d number",i);
}
Output:
In the above example program, we used the scanf() function to read an integer value
from the keyboard and store it into variable 'i'.
The scanf function also used to read multiple data values of different or same data
types. Consider the following example program...
#include <stdio.h>
void main(){
int i;
float x;
printf("\nEnter one integer followed by one float value :
");
scanf("%d%f",&i, &x);
printf("\ninteger = %d, float = %f",i, x);
}
Output:
In the above example program, we used the scanf() function to read one integer
value and one float value from the keyboard. Here 'i' is an integer variable so we
have used format string %d, and 'x' is a float variable so we have used format string
%f.
The scanf() function returns an integer value equal to the total number of input
values read using scanf function.
#include <stdio.h>
void main(){
int i,a,b;
float x;
printf("\nEnter two integers and one float : ");
i = scanf("%d%d%f",&a, &b, &x);
printf("\nTotal inputs read : %d",i);
}
Output:
getchar() function
The getchar() function is used to read a character from the keyboard and return it
to the program. This function is used to read only single character. To read multiple
characters we need to write multiple times or use a looping statement. Consider the
following example program...
#include <stdio.h>
void main(){
char ch;
printf("\nEnter any character : ");
ch = getchar();
printf("\nYou have entered : %c",ch);
}
Output:
getch() function
The getch() function is similar to getchar function. The getch() function is used to
read a character from the keyboard and return it to the program. This function is
used to read only single character. To read multiple characters we need to write
multiple times or use a looping statement. Consider the following example
program...
#include <stdio.h>
void main(){
char ch;
printf("\nEnter any character : ");
ch = getch();
printf("\nYou have entered : %c",ch);
gets() function
The gets() function is used to read a line of string and stores it into character array.
The gets() function reads a line of string or sequence of characters till a newline
symbol enters. Consider the following example program...
#include <stdio.h>
void main(){
char name[30];
printf("\nEnter your favourite website: ");
gets(name);
printf("%s",name);
}
Output:
fscanf() function
The fscanf() function is used with the concept of files. The fscanf() function is used
to read data values from a file. When you want to use fscanf() function the file must
be opened in reading mode.
Operators in C
1. Arithematic Operators
2. Relational Operators
3. Logical Operators
4. Increment & Decrement Operators
5. Assignment Operators
6. Bitwise Operators
7. Conditional Operator
8. Special Operators
The arithematic operators are the symbols that are used to perform basic
mathematical operations like addition, subtraction, multiplication, division and
percentage modulo. The following table provides information about arithematic
operators...
⇒ The addition operator can be used with numerical data types and character data
type. When it is used with numerical values, it performs mathematical addition and
when it is used with character data type values, it performs concatination
(appending).
⇒ The remainder of division operator is used with integer data type only.
The relational operators are the symbols that are used to compare two values. That
means, the relational operators are used to check the relationship between two
values. Every relational operator has two results TRUE or FALSE. In simple words,
the relational operators are used to define conditions in a program. The following
table provides information about relational operators...
The logical operators are the symbols that are used to combine multiple conditions
into one condition. The following table provides information about logical
operators...
⇒ Logical AND - Returns TRUE only if all conditions are TRUE, if any of the conditions
is FALSE then complete condition becomes FALSE.
⇒ Logical OR - Returns FALSE only if all conditions are FALSE, if any of the conditions
is TRUE then complete condition becomes TRUE.
The increment and decrement operators are called as unary operators because, both
needs only one operand. The increment operators adds one to the existing value of
the operand and the decrement operator subtracts one from the existing value of
the operand. The following table provides information about increment and
decrement operators...
The increment and decrement operators are used infront of the operand (++a) or
after the operand (a++). If it is used infront of the operand, we call it as pre-
increment or pre-decrement and if it is used after the operand, we call it as post-
increment or post-decrement.
In case of pre-increment, the value of the variable is increased by one before the
expression evaluation. In case of pre-decrement, the value of the variable is
decreased by one before the expression evaluation. That means, when we use pre
increment or pre decrement, first the value of the variable is incremented or
decremented by one, then modified value is used in the expression evaluation.
#include <stdio.h>
void main(){
int i = 5,j;
j = ++i; // Pre-Increment
}
Output:
i = 6, j = 6
Post-Increment or Post-Decrement
In case of post-increment, the value of the variable is increased by one after the
expression evaluation. In case of post-decrement, the value of the variable is
decreased by one after the expression evaluation. That means, when we use post-
increment or post-decrement, first the expression is evaluated with existing value,
then the value of the variable is incremented or decremented by one.
Example
#include <stdio.h>
void main(){
int i = 5,j;
j = i++; // Post-Increment
}
Output:
i = 6, j = 5
The assignment operators are used to assign right hand side value (Rvalue) to the
left hand side variable (Lvalue). The assignment operator is used in different variants
along with arithematic operators. The following table describes all the assignment
operators in C programming language.
The bitwise operators are used to perform bit level operations in c programming
language. When we use the bitwise operators, the operations are performed based
on the binary values. The following table describes all the bitwise operators in C
programming language.
The conditional operator is also called as ternary operator because it requires three
operands. This operator is used for decision making. In this operator, first we verify
a condition, then we perform one operation out of the two operations based on the
condition result. If the condition is TRUE the first option is performed, if the
condition is FALSE the second option is performed. The conditional operator is used
with the following syntax...
Example
sizeof operator
This operator is used to find the size of the memory (in bytes) allocated for a
variable. This operator is used with the following syntax...
sizeof(variableName);
Example
This operator is used to separate variables while they are declaring, separate the
expresions in function calls etc..
What is an expression?
In the above definition, operator is a symbol which performs tasks like arithmetic
operations, logical operations and conditional operations etc.,
Operands are the values on which the operators perform the task. Here operand can
be a direct value or variable or address of memory location.
Expression Types in C
In C programming language, expressions are divided into THREE types. They are as
follows...
a) Infix Expression
b) Postfix Expression
c) Prefix Expression
Infix Expression
Example
Example
Prefix Expression
Example
() function call
[] array reference
1 Left to Right
-> structure member access
. structure member access
! negation
~ 1's complement
+ Unary plus
- Unary minus
++ increment operator
2 Right to Left
-- decrement operator
& address of operator
* pointer
sizeof returns size of a variable
(type) type conversion
* multiplication
3 / division Left to Right
% remainder
+ addition
4 Left to Right
- subtraction
= assignment
*= assign multiplication
/= assign division
%= assign remainder
+= assign additon
14 -= assign subtraction Right to Left
&= assign bitwise AND
^= assign bitwise XOR
|= assign bitwise OR
<<= assign left shift
>>= assign right shift
In the above table, the operator precedence decrese from top to bottom and
increase from bottom to top.
Expression Evaluation in C
10 + 4 * 3 / 2
In the above expression there are three operators +, * and /. Among these three
operators, both multiplication and division have same higher precedence and
addition has lower precedence. So, according to the operator precedence both
multiplication and division are evaluated first and then addition is evaluated. As
multiplication and division have same precedence they are evaluated based on the
associativity. Here, the associativity of multiplication and division is left to right.
So, multiplication is performed first, then division and finally addition. So, the above
expression is evaluated in the order of * / and +. It is evaluated as follows...
4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.
1. Type Conversion
2. Type Casting
Type Conversion
The type conversion is the process of converting a data value from one datatype to
another datatype automatically by the compiler. Sometimes type conversion is also
called as implicit type conversion. The implicit type conversion is automatically
performed by the compiler.
int i = 10 ;
float x = 15.5 ;
char ch = 'A' ;
Example Program
#include <stdio.h>
void main(){
int i = 95 ;
float x = 90.99 ;
char ch = 'A' ;
i = x ;
printf("i value is %d\n",i);
x = i ;
printf("x value is %f\n",x);
i = ch ;
printf("i value is %d\n",i);
}
Output:
i value is 90
x value is 90.000000
i value is 65
In the above program, we assign i = x, i.e., float variable value is assigned to integer
variable. Here, the compiler automatically converts the float value (90.99) into
integer value (90) by removing the decimal part of the float value (90.99) and then
it is assigned to variable i. Similarly when we assign x = i, the integer value (90) gets
converted to float value (90.000000) by adding zero as decimal part.
Type Casting
Type casting is also called as explicit type conversion. Compiler converts data from
one datatype to another datatype implicitly. When compiler converts implicitly,
there may be a data loss.In such case, we convert the data from one datatype to
another datatype using explicit type conversion. To perform this we use the unary
cast operator. To convert data from one type to another type we specify the target
(TargetDatatype) DataValue
Example
In the above example code, both totalMarks and maxMarks are integer data values.
When we perform totalMarks / maxMarks the result is a float value, but the
destination (average) datatype is float. So we use type casting to convert totalMarks
and maxMarks into float datatype.
Example Program
#include <stdio.h>
void main(){
int a, b, c ;
float avg ;
printf("Enter any three integer values : ") ;
scanf("%d%d%d", &a, &b, &c) ;
avg = (a + b + c) / 3 ;
printf("avg before casting = %f\n",avg);
avg = (float)(a + b + c) / 3 ;
printf("avg after casting = %f\n",avg);
}
Output:
if statement in C
In c programming language, the program execution flow is, line by line from top to
bottom. That means the c program is executed line by line from the main method.
But this type of execution flow may not be suitable for all the program solutions.
Sometimes, we make some decisions or we may skip the execution of one or more
lines of code. Consider a situation, where we write a program to check whether a
student has passed or failed in a particular subject. Here, we need to check whether
Decision making statements are the statements that are used to verify a given
condition and decides whether a block of statements gets executed or not based
on the condition result.
In c programming language, there are two decision making statements they are as
follows...
1. if statement
2. switch statement
if statement in c
1. Simple if statement
2. if - else statement
3. Nested if statement
4. if-else-if statement (if-else ladder)
Simple if statement
Simple if statement is used to verify the given condition and executes the block of
statements based on the condition result. The simple if statement evaluates
specified condition. If it is TRUE, it executes the next statement or block of
statements. If the condition is FALSE, it skips the execution of the next statement
or block of statements. The general syntax and execution flow of the simple if
statement is as follows...
#include <stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%5 == 0 )
printf("Given number is divisible by 5\n") ;
printf("statement does not belong to if!!!") ;
}
Output 1:
Output 2:
if - else statement
The if - else statement is used to verify the given condition and executes only one
out of the two blocks of statements based on the condition result. The if-else
statement evaluates the specified condition. If it is TRUE, it executes a block of
statements (True block). If the condition is FALSE, it executes another block of
statements (False block). The general syntax and execution flow of the if-else
statement is as follows...
#include <stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n%2 == 0 )
printf("Given number is EVEN\n") ;
else
printf("Given number is ODD\n") ;
}
Output 1:
Output 2:
Nested if statement
#include <stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Enter any integer number: ") ;
scanf("%d", &n) ;
if ( n < 100 )
{
printf("Given number is below 100\n") ;
if( n%2 == 0)
printf("And it is EVEN") ;
else
printf("And it is ODD") ;
}
else
printf("Given number is not below 100") ;
}
Output 1:
Output 2:
#include <stdio.h>
#include<conio.h>
void main(){
int a, b, c ;
clrscr() ;
else
printf("%d is the largest number", c) ;
}
Output 1:
• if(10) - is TRUE
• if(x) - is FALSE if x value is zero otherwise TRUE
• if(a+b) - is FALSE if a+b value is zero otherwise TRUE
• if(a = 99) - is TRUE because a value is non-zero
• if(10, 5, 0) - is FALSE because it considers last value
• if(0) - is FALSE
• if(a=10, b=15, c=0) - is FALSE because last value is zero
Switch statement in C
The switch statement has the following syntax and execution flow diagram...
The switch statement contains one or more number of cases and each case has a
value associated with it. At first switch statement compares the first case value with
the switchValue, if it gets matched the execution starts from the first case. If it
doesn't match the switch statement compares the second case value with the
switchValue and if it is matched the execution starts from the second case. This
process continues until it finds a match. If no case value matches with the
switchValue specified in the switch statement, then a special case called default is
executed.
When a case value matches with the switchValue, the execution starts from that
particular case. This execution flow continues with next case statements also. To
avoid this, we use "break" statement at the end of each case. That means
the break statement is used to terminate the switch statement. However it is
optional.
#include <stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
switch( n )
{
case 0: printf("ZERO") ;
break ;
case 1: printf("ONE") ;
break ;
case 2: printf("TWO") ;
break ;
case 3: printf("THREE") ;
break ;
case 4: printf("FOUR") ;
break ;
case 5: printf("FIVE") ;
break ;
case 6: printf("SIX") ;
break ;
case 7: printf("SEVEN") ;
break ;
case 8: printf("EIGHT") ;
break ;
case 9: printf("NINE") ;
break ;
default: printf("Not a Digit") ;
}
getch() ;
}
Output 1:
Output 2:
• Both switch and case are keywords so they must be used only in lower case
letters.
• The data type of case value and the value specified in switch statement
must be same.
• switch and case values must be either integer or character but not float or
string.
• A switch statement can contain any number of cases.
• The keyword case and its value must be superated with a white space.
• The case values need not be defined in sequence, they can be in any order.
• The default case is optional and it can be defined anywhere inside the
switch statement.
• The switch value might be a direct value, a variable or an expression.
while Statement in C
• while statement
• do-while statement
• for statement
At first, the given condition is evaluated. If the condition is TRUE, the single
statement or block of statements gets executed. Once the execution gets completed
the condition is evaluated again. If it is TRUE, again the same statements gets
executed. The same process is repeated until the condition is evaluated to FALSE.
Whenever the condition is evaluated to FALSE, the execution control moves out of
the while block.
#include <stdio.h>
#include<conio.h>
void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
while( n <= 10 )
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}
getch() ;
}
Output 1:
At first, the single statement or block of statements which are defined in do block
are executed. After execution of do block, the given condition gets evaluated. If the
condition is evaluated to TRUE, the single statement or block of statements of do
block are executed again. Once the execution gets completed again the condition is
evaluated. If it is TRUE, again the same statements are executed. The same process
is repeated until the condition is evaluated to FALSE. Whenever the condition is
evaluated to FALSE, the execution control moves out of the while block.
#include <stdio.h>
#include<conio.h>
void main(){
int n = 0;
clrscr() ;
printf("Even numbers upto 10\n");
do
{
if( n%2 == 0)
printf("%d\t", n) ;
n++ ;
}while( n <= 10 ) ;
getch() ;
}
Output 1:
• Both do and while are keywords so they must be used only in lower case
letters.
• If the condition contains variable, it must be assigned a value before it is
used.
• The value of the variable used in condition must be modified according to
the requirement inside the do block.
• In do-while statement the condition may be, a direct integer value, a
variable or a condition.
• A do-while statement can be an empty statement.
• In do-while, the block of statements are executed atleast once.
#include <stdio.h>
#include<conio.h>
void main(){
int n ;
clrscr() ;
printf("Even numbers upto 10\n");
getch() ;
}
Output 1:
Even numbers upto 10
0 2 4 6 8 10
In c, there are control statements which does not need any condition to control the
program execution flow. These control statements are called as unconditional
control statements. C programming language provides the following unconditional
control statements...
• break
• continue
• goto
break statement
In C, the break statement is used to perform the following two things...
When a break statement is encountered inside the switch case statement, the
execution control moves out of the switch statement directly. For example consider
the following program...
#include <stdio.h>
#include<conio.h>
void main(){
int number1, number2, result ;
char operator;
clrscr() ;
printf("Enter any two integer numbers: ") ;
scanf("%d%d", &number1, &number2) ;
printf("Please enter any arithmetic operator: ");
operator = getchar();
switch(operator)
{
case '+': result = number1 + number2 ;
printf("Addition = %d", result) ;
break;
case '-': result = number1 - number2 ;
printf("Subtraction = %d", result) ;
break;
case '*': result = number1 * number2 ;
printf("Multiplication = %d", result) ;
break;
case '/': result = number1 / number2 ;
printf("Division = %d", result) ;
break;
case '%': result = number1 % number2 ;
printf("Remainder = %d", result) ;
break;
default: printf("\nWrong selection!!!") ;
}
getch() ;
}
When the break statement is encountered inside the looping statement, the
execution control moves out of the looping statements. The break statement
execution is as shown in the following figure.
#include <stdio.h>
#include<conio.h>
void main(){
char ch ;
clrscr() ;
do
{
printf("Enter Y / N : ") ;
scanf("%c", &ch) ;
if(ch == 'Y')
{
printf("Okay!!! Repeat again !!!\n") ;
}
else
{
printf("Okay !!! Breaking the loop !!!") ;
break ;
}
} while( 1 ) ;
getch() ;
}
Output
continue statement
The continue statement is used to move the program execution control to the
beginning of looping statement. When continue statement is encountered in a
looping statement, the execution control skips the rest of the statements in the
looping block and directly jumps to the beginning of the loop.
The continue statement can be used with looping statements like while, do-while
and for.
When we use continue statement with while and do-while statements the
execution control directly jumps to the condition. When we use continue statement
with for statement the execution control directly jumps to the modification portion
(increment / decrement / any modification) of the for loop.
The continue statement execution is as shown in the following figure...
#include <stdio.h>
#include<conio.h>
void main(){
int number ;
clrscr() ;
while( 1 )
{
printf("Enter any integer number: ") ;
scanf("%d", &number) ;
if(number%2 == 0)
{
Output
goto statement
The goto statement is used to jump from one line to another line in the program.
Using goto statement we can jump from top to bottom or bottom to top. To jump
from one line to another line, the goto statement requires a lable. Lable is a name
given to the instruction or line in the program. When we use goto statement in the
program, the execution control directly jumps to the line with specified lable.
#include <stdio.h>
#include<conio.h>
void main(){
clrscr() ;
printf("We are at first printf statement!!!\n") ;
goto last ;
printf("We are at second printf statement!!!\n") ;
printf("We are at third printf statement!!!\n") ;
last: printf("We are at last printf statement!!!\n") ;
getch() ;
}
Output
When we use break, continue and goto statements, we must follow the following...
When we write a program to solve a larger problem, we divide that larger problem
into smaller sub problems and are solved individually to make the program easier.
In C, this concept is implemented using functions. Functions are used to divide a
larger program into smaller subprograms such that program becomes easy to
understand and easy to implement. A function is defined as follows...
Every C program must contain atleast one function called main(). However a program
may also contain other functions. Every function in C has the following...
Function Declaration
The function declaration tells the compiler about function name, datatype of the
return value and parameters. The function declaration is also called as function
prototype. The function declaration is performed before main function or inside
main function or inside any other function.
returnType functionName(parametersList);
In the above syntax, returnType specifies the datatype of the value which is sent as
a return value from the function definiton. The functionName is a user defined
name used to identify the function uniquely in the program. The parametersList is
the data values that are sent to the function definition.
Function Definition
The function definition provides the actual code of that function. The function
definition is also known as body of the function. The actual task of the function is
implemented in the function definition. That means the actual instructions to be
performed by a function are written in function definition. The actual instructions
of a function are written inside the braces "{ }". The function definition is performed
before main function or after main function.
Actual code...
Function Call
The function call tells the compiler when to execute the function definition. When
a function call is executed, the execution control jumps to the function definition
where the actual code gets executed and returns to the same functions call once
the execution completes. The function call is performed inside main function or
inside any other function or inside the function itself.
functionName(parameters);
Advantages of Functions
Types of Functions in C
The system defined functions are also called as Library Functions or Standard
Functions or Pre-Defined Functions. The implementation of system defined
functions is already defined by the system.
In C, all the system defined functions are defined inside the header
files like stdio.h, conio.h, math.h, string.h etc., For example, the
funtions printf() and scanf() are defined in the header file called stdio.h.
Whenever we use system defined functions in the program, we must include the
respective header file using #include statement. For example, if we use a system
defined function sqrt() in the program, we must include the header file
called math.h because the function sqrt() is defined in math.h.
Points to be Remembered
In C programming language, users can also create their own functions. The functions
that are created by users are called as user defined functions. The user defined
function is defined as follows...
The function whose definition is defined by the user is called as user defined
function.
That means the function that is implemented by user is called as user defined
function. For example, the function main is implemented by user so it is called as
user defined function.
In the concept of functions, the function call is known as "Calling Function" and the
function definition is known as "Called Function".
When we make a function call, the execution control jumps from calling function to
called function. After executing the called function, the execution control comes
back to calling function from called function. When the control jumps from calling
function to called function it may carry one or more data values called
"Paramenters" and while coming back it may carry a single value called "return
value". That means the data values transferred from calling function to called
function are called as Parameters and the data value transferred from called
funcion to calling function is called Return value.
Based on the data flow between the calling function and called function, the
functions are classified as follows...
In this type of functions there is no data transfer between calling function and called
function. Simply the execution control jumps from calling function to called function
and executes called function, and finally comes back to the calling function. For
example, consider the following program...
#include <stdio.h>
#include<conio.h>
void main()
{
void addition() ; // function declaration
clrscr() ;
getch() ;
}
void addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
printf("Sum = %d", num1+num2 ) ;
}
In this type of functions there is data transfer from calling function to called function
(parameters) but there is no data transfer from called function to calling function
(return value). The execution control jumps from calling function to called function
along with the parameters and executes called function, and finally comes back to
the calling function. For example, consider the following program...
#include <stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void addition(int, int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
addition(num1, num2) ; // function call
getch() ;
}
void addition(int a, int b) // function definition
{
printf("Sum = %d", a+b ) ;
}
In this type of functions there is no data transfer from calling function to called
function (parameters) but there is data transfer from called function to calling
function (return value). The execution control jumps from calling function to called
function and executes called function, and finally comes back to the calling function
along with a return value. For example, consider the following program...
#include <stdio.h>
#include<conio.h>
void main(){
int result ;
int addition() ; // function declaration
clrscr() ;
result = addition() ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition() // function definition
{
int num1, num2 ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
return (num1+num2) ;}
In this type of functions there is data transfer from calling function to called function
(parameters) and also from called function to calling function (return value). The
execution control jumps from calling function to called function along with
parameters and executes called function, and finally comes back to the calling
function along with a return value. For example, consider the following program...
#include <stdio.h>
#include<conio.h>
void main(){
int num1, num2, result ;
int addition(int, int) ; // function declaration
clrscr() ;
printf("Enter any two integer numbers : ") ;
scanf("%d%d", &num1, &num2);
result = addition(num1, num2) ; // function call
printf("Sum = %d", result) ;
getch() ;
}
int addition(int a, int b) // function definition
{
return (a+b) ;
}
Parameter Passing in C
When a function gets executed in the program, the execution control is transferred
from calling function to called function and executes function definition, and finally
comes back to the calling function. When the execution control is transferred from
calling function to called function it may carry one or more number of data values.
These data values are called as parameters.
Parameters are the data values that are passed from calling function to called
function.
a) Actual Parameters
b) Formal Parameters
The actual parameters are the parameters that are speficified in calling function.
The formal parameters are the parameters that are declared at called function.
When a function gets executed, the copy of actual parameter values are copied into
formal parameters.
In C Programming Language, there are two methods to pass parameters from calling
function to called function and they are as follows...
a) Call by Value
b) Call by Reference
Call by Value
In call by value parameter passing method, the copy of actual parameter values are
copied to formal parameters and these formal parameters are used in called
function. The changes made on the formal parameters does not effect the values
of actual parameters. That means, after the execution control comes back to the
#include <stdio.h>
#include<conio.h>
void main(){
int num1, num2 ;
void swap(int,int) ; // function declaration
clrscr() ;
num1 = 10 ;
num2 = 20 ;
In the above example program, the variables num1 and num2 are called actual
parameters and the variables a and b are called formal parameters. The value
of num1 is copied into a and the value of num2 is copied into b. The changes made
on variables a and b does not effect the values of num1 and num2.
Call by Reference
That means in call by reference parameter passing method, the address of the actual
parameters is passed to the called function and is recieved by the formal parameters
(pointers). Whenever we use these formal parameters in called function, they
directly access the memory locations of actual parameters. So the changes made
on the formal parameters effects the values of actual parameters. For example
consider the following program...
In the above example program, the addresses of variables num1 and num2 are
copied to pointer variables a and b. The changes made on the pointer
variables a and b in called function effects the values of actual
parameters num1 and num2 in calling function.
Standard Functions in C
In C when we use standard functions, we must include the respective header file
using #include statement. For example, the function printf() is defined in header
file stdio.h (Standard Input Output header file). When we use printf() in our
program, we must include stdio.hheader file using #include<stdio.h> statement.
circle(),
graphics.h Provides functions to draw graphics.
rectangle()
Scope of Variable in C
When we declare a variable in a program, it can not be accessed against the scope
rules. Variables can be accessed based on their scope. Scope of a variable decides
the portion of a program in which the variable can be accessed. Scope of the variable
is defined as follows...
Scope of a variable is the portion of the program where a defined variable can
be accessed.
The variable scope defines the visibility of variable in the program. Scope of a
variable depends on the position of variable declaration.
Declaring a variable before the function definition (outside the function definition)
is called global declaration. The variable declared using global declaration is
called global variable. Tha global variable can be accessed by all the functions that
are defined after the global declaration. That means the global variable can be
accessed any where in the program after its declaration. The global variable scope
is said to be file scope.
Output:
In the above example program, the variables num1 and num2 are declared as global
variables. They are declared before the main() function. So, they can be accessed
by function main() and other functions that are defined after main(). In the above
example, the functions main(), addition(), subtraction() and multiplication() can
access the variables num1 and num2.
Declaring a variable inside the function or block is called local declaration. The
variable declared using local declaration is called local variable. The local variable
can be accessed only by the function or block in which it is declared. That means
the local variable can be accessed only inside the function or block in which it is
declared.
#include <stdio.h>
#include<conio.h>
void main(){
void addition() ;
int num1, num2 ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("num1 = %d, num2 = %d", num1, num2) ;
addition() ;
getch() ;
}
void addition()
{
int sumResult ;
sumResult = num1 + num2 ;
printf("\naddition = %d", sumResult) ;
}
Output:
ERROR
The above example program shows an error because, the variables num1 and num2
are declared inside the function main(). So, they can be used only inside main()
function and not in addition() function.
#include <stdio.h>
#include<conio.h>
void main(){
void addition(int, int) ;
int num1, num2 ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;
In the above example program, the variables a and b are declared in function
definition as parameters. So, they can be used only inside the addition() function.
Recursive Functions in C
The recursive functions should be used very carefully because, when a function
called by itself it enters into infinite loop. And when a function enters into the
infinite loop, the function execution never gets completed. We should define the
condition to exit from the function call so that the recursive function gets
terminated.
When a function is called by itself, the first call remains under execution till the last
call gets invoked. Every time when a function call is invoked, the function returns
the execution control to the previous function call.
#include <stdio.h>
#include<conio.h>
int factorial( int ) ;
void main( )
{
int fact, n ;
printf(“Enter any positive integer: ”) ;
scanf(“%d”, &n) ;
fact = factorial( n ) ;
printf(“Factorial of %d is %d”, n, fact) ;
}
int factorial( int n )
{
int temp ;
Output:
Enter any positive integer: 3
Factorial of 3 is 6
In the above example program, the factorial() function call is initiated from main()
function with the value 3. Inside the factorial() function, the function calls
factorial(2), factorial(1) and factorial(0) are called recursively. In this program
execution process, the function call factorial(3) remains under execution till the
execution of function calls factorial(2), factorial(1) and factorial(0) gets completed.
Similarly the function call factorial(2) remains under execution till the execution of
function calls factorial(1) and factorial(0) gets completed. In the same way the
function call factorial(1) remains under execution till the execution of function call
factorial(0) gets completed. The complete execution process of the above program
is shown in the following figure...
In C programming language, type qualifiers are the keywords used to modify the
properties of variables. Using type qualifiers, we can change the properties of
variables. C programming language provides two type qualifiers and they are as
follows...
• const
• volatile
The const type qualifier is used to create constant variables. When a variable is
created with const keyword, the value of that variable can't be changed once it is
defined. That means once a value is assigned to a constant variable, that value is
fixed and cannot be changed throughout the program.
The keyword const is used at the time of variable declaration. We use the following
syntax to create constant variable using constkeyword.
When a variable is created with const keyword it becomes a constant variable. The
value of the constant variable can't be changed once it is defined. The following
program generates error message because we try to change the value of constant
variable x.
#include <stdio.h>
#include<conio.h>
void main(){
int i = 9 ;
const int x = 10 ;
clrscr() ;
i = 15 ;
x = 100 ; // creates an error
Output:
Compiler error, we cannot modify const variable
The volatile type qualifier is used to create variables whose values can't be changed
in the program explicitly but can be changed by any external device or hardware.
For example, the variable which is used to store system clock is defined as volatile
variable. The value of this variable is not changed explicitly in the program but is
changed by the clock routine of the operating system.
Preprocessor Commands in C
When we try to compile a program, preprocessor commands are executed first and
then the program gets compiled. Every preprocessor command begins with #
#define
#include <stdio.h>
#include<conio.h>
#define PI 3.14
void main(){
area = PI * SQR(radius) ;
printf("area = %ld",area);
getch();
}
Output:
#undef
#undef is used to destroy a macro that was already created using #define.
#ifdef
#ifdef returns TRUE if the macro is defined and returns FALSE if the macro is not
defined.
#ifndef
#ifndef returns TRUE if the specified macro is not defined otherwise returns FALSE.
#else
#elif
#endif
#include
#error
#pragma
In C programming language, there are some pre-defined macros and they are as
follows...
Arrays in C
When we work with large number of data values we need that many number of
different variables. As the number of variables increases, the complexity of the
program also increases and so the programmers get confused with the variable
names. There may be situations where we need to work with large number of similar
data values. To make this work more easy, C programming language provides a
concept called "Array".
An array is a special type of variable used to store multiple values of same data
type at a time.
Declaration of an Array
Syntax for creating an array without size and with initial values
In the above syntax, the datatype specifies the type of values we store in that array
and size specifies the maximum number of values that can be stored in that array.
Example
int a [3] ;
Here, the compiler allocates 6 bytes of continuous memory locations with single
name 'a' and tells the compiler to store three different integer values (each in 2
bytes of memory) into that 6 bytes of memory. For the above declaration the
memory is organized as follows...
In the above memory allocation, all the three memory locations has a common name
'a'. So the accession of individual memory location is not possible directly. Hence
compiler not only allocates the memory but also assigns a numerical reference value
arrayName [ indexValue ] ;
For the above example the individual elements can be denoted as follows...
For example, if we want to assign a value to the second memory location of above
array 'a', we use the following statement...
a [1] = 100 ;
Types of Arrays in C
In c programming language, single dimensional arrays are used to store list of values
of same datatype. In other words, single dimensional arrays are used to store a row
of values. In single dimensional array, data is stored in linear form. Single
dimensional arrays are also called as one-dimensional arrays, Linear Arrays or
simply 1-D Arrays.
We use the following general syntax for declaring a single dimensional array...
Example
We use the following general syntax for declaring and initializing a single
dimensional array with size and initial values.
Example
The array must be initialized if it is created without specifying any size. In this case,
the size of the array is decided based on the number of values initialized.
Example
In the above example declaration, size of the array 'marks' is 6 and the size of the
array 'studentName' is 16. This is because in case of character array, compiler
stores one exttra character called \0 (NULL) at the end.
arrayName [ indexValue ]
Example
marks [2] = 99 ;
In the above statement, the third element of 'marks' array is assinged with
value '99'.
We use the following general syntax for declaring a two dimensional array...
Example
We use the following general syntax for declaring and initializing a two dimensional
array with specific number of rows and coloumns with initial values.
Example
We use the following general syntax to access the individual elements of a two
dimensional array...
Example
matrix_A [0][1] = 10 ;
In the above statement, the element with row index 0 and column index 1
of matrix_A array is assinged with value 10.
Applications of Arrays in C
In c programming language, single dimensional arrays are used to store list of values
of same datatype. In other words, single dimensional arrays are used to store a row
of values. In single dimensional array data is stored in linear form.
We use two dimensional arrays to create matrix. We can perform various operations
on matrices using two dimensional arrays.
1. Linear Search
2. Binary Search
1. Insertion Sort
2. Bubble Sort
3. Selection Sort
4. Quick Sort
5. Merge Sort, etc.,
Pointers in C
In c programming language, we use normal variables to store user data values. When
we declare a variable, the compiler allocates required memory with specified name.
In c programming language, every variable has name, datatype, value, storage class,
and address. We use a special type of variable called pointer to store the address of
another variable with same datatype. Pointer is defined as follows...
Pointer is a special type of variable used to store the memory location address
of a variable.
datatype *pointerName ;
Example
int *ptr ;
In the above example declaration, the variable "ptr" is a pointer variable that can
be used to store any integer variable address.
int a, *ptr ;
ptr = &a ;
Pointer variables are used to store the address of other variables. We can use this
address to access the value of the variable through its pointer. We use the
symbol "*" infront of pointer variable name to access the value of variable to which
the pointer is pointing. We use the following general syntax...
*pointerVariableName
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 10, *ptr ;
clrscr();
Output
In the above example program, variable a is a normal variable and variable ptr is a
pointer variable. Address of variable a is stored in pointer variable ptr. Here ptr is
used to access the address of variable a and *ptr is used to access the value of
variable a.
Every pointer variable is used to store the address of another variable. In computer
memory address of any memory location is an unsigned integer value. In c
programming language, unsigned integer requires 2 bytes of memory. So,
irrespective of pointer datatype every pointer variable is allocated with 2 bytes of
memory.
Pointer variables are used to store address of variables. Address of any variable is
an unsigned integer value i.e., it is a numerical value. So we can perform arithematic
operations on pointer values. But when we perform arithematic operations on
pointer variable, result depends on the amount of memory required by the variable
to which the pointer is pointing.
1. Addition
2. Subtraction
3. Increment
4. Decrement
5. Comparison
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000
getch() ;
}
Example
#include<stdio.h>
#include<conio.h>
void main()
{
getch() ;
}
AddressAtPointer + NumberOfBytesRequiresByDatatype
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000
getch() ;
}
AddressAtPointer - NumberOfBytesRequiresByDatatype
Example
#include<stdio.h>
#include<conio.h>
void main()
{
int a, *intPtr ;
float b, *floatPtr ;
double c, *doublePtr ;
clrscr() ;
intPtr = &a ; // Asume address of a is 1000
floatPtr = &b ; // Asume address of b is 2000
doublePtr = &c ; // Asume address of c is 3000
getch() ;
}
Comparison of Pointers
Pointers to Pointers in C
datatype **pointerName ;
Example
int **ptr ;
Here, ptr is an integer pointer variable that stores the address of another integer
pointer variable but does not stores the normal integer variable address.
Points to be Remembered
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a ;
int *ptr1 ;
int **ptr2 ;
int ***ptr3 ;
clrscr() ;
ptr1 = &x ;
getch() ;
}
Pointers to void in C
void *pointerName ;
Example
void *ptr ;
Here, "ptr" is a void pointer variable which is used to store the address of any
datatype variable.
Points to be Remembered
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int a ;
float b ;
char c ;
void *ptr ;
clrscr() ;
ptr = &b ;
printf(“Address of float variable ‘b' = %u\n”, ptr) ;
ptr = &c ;
printf(“Address of character variable ‘c’ = %u\n”, ptr) ;
getch() ;
}
Pointers to Arrays in C
The array name itself acts as pointer to the first element of that array. Consider the
following example of array declaration...
int marks[6] ;
For the above declaration, the compiler allocates 12 bytes of memory and the
address of first memory location (i.e., marks[0]) is stored in a constant pointer
called marks. That means in the above example, marks is a pointer to marks[0].
Example Program
#include<stdio.h>
#include<conio.h>
void main()
{
int marks[6] = {89, 45, 58, 72, 90, 93} ;
int *ptr ;
clrscr() ;
ptr = marks ;
printf(“Base Address of 'marks' array = %u\n”, ptr) ;
getch() ;
}
Points to be Remembered
Here, the pointer variable "ptr" is assigned with address of "marks[2]" element.
In the above two statements, first printf statement prints the value 89 (i.e., value
of marks[0]) and the second printf statement prints the value 72 (i.e., value of
marks[3]).
marks++ ;
The above statement generates compilation error because the array name acts as
a constant pointer. So we can't change its value.
In the above example program, the array name marks can be used as follows...
In case of multi dimensional array also the array name acts as a constant pointer to
the base address of that array. For example, we declare an array as follows...
int marks[3][3] ;
1. Call by Value
2. Call By Reference
#include<stdio.h>
#include<conio.h>
void main()
{
int a = 10, b = 20 ;
clrscr() ;
swap(&a, &b) ;
getch() ;
}
void swap(int *x, int *y)
{
int temp ;
temp = *x ;
*x = *y ;
*y = temp ;
}