C Notes Full
C Notes Full
C language Tutorial with programming approach for beginners and professionals
helps you to understand the C language tutorial easily. Our C tutorial explains each
topic with programs.
The C Language is developed for creating system applications that direct interacts
to the hardware devices such as drivers, kernels etc.
C programming is considered as the base for other programming languages, that is
why it is known as mother language.
It can be defined by following ways:
1. Mother language
2. System programming language
3. Procedureoriented programming language
4. Structured programming language
5. Mid level programming language
1) C as a mother language
C language is considered as the mother language of all the modern languages
because most of the compilers, JVMs, Kernels etc. are written in C
language and most of languages follows c syntax e.g. C++, Java etc.
It provides the core concepts like array, functions, file handling etc. that is being
used in many languages like C++, java, C# etc.
2) C as a system programming language
A system programming language is used to create system softwares. C language is a
system programming language because it can be used to do low level
programming (e.g. driver and kernel). It is generally used to create hardware
devices, OS, drivers, kernels etc. For example, Linux kernel is written in C.
It can’t be used in internet programming like java, .net, php etc.
3) C as a procedural language
A procedure is known as function, method, routine, subroutine etc. A procedural
language specifies a series of steps or procedures for the program to solve the
problem.
A procedural language breaks the program into functions, data structures etc.
1
C is a procedural language. In C, variables and function prototypes must be
declared before being used.
4) C as a structured programming language
A structured programming language is a subset of procedural language. Structure
means to break a program into parts or blocks so that it may be easy to
understand.
In C language, we break the program into parts using functions. It makes the
program easier to understand and modify.
5) C as a midlevel programming language
C is considered as a middle level language because it supports the feature of
both lowlevel and high level language. C language program is converted into
assembly code, supports pointer arithmetic (low level), but it is machine independent
(feature of high level).
Low level language is specific to one machine i.e. machine dependent. It is
machine dependent, fast to run. But it is not easy to understand.
High Level language is not specific to one machine i.e. machine independent. It is
easy to understand.
History of C Language
History of C language is interesting to know. Here we are going to discuss brief
history of c language.
C programming language was developed in 1972 by Dennis Ritchie at bell
laboratories of AT&T (American Telephone & Telegraph), located in U.S.A.
Dennis Ritchie is known as the founder of c language.
It was developed to overcome the problems of previous languages such as B, BCPL
etc.
2
Initially, C language was developed to be used in UNIX operating system. It
inherits many features of previous languages such as B and BCPL.
Let's see the programming languages that were developed before C language.
1. Simple
2. Machine Independent or Portable
3. Midlevel programming language
4. structured programming language
5. Rich Library
6. Memory Management
7. Fast Speed
8. Pointers
9. Recursion
10. Extensible
1) Simple
C is a simple language in the sense that it provides structured approach (to
break the problem into parts), rich set of library functions, data types etc.
2) Machine Independent or Portable
Unlike assembly language, c programs can be executed in many machines with
little bit or no change. But it is not platformindependent.
3) Midlevel programming language
3
C is also used to do low level programming. It is used to develop system
applications such as kernel, driver etc. It also supports the feature of high level
language. That is why it is known as midlevel language.
4) Structured programming language
C is a structured programming language in the sense that we can break the
program into parts using functions. So, it is easy to understand and modify.
5) Rich Library
C provides a lot of inbuilt functions that makes 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.
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.
10) Extensible
C language is extensible because it can easily adopt new features.
Structure of a C Program:
Documentation Section /* Comment Line */
Linking Section //#include<stdio.h>
Global Variables Declaration //extern float b;
void main()
{
Declaration Part //int a;
Executable Part //printf(“%d\t%d\n”,a,b);
}
4
First C Program
Before starting the abcd of C language, you need to learn how to write, compile and
run the first c program. To write the first c program, open the C console and write the
following code:
1. #include <stdio.h>
2. #include <conio.h>
3. void main()
4. {
5. clrscr();
6. printf("Hello C Language");
7. getch();
8. }
#include <stdio.h> includes the standard input output library functions. The
printf() and scanf() function is defined in stdio.h
#include <conio.h> includes the console input output library functions. The
getch() and clrscr() functions is defined in conio.h file.
clear screen by clrscr() function
If you run the c program many times, it will append the output in previous output.
But, you can call clrscr() function to clear the screen. So it will be better for you to
call clrscr() function after the main method
void main() The main() function is the entry point of every program in c
language. The void keyword specifies that it returns no value.
printf() The printf() function is used to print data on the console.
scanf() The scanf() function is used to read data from the keyboard.
getch() The getch() function asks for a single character. Until you press any key,
it blocks the screen.
How to compile and run the c program
There are 2 ways to compile and run the c program, by menu and by shortcut.
By menu
Now click on the compile menu then compile sub menu to compile the c program.
Then click on the run menu then run sub menu to run the c program.
By shortcut
5
or, press alt+f9 and ctrl+f9 keys compile and run the program directly.
You can view the user screen any time by pressing the alt+f5 keys.
C Characters Set:
Whenever we write any C program then it consists of different statements. Each C Program is set of
statements and each statement is set of different c programming lexims. In C Programming each and every
character is considered as single lexim. i.e [Basic Lexical Element]. It consists following.
Uppercase Letters A to Z
Digits 0-9
Variables in C
A variable is a name of 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.
Let's see the syntax to declare a variable:
datatype variable_list;
Rules for Declaring a Variable Name:
1. Characters Allowed :
o Underscore(_)
o Capital Letters ( A – Z )
o Small Letters ( a – z )
o Digits ( 0 – 9 )
2. Blanks & Commas are not allowed
3. No Special Symbols other than underscore(_) are allowed
4. First Character should be alphabet or Underscore
5. Variable name Should not be Reserved Word (Keywords)
The example of declaring variable is given below:
6
1 int a;
2 float b;
3 char c;
Here, a, b, c are variables and int, float, char are data types.
We can also provide values while declaring the variables as given below:
1 int a=10,b=20;//declaring 2 variable of integer type
2 float f=20.8;
3 char c='A';
Keywords in C
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 C language.
A list of 32 keywords in c language is given below:
We will learn about all the C language keywords later.
Formatted Input and output functions in c: (printf, scanf in C)
The printf() and scanf() functions are used for input and output in C language. Both
functions are inbuilt library functions, defined in stdio.h (header file).
printf() function
The printf() function is used for output. It prints the given statement to the
console. whatever you are writing in between the double quotations in printf() function
as it is displayed on the console, except format strings and escape sequences (\n, \t,
etc.,).
The syntax of printf() function is given below:
printf("format string",argument_list);
The format string can be %d (integer), %c (character), %s (string), %f (float) etc.
scanf() function
7
The scanf() function is used for input. It reads the input data from the console.
You are not writing anything in between the double quotes in scanf() function except
format strings.
scanf("format string",argument_list);
Unformatted Input and Output Functions in ‘C’:
Unformatted I/O functions works only with character datatype (char).
The unformatted Input functions used in C are getch(), getche(), getchar(),
gets().
Syntax for getch () in C :
variable_name = getch();
getch() accepts only single character from keyboard. The character entered through
getch() is not displayed in the screen (monitor).
Syntax for getche() in C :
variable_name = getche();
Like getch(), getche() also accepts only single character, but unlike getch(), getche()
displays the entered character in the screen.
Syntax for getchar() in C :
variable_name = getchar();
getchar() accepts one character type data from the keyboard.
Syntax for gets() in C :
gets(variable_name);
gets() accepts any line of string including spaces from the standard Input device
(keyboard). gets() stops reading character from keyboard only when the enter key is
pressed.
The unformatted output statements in C are putch, putchar and puts.
Syntax for putch in C :
putch(variable_name);
putch displays any alphanumeric characters to the standard output device. It
displays only one character at a time.
Syntax for putchar in C :
putchar(variable_name);
putchar displays one character at a time to the Monitor.
Syntax for puts in C :
puts(variable_name);
puts displays a single / paragraph of text to the standard output device.
8
Data Types in C:
A data type specifies the type of data that a variable can store such as integer,
floating, character etc.
There are 4 types of data types in C language.
The basic data types are integerbased and floatingpoint based. C language
supports both signed and unsigned literals.
The memory size of basic data types may change according to 32 or 64 bit operating
system.
Let's see the basic data types. It size is given according to 32 bit OS.
Integer Types
Following table gives you details about standard integer types with its storage sizes and value ranges:
the sizeof operator. The expressions sizeof (type) yields the storage size of the object or
type in bytes. Following is an example to get the size of int type on any machine.
FloatingPoint Types
9
Following table gives you details about standard floating-point types with storage sizes and value ranges
and their precision:
#include <stdio.h>
#include <float.h>
int main()
{
printf("Storage size for float : %d \n", sizeof(float));
printf("Minimum float positive value: %E\n", FLT_MIN );
printf("Maximum float positive value: %E\n", FLT_MAX );
printf("Precision value: %d\n", FLT_DIG );
return 0;
}
When you compile and execute the above program, it produces the following result on Linux:
Storage size for float : 4
Minimum float positive value: 1.175494E38
Maximum float positive value: 3.402823E+38
Precision value: 6
Constants in C
In variables values can be changed to any number of times during execution,
whereas in constants value once assigned will remain static throughout the entire
period.
Rules for declaring a constant is exactly the same as variables, except constant
declaration is preceded by the keyword const.
const data_type constant_name = value;
Ex: const int a=10;
const float b=56.987;
10
const char c=’a’;
Program to print cube of given number
Let's see a simple example of c language that gets input from the user and prints
the cube of the given number.
/* Caluclate cube of a given number */
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. int number;
5. clrscr();
6. printf("enter a number:");
7. scanf("%d",&number);
8. printf("cube of number is:%d ",number*number*number);
9. getch();
10. }
Output
enter a number:5
cube of number is:125
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.
Program to print sum of 2 numbers
Let's see a simple example of input and output in C language that prints addition of
2 numbers.
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. int x=0,y=0,result=0;
5. clrscr();
6. printf("enter first number:");
11
7. scanf("%d",&x);
8. printf("enter second number:");
9. scanf("%d",&y);
10. result=x+y;
11. printf("sum of 2 numbers:%d ",result);
12. getch();
13. }
Output
enter first number:9
enter second number:9
sum of 2 numbers:18
C Operators
An operator is simply a symbol that is used to perform operations. There can be
many types of operations like arithmetic, logical, bitwise etc.
There are following types of operators to perform different types of operations in C
language.
Arithmetic Operators (+,,*,/,%)
Relational Operators (<,>,<=,>=,==,!=)
Shift Operators (<<,>>)
Logical Operators (&&,||,!)
Bitwise Operators (&,|,^)
Ternary or Conditional Operators (? : ((a<b)?1:0))
Assignment Operator (=)
Misc Operator (sizeof(),&a,*a)
Example Program for Arithmetic Operators:
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
c = a + b;
printf("Line 1 Value of c is %d\n", c );
c = a b;
printf("Line 2 Value of c is %d\n", c );
c = a * b;
12
printf("Line 3 Value of c is %d\n", c );
c = a / b;
printf("Line 4 Value of c is %d\n", c );
c = a % b;
printf("Line 5 Value of c is %d\n", c ); }
Example Program for Relational Operators:
#include <stdio.h>
main() {
int a = 21;
int b = 10;
int c ;
if( a == b ) {
printf("Line 1 a is equal to b\n" );
}
else {
printf("Line 1 a is not equal to b\n" );
}
if ( a < b ) {
printf("Line 2 a is less than b\n" );
}
else {
printf("Line 2 a is not less than b\n" );
}
if ( a > b ) {
printf("Line 3 a is greater than b\n" );
}
else {
printf("Line 3 a is not greater than b\n" );
}
/* Lets change value of a and b */
a = 5;
b = 20;
if ( a <= b ) {
printf("Line 4 a is either less than or equal to b\n" );
}
if ( b >= a ) {
printf("Line 5 b is either greater than or equal to b\n" );
}
}
13
Example Program for Logical Operators:
#include <stdio.h>
main() {
int a = 5;
int b = 20;
int c ;
if ( a && b ) {
printf("Line 1 Condition is true\n" );
}
if ( a || b ) {
printf("Line 2 Condition is true\n" );
}
/* lets change the value of a and b */
a = 0;
b = 10;
if ( a && b ) {
printf("Line 3 Condition is true\n" );
}
else {
printf("Line 3 Condition is not true\n" );
}
if ( !(a && b) ) {
printf("Line 4 Condition is true\n" );
}
}
Example Program for Bitwise and Shift Operators:
Bitwise operator works on bits and performs bit-by-bit operation. The truth tables for &, |, and ^
is as follows −
p q p&q p|q p^q ~p
0 0 0 0 0 1
0 1 0 1 1 1
1 1 1 1 0 0
1 0 0 1 1 0
#include <stdio.h>
main() {
unsigned int a = 60; /* 60 = 0011 1100 */
unsigned int b = 13; /* 13 = 0000 1101 */
int c = 0;
c = a & b; /* 12 = 0000 1100 */
printf("Line 1 Value of c is %d\n", c );
14
c = a | b; /* 61 = 0011 1101 */
printf("Line 2 Value of c is %d\n", c );
c = a ^ b; /* 49 = 0011 0001 */
printf("Line 3 Value of c is %d\n", c );
c = ~a; /*61 = 1100 0011 */
printf("Line 4 Value of c is %d\n", c );
c = a << 2; /* 240 = 1111 0000 */
printf("Line 5 Value of c is %d\n", c );
c = a >> 2; /* 15 = 0000 1111 */
printf("Line 6 Value of c is %d\n", c );
}
Example Program for Assignment Operator:
#include <stdio.h>
main() {
int a = 21;
int c ;
c = a;
printf("Line 1 = Operator Example, Value of c = %d\n", c );
c += a;
printf("Line 2 += Operator Example, Value of c = %d\n", c );
c = a;
printf("Line 3 = Operator Example, Value of c = %d\n", c );
c *= a;
printf("Line 4 *= Operator Example, Value of c = %d\n", c );
c /= a;
printf("Line 5 /= Operator Example, Value of c = %d\n", c );
c = 200;
c %= a;
printf("Line 6 %= Operator Example, Value of c = %d\n", c );
c <<= 2;
printf("Line 7 <<= Operator Example, Value of c = %d\n", c );
c >>= 2;
printf("Line 8 >>= Operator Example, Value of c = %d\n", c );
c &= 2;
printf("Line 9 &= Operator Example, Value of c = %d\n", c );
c ^= 2;
printf("Line 10 ^= Operator Example, Value of c = %d\n", c );
c |= 2;
printf("Line 11 |= Operator Example, Value of c = %d\n", c );
}
Example Program for Misc Operators and Ternary (Conditional) Operator:
#include <stdio.h>
15
main() {
int a = 4;
short b;
double c;
int* ptr;
/* example of sizeof operator */
printf("Line 1 Size of variable a = %d\n", sizeof(a) );
printf("Line 2 Size of variable b = %d\n", sizeof(b) );
printf("Line 3 Size of variable c= %d\n", sizeof(c) );
/* example of & and * operators */
ptr = &a; /* 'ptr' now contains the address of 'a'*/
printf("value of a is %d\n", a);
printf("*ptr is %d.\n", *ptr);
/* example of ternary operator */
a = 10;
b = (a == 1) ? 20: 30;
printf( "Value of b is %d\n", b );
b = (a == 10) ? 20: 30;
printf( "Value of b is %d\n", b );
}
Precedence of Operators in C:
The precedence of operator specifies that which operator will be evaluated first and
next. The associativity specifies the operators’ direction to be evaluated; it may be left
to right or right to left. Let's understand the precedence by the example given below:
int value=10+20*10;
The value variable will contain 210 because * (multiplicative operator) is evaluated
before + (additive operator).
The precedence and associativity of C operators is given below:
16
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
Comma , Left to right
Decision Making Statements
C if else Statement
The if statement in C language is used to perform operation on the basis of
condition. By using ifelse statement, you can perform operation either condition is true
or false.
There are many ways to use if statement in C language:
If statement
Ifelse statement
If elseif ladder
Nested if
If Statement
The single if statement in C language is used to execute the code if condition is true.
The syntax of if statement is given below:
1. if(expression){
2. //code to be executed
3. }
Flowchart of if statement in C
Let's see a simple example of c language if
statement.
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. int number=0;
5. clrscr();
6. printf("enter a number:");
7. scanf("%d",&number);
17
8. if(number%2==0){
9. printf("%d is even number",number);
10. }
11. getch();
12. }
Output
enter a number:4
4 is even number
enter a number:5
Ifelse Statement
The ifelse statement in C language is used to execute the code if condition is true or
false. The syntax and Flow Chart of ifelse statement is given below:
1. if(expression){
2. //code to be executed if condition is true
3. }
4. else{
//code to be executed if condition is false
5. }
Let's see the simple example of even and odd
number using ifelse statement in C language.
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. int number=0;
5. clrscr();
6. printf("enter a number:");
7. scanf("%d",&number);
8. if(number%2==0){
9. printf("%d is even number",number);
10. }
11. else{
18
12. printf("%d is odd number",number);
13. }
14. getch();
15. }
Output
enter a number:4 4 is even number enter a number:5 5 is odd number
If elseif ladder Statement
The if elseif statement is used to execute one code from multiple conditions. The
syntax of if elseif statement is given below:
1. if(condition1){
2. //code to be executed if condition1 is true
3. }else if(condition2){
4. //code to be executed if condition2 is true
5. }
6. else if(condition3){
7. //code to be executed if condition3 is true
8. }
9. ...
10. else{
11. //code to be executed if all the conditions are false
12. }
Flowchart of elseif ladder statement in C
19
The example of ifelseif statement in C language is given below.
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. int number=0;
5. clrscr();
6. printf("enter a number:");
7. scanf("%d",&number);
8. if(number==10){
9. printf("number is equals to 10");
10. }
11. else if(number==50){
12. printf("number is equal to 50");
13. }
14. else if(number==100){
15. printf("number is equal to 100");
16. }
17. else{
18. printf("number is not equal to 10, 50 or 100");
19. }
20
20. getch();
21. }
Output
enter a number:4 number is not equal to 10, 50 or 100
enter a number:50 number is equal to 50
C Switch Statement
The switch statement in C language is used to execute the code from multiple
conditions. It is like if elseif ladder statement.
The syntax of switch statement in c language is given below:
1. switch(expression){
2. case value1:
3. //code to be executed;
4. break; //optional
5. case value2:
6. //code to be executed;
7. break; //optional
8. ......
9.
10. default:
11. code to be executed if all cases are not matched;
12. }
Rules for switch statement in C language
1) The switch expression must be of integer or character type.
2) The case value must be integer or character constant.
3) The case value can be used only inside the switch statement.
4) The break statement in switch case is not must. It is optional. If there is no break
statement found in switch case, all the cases will be executed after matching the case
value. It is known as fall through state of C switch statement.
Let's try to understand it by the examples. We are assuming there are following
variables.
1 int x,y,z;
2 char a,b;
21
3 float f;
Let's see a simple example of c language switch statement.
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. int number=0;
5. clrscr();
6. printf("enter a number:");
7. scanf("%d",&number);
8. switch(number){
9. case 10:
10. printf("number is equals to 10");
11. break;
22
12. case 50:
13. printf("number is equal to 50");
14. break;
15. case 100:
16. printf("number is equal to 100");
17. break;
18. default:
19. printf("number is not equal to 10, 50 or 100");
20. }
21. getch();
22. }
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
C Switch statement is fallthrough
In C language, switch statement is fall through, it means if you don't use break
statement in switch case, all the case after matching case will be executed.
Let's try to understand the fall through state of switch statement by the example
given below.
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. int number=0;
5. clrscr();
6. printf("enter a number:");
7. scanf("%d",&number);
8. switch(number){
9. case 10:
10. printf("number is equals to 10\n");
11. case 50:
12. printf("number is equal to 50\n");
23
13. case 100:
14. printf("number is equal to 100\n");
15. default:
16. printf("number is not equal to 10, 50 or 100");
17. }
18. getch();
19. }
Output
enter a number:10
number is equals to 10
number is equals to 50
number is equals to 100
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100
C Loops
The loops in C language are used to execute a block of code or a part of the program
several times.
In other words, it iterates a code or group of code many times.
Why use loops in C language?
Suppose that you have to print table of 2, then you need to write 10 lines of code.
By using the loop statement, you can do it by 2 or 3 lines of code only.
Advantage of loops in C
1) It saves code.
2) It helps to traverse the elements of array (which is covered in next pages).
Types of C Loops
There are three types of loops in C language that is given below:
1. do while
2. while
3. for
do while loop in C
24
To execute a part of program or code several times, we can use dowhile loop of C
language. The code given between the do and while block will be executed until
condition is true.
In do while loop, statement is given before the condition, so statement or code will be
executed at least one time. In other words, we can say it is executed 1 or more times.
It is better if you have to execute the code at least once.
do while loop syntax
The syntax of C language dowhile loop is given below:
1 do{
2 //code to be executed
3 }
4 while(condition);
Flowchart of do while loop
do while example
There is given the simple program
of c language do while loop where we
are printing the table of
1. #include <stdio.h>
2. #include <conio.h>
3. void main(){
4. int i=1;
5. clrscr();
6. do{
7. printf("%d \t",i);
8. i++;
9. }while(i<=10);
10. getch();
11. }
Output
1 2 3 4 5 6 7 8 9 10
Program to print table for the given number using do while loop
1. #include <stdio.h>
2. #include <conio.h>
25
3. void main(){
4. int i=1,number=0;
5. clrscr();
6. printf("Enter a number: ");
7. scanf("%d",&number);
8. do{
9. printf("%d \t",(number*i));
10. i++;
11. }while(i<=10);
12. getch();
13. }
Output
Enter a number: 5
5 10 15 20 25 30 35 40 45 50
Enter a number: 10
10 20 30 40 50 60 70 80 90 100
Infinitive do while loop
If you pass 1 as a expression in do while loop, it will run infinite number of times.
1. do{
2. //statement
3. }while(1);
while loop in C
The while loop in C language is used to iterate the part of program or statements
many times. In while loop, condition is given before the statement. So it is different
from the do while loop. It can execute the statements 0 or more times.
When use while loop in C
The C language while loop should be used if number of iteration is uncertain or
unknown.
Syntax of while loop in C language
The syntax of while loop in c language is given below:
while(condition){
//code to be executed
26
}
Flowchart of while loop in C
Example of while loop in C language
Let's see the simple program of while loop that prints
table of 1.
1. #include <stdio.h>
2. #include <conio.h>
3. void main(){
4. int i=1;
5. clrscr();
6. while(i<=10){
7. printf("%d \t",i);
8. i++;
9. }
10. getch(); }
Output
1 2 3 4 5 6 7 8 9 10
Program to print table for the given number using while loop in C
1. #include <stdio.h>
2. #include <conio.h>
3. void main(){
4. int i=1,number=0;
5. clrscr();
6. printf("Enter a number: ");
7. scanf("%d",&number);
8. while(i<=10){
9. printf("%d \t",(number*i));
10. i++;
11. }
12. getch();
13. }
Output
Enter a number: 50
50 100 150 200 250 300 350 400 450 500
27
Enter a number: 100
100 200 300 400 500 600 700 800 900 1000
Infinitive while loop in C
If you pass 1 as a expression in while loop, it will run infinite number of times.
1. while(1){
2. //statement
3. }
for loop in C
The for loop in C language is also used to iterate the statement or a part of the
program several times, like while and dowhile loop.
But, we can initialize and increment or decrement the variable also at the time of
checking the condition in for loop.
Unlike do while loop, the condition or expression in for loop is given before the
statement, so it may execute the statement 0 or more times.
When use for loop in C
For loop is better, if number of iterations is known by the programmer.
Syntax of for loop in C
The syntax of for loop in c language is given below:
1. for(initialization;condition;incr/decr){
2. //code to be executed
3. }
Flowchart of for loop in C
Example of for loop in C language
Let's see the simple program of for
loop that prints table of 1.
1. #include <stdio.h>
2. #include <conio.h>
3. void main(){
4. int i=0;
5. clrscr();
6. for(i=1;i<=10;i++){
7. printf("%d \t",i);
8. }
28
9. getch();
10. }
Output
1 2 3 4 5 6 7 8 9 10
C Program: Print table for the given number using C for loop
1. #include <stdio.h>
2. #include <conio.h>
3. void main(){
4. int i=1,number=0;
5. clrscr();
6. printf("Enter a number: ");
7. scanf("%d",&number);
8. for(i=1;i<=10;i++){
9. printf("%d \t",(number*i));
10. }
11. getch();
12. }
Output
Enter a number: 2
2 4 6 8 10 12 14 16 18 20
Enter a number: 1000
1000 2000 3000 4000 5000 6000 7000 8000 9000 10000
Infinitive for loop in C
If you don't initialize any variable, check condition and increment or decrement
variable in for loop, it is known as infinitive for loop.
In other words, if you place 2 semicolons in for loop, it is known as infinitive for
loop.
1. for(;;){
2. printf("infinitive for loop example by CRR");
3. }
If you run this program, you will see above statement infinite times.
C break statement
The break statement in C language is used to break the execution of loop (while,
do while and for) and switch case.
29
In case of inner loops, it terminates the control of inner loop only.
There can be two usage of C break keyword:
1. With switch case
2. With loop
Syntax:
1. jumpstatement;
2. break;
The jump statement in c break syntax can be while loop, do while loop, for loop or
switch case.
Flowchart of break in c
4. int i=1;//initializing a local variable
5. clrscr();
6. //starting a loop from 1 to 10
7. for(i=1;i<=10;i++){
8. printf("%d \t",i);
9. if(i==5){//if value of i is equal to 5, it will break the loop
10. break;
11. }
12. }//end of for loop
13. getch();
14. }
30
Output
1 2 3 4 5
As you can see on console output, loop from 1 to 10 is not printed after i==5.
C break statement with inner loop
In such case, it breaks only inner loop, but not outer loop.
1. #include <stdio.h>
2. #include <conio.h>
3. void main(){
4. int i=1,j=1;//initializing a local variable
5. clrscr();
6. for(i=1;i<=3;i++){
7. for(j=1;j<=3;j++){
8. printf("%d &d\n",i,j);
9. if(i==2 && j==2){
10. break;//will break loop of j only
11. }
12. }
13. }//end of for loop
14. getch();
15. }
Output
1 1
1 2
1 3
2 1
2 2
3 1
3 2
3 3
As you can see the output on console, 2 3 is not printed because there is break
statement after printing i==2 and j==2. But 3 1, 3 2 and 3 3 is printed because break
statement works for inner loop only.
C continue statement
31
The continue statement in C language is used to continue the execution of loop
(while, do while and for). It is used with if condition within the loop.
In case of inner loops, it continues the control of inner loop only.
Syntax:
1. jumpstatement;
2. continue;
The jump statement can be while, do while and for loop.
Example of continue statement in c
1. #include <stdio.h>
2. #include <conio.h>
3. void main(){
4. int i=1;//initializing a local variable
5. clrscr();
6. //starting a loop from 1 to 10
7. for(i=1;i<=10;i++){
8. if(i==5){//if value of i is equal to 5, it will continue the loop
9. continue;
10. }
11. printf("%d \t",i);
12. }//end of for loop
13. getch();
14. }
Output
1 2 3 4 6 7 8 9 10
As you can see, 5 is not printed on the console because loop is continued at i==5.
C continue statement with inner loop
In such case, C continue statement continues only inner loop, but not outer loop.
1. #include <stdio.h>
2. #include <conio.h>
3. void main(){
4. int i=1,j=1;//initializing a local variable
5. clrscr();
6. for(i=1;i<=3;i++){
32
7. for(j=1;j<=3;j++){
8. if(i==2 && j==2){
9. continue;//will continue loop of j only
10. }
11. printf("%d &d\n",i,j);
12. }
13. }//end of for loop
14. getch();
15. }
Output
1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3
As you can see, 2 2 is not printed on the console because inner loop is continued at
i==2 and j==2.
goto Statement:
from the goto to a labeled statement in the same function.
NOTE: Use of goto statement is highly discouraged in any programming language
because it makes difficult to trace the control flow of a program, making the program
hard to understand and hard to modify. Any program that uses a goto can be rewritten
so that it doesn't need the goto.
Syntax: The syntax for a goto statement in C is as follows:
goto label;
..
.
label: statement;
33
Here label can be any plain text except C keyword and it can be set anywhere in
the C program above or below to goto statement.
Flow Diagram:
Example:
#include <stdio.h>
int main ()
{
/* local variable definition */
int a = 10;
/* do loop execution */
LOOP:do
{
if( a == 15)
{
/* skip the iteration */
a = a + 1;
goto LOOP;
}
printf("value of a: %d\n", a);
a++;
}while( a < 20 );
return 0;
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
34
value of a: 18
value of a: 19
Arrays
Array in C language is a collection or group of elements (data). All the elements of c
array are homogeneous (similar). It has contiguous memory location.
C array is beneficial if you have to store similar elements. Suppose you have to store
marks of 50 students, one way to do this is allotting 50 variables. So it will be typical
and hard to manage. For example we cannot access the value of these variables with
only 1 or 2 lines of code.
Another way to do this is array. By using array, we can access the elements easily.
Only few lines of code is required to access the elements of array.
Advantage of C Array
1) Code Optimization: Less code to the access the data.
2) Easy to traverse data: By using the for loop, we can retrieve the elements of an
array easily.
3) Easy to sort data: To sort the elements of array, we need a few lines of code only.
4) Random Access: We can access any element randomly using the array.
Disadvantage of C Array
1) Fixed Size: Whatever size, we define at the time of declaration of array, we can't
exceed the limit. So, it doesn't grow the size dynamically like Linked List which we will
learn later.
Declaration of C Array
We can declare an array in the c language in the following way.
data_type array_name[array_size];
Now, let us see the example to declare array.
int marks[5];
Here, int is the data_type, marks is the array_name and 5 is the array_size.
Initialization of C Array
A simple way to initialize array is by index. Notice that array index starts from
0 and ends with [SIZE 1].
marks[0]=80;//initialization of array
35
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
C array example
1. #include <stdio.h>
2. #include <conio.h>
3. void main(){
4. int i=0;
5. int marks[5];//declaration of array
6. clrscr();
7. marks[0]=80;//initialization of array
8. marks[1]=60;
9. marks[2]=70;
10. marks[3]=85;
11. marks[4]=75;
12. //traversal of array
13. for(i=0;i<5;i++){
14. printf("%d \t",marks[i]);
15. }//end of for loop
16. getch();
17. }
Output
80 60 70 85 75
C Array: Declaration with Initialization
We can initialize the c array at the time of declaration. Let's see the code.
int marks[5]={20,30,40,50,60};
In such case, there is no requirement to define size. So it can also be written as
the following code.
36
int marks[]={20,30,40,50,60};
Let's see the full program to declare and initialize the array in C.
#include <stdio.h>
#include <conio.h>
void main(){
int i=0;
int marks[5]={20,30,40,50,60};//declaration and initialization of array
clrscr();
//traversal of array
for(i=0;i<5;i++){
printf("%d \t",marks[i]);
}
getch();
}
Output
20 30 40 50 60
Two Dimensional Array in C
The two dimensional array in C language is represented in the form of rows and
columns, also known as matrix. It is also known as array of arrays or list of arrays.
The two dimensional, three dimensional or other dimensional arrays are also known
as multidimensional arrays.
Declaration of two dimensional Array in C
We can declare an array in the c language in the following way.
data_type array_name[size1][size2];
A simple example to declare two dimensional array is given below.
int twodimen[4][3];
Here, 4 is the row number and 3 is the column number.
Initialization of 2D Array in C
A way to initialize the two dimensional array at the time of declaration is given
below.
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
Two dimensional array example in C
37
#include <stdio.h>
#include <conio.h>
void main(){
int i=0,j=0;
int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
clrscr();
//traversing 2D array
for(i=0;i<4;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \t",i,j,arr[i][j]);
}//end of j
}//end of i
getch();
}
Output
arr[0][0] = 1 arr[0][1] = 2 arr[0][2] = 3 arr[1][0] = 2 arr[1][1] = 3 arr[1][2] = 4
arr[2][0] = 3 arr[2][1] = 4 arr[2][2] = 5 arr[3][0] = 4 arr[3][1] = 5 arr[3][2] = 6
38
Storage Classes
C Programming Storage Class
Every variable in C programming has two properties: type and storage class.
Type refers to the data type of variable whether it is character or integer or
floatingpoint value etc. And storage class determines how long it stays in
existence.
There are 4 types of storage class:
1. automatic
2. external
3. static
4. register
Automatic storage class
Keyword for automatic variable is auto
Variables declared inside the function body are automatic by default. These
variable are also known as local variables as they are local to the function and
doesn't have meaning outside that function
Since, variable inside a function is automatic by default, keyword auto are
rarely used.
External storage class
39
External variable can be accessed by any function. They are also known as
global variables. Variables declared outside every function are external
variables.
In case of large program, containing more than one file, if the global variable
is declared in file 1 and that variable is used in file 2 then, compiler will show
error. To solve this problem, keyword extern is used in file 2 to indicate that,
the variable specified is global variable and declared in another file.
Example to demonstrate working of external variable
#include <stdio.h>
void Check();
int a=5;
/* a is global variable because it is outside every function */
int main(){
a+=4;
check();
return 0;
}
void check(){
++a;
/* Variable a is not declared in this function but, works in any
function as they are global variable */
printf("a=%d\n",a);
}
Output
a=10
Register Storage Class
Keyword for declare register variable register
Example of register variable
register int a;
Register variables are similar to automatic variable and exists inside that
particular function only.
40
If the compiler encounters register variable, it tries to store variable in
microprocessor's register rather than memory. Values stored in registers are
much faster than that of memory.
In case of larger program, variables that are used in loops and function
parameters are declared register variables.
Since, there are limited number of register in processor and if it couldn't
store the variable in register, it will automatically store it in memory.
static storage Class
The value of static variable persists until the end of the program. A variable
can be declared static using keyword: static. For example:
static int i;
Here, i is a static variable.
Example to demonstrate the static variable
#include <stdio.h>
void Check();
int main(){
Check();
Check();
Check();
}
void Check(){
static int c=0;
printf("%d\t",c);
c+=5;
}
Output
0 5 10
During first function call, it will display 0. Then, during second function call,
variable c will not be initialized to 0 again, as it is static variable. So, 5 is
displayed in second function call and 10 in third call.
If variable c had been automatic variable, the output would have been:
0 0 0
41
Strings
In C programming, array of character are called strings. A string is
terminated by null character \0. For example:
"c string tutorial"
Here, "c string tutorial" is a string. When, compiler encounters strings, it
appends null character at the end of string.
42
Declaration of strings
Strings are declared in C in similar manner as arrays. Only difference is
that, strings are of char type.
char s[5];
Strings can also be declared using pointer.
char *p
Initialization of strings
In C, string can be initialized in different number of ways.
char c[]="abcd";
OR,
char c[5]="abcd";
OR,
char c[]={'a','b','c','d','\0'};
OR;
char c[5]={'a','b','c','d','\0'};
String can also be initialized using pointers
char *c="abcd";
Reading Strings from user.
Reading words from user.
char c[20];
scanf("%s",c);
String variable c can only take a word. It is beacause when white space is
encountered, the scanf()function terminates.
Write a C program to illustrate how to read string from terminal.
#include <stdio.h>
int main(){
char name[20];
printf("Enter name: ");
43
scanf("%s",name);
printf("Your name is %s.",name);
return 0;
}
Output
Enter name: Dennis Ritchie
Your name is Dennis.
Here, program will ignore Ritchie because, scanf() function takes only string
before the white space.
Reading a line of text
C program to read line of text manually.
#include <stdio.h>
int main(){
char name[30],ch;
int i=0;
printf("Enter name: ");
while(ch!='\n') // terminates if user hit enter
{
ch=getchar();
name[i]=ch;
i++;
}
name[i]='\0'; // inserting null character at end
printf("Name: %s",name);
return 0;
}
This process to take string is tedious. There are predefined
functions gets() and puts in C language to read and display string respectively.
int main(){
char name[30];
printf("Enter name: ");
gets(name); //Function to read string from user.
printf("Name: ");
44
puts(name); //Function to display string.
return 0;
}
Both, the above program has same output below:
Output
Enter name: Tom Hanks
Name: Tom Hanks
String handling functions
You can perform different type of string operations manually like: finding
length of string, concatenating (joining) two strings etc. But, for programmers
ease, many library functions are defined under header file <string.h> to handle
these commonly used in C programming. You will learn more about string
hadling functions.
String Manipulations in C Programming Using Library Functions
Strings are often needed to be manipulated by programmer according to the
need of a problem. All string manipulation can be done manually by the
programmer but, this makes programming complex and large. To solve this, the
C supports a large number of string handling functions.
There are numerous functions defined in "string.h" header file. Few
commonly used string handling functions are discussed below:
Functions
Byte string Description
manipulation
strncpy Writes exactly n bytes copying from source or adding nulls
strcat Appends one string to another
strncat Appends no more than n bytes from one string to another
45
strxfrm Transforms a string according to the current locale
strlen Returns the length of the string
strcmp Compares two strings (threeway comparison)
strncmp Compares a specific number of bytes in two strings
strchr Finds the first occurrence of a byte in a string
strrchr Finds the last occurrence of a byte in a string
String
examination
strspn Finds in a string the first occurrence of a byte not in a set
strcspn Finds in a string the last occurrence of a byte not in a set
strpbrk Finds in a string the first occurrence of a byte in a set
strstr Finds the first occurrence of a substring in a string
strtok Splits a string into tokens
/* String handling functions*/
#include<stdio.h>
#include<conio.h>
void main()
{
char str1[20],str2[20],str3[30];
int length,n,d;
clrscr();
printf("Enter the string\n");
scanf("%s",&str1); /*gets(str1); */
46
printf("Given string str1 is %s\n",str1);
length=strlen(str1);
printf("%s length is %d\n",str1,length);
strcpy(str2,str1);
printf("Copied string str2 is %s\n",str2);
printf("Enter the number\n");
scanf("%d",&n);
strncpy(str3,str2,n);
printf("%d characters from %s is copied into %s\n",n,str2,str3);
printf("Riverse of the given string is %s\n",strrev(str1));
printf("Str 1 is %s\n",str1);
/*concatination*/
printf("Concatination of %s and %s is ",str1,str2);
printf("%s\n",strcat(str1,str2));
printf("Str1 is %s\n",str1);
d=strcmp(str2,str3);
if(d==0)
printf("%s and %s are same\n",str3,str2);
else
printf("%s and %s are not equal\n",str3,str2);
d=strncmp(str2,str3,n);
if(d==0)
printf("%s and %s are equal upto %d characters\n",str2,str3,n);
else
printf("%s and %s are not equal upto %d characters\n",str2,str3,n);
printf("%s in uppercase ",str1);
printf("%s\n",strupr(str1));
printf("%s in lowercase ",str1);
printf(" %s\n",strlwr(str1));
printf("%s is replaced with * is ",str1);
printf("%s\n",strset(str1,'*'));
printf("%s is replaced with + upto %d characters is ",str2,n);
printf("%s \n",strnset(str2,'+',n));
47
getch();
}
Pointers
48
Pointers in C are easy and fun to learn. Some C programming tasks are performed
more easily with pointers, and other tasks, such as dynamic memory allocation, cannot
be performed without using pointers. So it becomes necessary to learn pointers to
become a perfect C programmer. Let's start learning them in simple and easy steps.
As you know, every variable is a memory location and every memory location has
its address defined which can be accessed using ampersand (&) operator, which
denotes an address in memory. Consider the following example, which prints the
address of the variables defined −
#include <stdio.h>
int main () {
int var1;
char var2[10];
printf("Address of var1 variable: %x\n", &var1 );
printf("Address of var2 variable: %x\n", &var2 );
return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var1 variable: bff5a400
Address of var2 variable: bff5a3f6
What are Pointers?
A pointer is a variable whose value is the address of another variable, i.e., direct
address of the memory location. Like any variable or constant, you must declare a
pointer before using it to store any variable address. The general form of a pointer
variable declaration is −
type *varname;
Here, type is the pointer's base type; it must be a valid C data type and var
name is the name of the pointer variable. The asterisk * used to declare a pointer is
the same asterisk used for multiplication. However, in this statement the asterisk is
being used to designate a variable as a pointer. Take a look at some of the valid
pointer declarations −
int *ip; /* pointer to an integer */
49
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */
The actual data type of the value of all pointers, whether integer, float, character,
or otherwise, is the same, a long hexadecimal number that represents a memory
address. The only difference between pointers of different data types is the data type
of the variable or constant that the pointer points to.
How to Use Pointers?
There are a few important operations, which we will do with the help of pointers
very frequently. (a) We define a pointer variable,(b) assign the address of a variable to
a pointer and (c) finally access the value at the address available in the pointer
variable. This is done by using unary operator * that returns the value of the variable
located at the address specified by its operand. The following example makes use of
these operations −
#include <stdio.h>
int main () {
int var = 20; /* actual variable declaration */
int *ip; /* pointer variable declaration */
ip = &var; /* store address of var in pointer variable*/
printf("Address of var variable: %x\n", &var );
/* address stored in pointer variable */
printf("Address stored in ip variable: %x\n", ip );
/* access the value using the pointer */
printf("Value of *ip variable: %d\n", *ip );
printf(“Value of var variable:%d\n Value of var variable:%d\n”,var,*(&var));
return 0;
}
When the above code is compiled and executed, it produces the following result −
Address of var variable: bffd8b3c
Address stored in ip variable: bffd8b3c
Value of *ip variable: 20 Value of var variable: 20 Value of var variable: 20
50
NULL Pointers
It is always a good practice to assign a NULL value to a pointer variable in case
you do not have an exact address to be assigned. This is done at the time of variable
declaration. A pointer that is assigned NULL is called a null pointer.
The NULL pointer is a constant with a value of zero defined in several standard
libraries. Consider the following program −
#include <stdio.h>
int main () {
int *ptr = NULL;
printf("The value of ptr is : %x\n", ptr );
return 0;
}
When the above code is compiled and executed, it produces the following result −
The value of ptr is 0
In most of the operating systems, programs are not permitted to access memory at
address 0 because that memory is reserved by the operating system. However, the
memory address 0 has special significance; it signals that the pointer is not intended
to point to an accessible memory location. But by convention, if a pointer contains the
null (zero) value, it is assumed to point to nothing.
To check for a null pointer, you can use an 'if' statement as follows −
if(ptr) /* succeeds if p is not null */
if(!ptr) /* succeeds if p is null */
Pointers in Detail
Pointers have many but easy concepts and they are very important to C
programming. The following important pointer concepts should be clear to any C
programmer.
Arithmetic Operations with Pointers:
Arithmetic operations on pointer variables are also possible. Increase, decrease,
prefix, &postfix operations can be performed with the help of pointers.
Unary Operators: ++ (increment) and –(decrement)
Binary Operators: + (Addition) and –(Subtraction)
51
The size of pointer variable depends on the data type of variable pointed to by
the pointer.
Example:
Array name by itself is an address or pointer. It points to the address of the first
element (0th element of an array). The elements of the array together with their
addresses can be displayed by using array name itself. Array elements are always
stored in contiguous memory locations. The following program illustrates this.
void main()
{
int i,n,a[10],*pm;
clrscr();
printf(“Enter the size of an array\n”);
scanf(“%d”,&n);
printf(“Enter %d elements \n”);
for(i=0;i<n;i++)
scanf(“%d”,a+i);
pm=a //is equal to &a[0]
printf(“Array elements and their addresses using pointers is \n”);
for(i=0;i<n;i++)
{
printf(“address of a[%d]=%d\t value of a[%d]=%d\n”,i,pm,i,*pm);
printf(“address of a[%d]=%d\t value of a[%d]=%d\n”,i,&a[i],i,a[i]);
printf(“address of a[%d]=%d\t value of a[%d]=%d\n”,i,&i[a],i,i[a]);
printf(“address of a[%d]=%d\t value of a[%d]=%d\n”,i,a+i,i,*(a+i));
printf(“address of a[%d]=%d\t value of a[%d]=%d\n”i,i+a,i,*(i+a));
pm++;
}
getch();
52
}
Pointers to Two Dimensional Arrays:
So far we have studied array of different standard data types such array of int,
float, characters etc.., In the same way the ‘C’ language also supports array of
pointers. It is nothing but a collection of addresses. Here, we store address of variables
for which we have to declare an array as a pointer.
/* Array of Pointers */
void main()
{
int a[10],*pa[10];
53
int n,i;
clrscr();
printf("Enter the size of an array\n");
scanf("%d",&n);
printf("Enter the elements into an array\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
pa[i]=&a[i];
printf("Elements in an array using pointerarray\n");
for(i=0;i<n;i++)
printf("%d\t",*pa[i]);
getch();
}
Pointers to Pointers:
54
Pointers and Strings:
character pointer.
#include<stdio.h>
#include<conio.h>
void main()
{
char name[20],*pch;
clrscr();
printf(“Enter you name\n”);
gets(name);
pch=name;
while(*ch!=’\0’)
{
printf(“%c”,*ch);
ch++;
}
getch();
}
Pointers to Functions:
I think you have already studied functions, now let’s see how it works with
pointers.
/* As same as Function Returning more values */
/* Function Returning more values */
void add(int *,int *,int *);
void main()
{
int a,b,c;
clrscr();
printf("Enter the values of a and b\n");
scanf("%d%d%d",&a,&b,&c);
printf("Before calling=%d\t b=%d\tc=%d\n",a,b,c);
add(&a,&b,&c);
55
printf("After calling a=%d\t b=%d\tc=%d\n",a,b,c);
getch();
}
void add(int *pa,int *pb,int *pc)
{
*pa=*pa+*pb+*pc;
*pb=*pa+*pb+*pc;
*pc=*pa+*pb+*pc;
printf("In change() a=%d\t b=%d\tc=%d\n",*pa,*pb,*pc);
}
56
Functions
The C language supports two types of Functions. 1. Library Functions 2. User
defined functions.
The library functions are predefined set of instructions. Their task is limited. A
user cannot understand the internal working of these functions. The user can only use
and pow (5,3) gives 125. Here, the user need not worry about its source code, but the
result should be provided by the function.
The userdefined functions are totally different. The functions defined by the
user according to his/her requirement are called as userdefined functions. The user
can modify the function according to the requirement. The user certainly understands
the internal working of the function. The user has full scope to implement his/her own
ideas in the function.
It is necessary to have a single function ‘main’ in every C program, along with
other functions used/defined by the programmer.
Definition of Function:
A function is a selfcontained block or a subprogram of one or more statements
that performs a special task when called.
Why use Functions?
If we want to perform a task repetitively then it is not necessary to rewrite the
particular block of the program again and again. Shift the particular block of
statements in a userdefined function. The userdefined function can be used for any
number of times to perform the task where we need in the entire program.
Using functions large programs can be reduced to smaller ones, It is easy to
debug and find out the errors in it. It also increases readability.
How Function Works?
1. Once a function is defined and called, it takes some data from the calling function
and returns a value to the called function.
2. The detail of inner working of a function is unknown to the rest of the program.
Whenever a function called, control passes to the called function and working of the
calling function is stopped. When the execution of the called function is completed, a
control returns back to the calling function and executes the next statement.
57
3. The value of actual arguments passed by calling function is received by the
formal arguments of the called function. The number of actual and formal arguments
should be the same. Extra arguments are discarded if they are defined. If the formal
arguments are more than the actual arguments then the extra arguments appear as
garbage. Any mismatch in the data type will produce the unexpected result.
4. The function operates on formal arguments and sends back the result to the
calling function using return () statement.
Declaration of Function and Function Prototype
Function is declared as per format given below.
return type functionname (type1 arg1,type2 arg2, ……..typen argn)
Where return type represents the datatype of the item that is returned by
the function, function name represents the name of the function, and type1, type2, …..
typen represents the data type of the arguments arg1, arg2, …argn.
Example: Following function returns the sum of two integers.
int add(int p,int q)
{
return p+q; //Body of the function
}
Here p and q are arguments. The arguments are called formal arguments or
formal parameters, because they represent the name of the data item that is
transferred into the function from the calling portion of the program. The
corresponding arguments in the function call are called actual arguments or actual
parameters, since they define the data items that are actually transferred.
A function can be invoked whenever it is needed. It can be accessed by specifying
its name followed by a list of arguments enclosed in parenthesis and separated by
commas.
Ex: add(10,20);
a) Actual Arguments The arguments of calling function are actual arguments.
b) Formal Arguments The arguments of called function are formal arguments.
c) Function Name A function must follow the same rule as we use for variable
naming.
d) Argument/Parameter List The argument list means variable names enclosed
within the parenthesis. They must be separated by comma (,). These formal
58
arguments (consignment) receive values from the actual argument and for performing
this is a communication between a consignee and consignor functions is made.
Function call A compiler executes the function when a semicolon (;) is followed by
function name. A function can be called simply using its name like other C statement,
terminated by semicolon (;).
For example the following program makes use of function that determines the sum
of two integer quantities.
#include<stdio.h>
#include<conio.h>
#include<math.h>
int add(int,int); /* Function Prototype */
void main()
{
int a,b,c;
clrscr();
printf("Enter the values of a and b\n");
scanf("%d%d",&a,&b);
printf(“Square root of %d is %f\n”,a,sqrt(a));
printf(“Power of %d power %d is %ld\n”,a,b,pow(a,b));
c=add(a,b); /* Calling Function Here a and b are actual arguments */
printf(“c=%d\n”,c);
getch();
}
int add(int p,int q)/* Called Function Here p and q are Formal arguments */
{
return(p+q);
}
The line of the function contains the function name, ‘add’ followed by formal
arguments p and q, enclosed in parenthesis. The formal arguments p and q represents
the data item that are transferred to the function from the calling function of the
program (i.e., add(a,b)). In addition the formal arguments p and q are preceded by the
data type int. i.e., it only accepts integers. When we execute this program the content
of the variables a and b are copied to the formal arguments p and q respectively and
59
the function returns the sum of p and q and is assigned to the variable c in the left side
of the calling function.
A function may or may not return a value. A ‘return’ statement returns some value
to the calling function and it may be assigned to the variable in the left side of the
calling function. The return value can be a constant, variable, a user defined data
structure, a general expression, a pointer to function, or a function call. The return
statement also causes the program logic to return to the point from which the function
was accessed. In general term the return statement is written as
return (variable or expression);
If a function does not return a value, the return type in the function definition
and declaration is specified as void. The declaration for a prototype for a function that
receive any arguments from the calling function and does not return any value will
have the format. void functionname(void);
Types of functions:
Depending upon the arguments present, return value sends the result back to
the calling function. Based on this, the functions are divided into four types.
1. Without arguments and no return values:
a) Neither the data is passed through the calling function nor the data is sent back
from the called function.
b) There is no data transfer between calling function and called function.
c) The function is only executed and nothing is obtained.
d) If such functions are used to perform any operation, they act independently. They
read data values and print results in the same block.
e) Such functions may be useful to print some messages, draw a line or split the line
etc..,
2. With arguments but without return values:
a) In above functions arguments are passed through the calling function. The called
function operates on the values. But no result is sent back.
b) Such functions are partly dependent on the calling function. The result obtained
is utilized by the called function and there is no gain to the main().
3. With arguments and return values:
a) In the below example the copy of actual arguments is passed to the passed to the
formal arguments i.e., value of ‘a’ and ‘b’ is assigned to ‘x’ and ‘y’ respectively.
60
b) The return statement returns the sum of two numbers and stores in z and return z.
c) Here data is transferred between calling and the called functions i.e.,
communications between functions is made.
4. without arguments and but with return value:
a) In the above type function no arguments are passed through the main() function.
But the called function returns the values.
b) The called function is independent. It reads values from the keyboard or
generates from initialization and returns the value.
c) Here both calling and called functions are partly communicated with each other.
/* Program for all four types of functions */
#include<stdio.h>
#include<conio.h>
void add(int,int);
void mul();
void main()
{
int a,b,c,d;
clrscr();
printf("Enter the values of a and b\n");
scanf("%d%d",&a,&b);
add(a,b); /*With arguments and no return value */
c=sub(a,b); /* With arguments and with return value */
printf("subtraction of a and b is %d\n",c);
mul(); /* Without arguments and without return value */
d=div(); /* Without arguments and with return value */
printf("Division of a and b is %d\n",d);
getch();
}
void add(int c,int d)
{
printf("Addition of a and b is %d\n",c+d);
}
int sub(int c,int d)
61
{
return(cd);
}
void mul()
{
int a,b;
printf("Enter the values of a and b\n");
scanf("%d%d",&a,&b);
printf("multiplication of a and b is %d\n",a*b);
}
int div()
{
int a,b;
printf("Enter the values of a and b\n");
scanf("%d%d",&a,&b);
return(a/b);
}
Arguments can be passed to a function by two methods. They are
1. Pass (call) by value.
2. Pass (call) by reference.
Pass (call) by value:
Function in C passes all arguments by value. When a single value is passed to a
function vail an actual argument, the value of the actual argument is copied into the
function. Therefore, the value of the corresponding formal argument can be altered
within the function, but the value of the actual argument within the calling routine
will not change. This procedure for passing the value of an argument to a function is
known as passing by value.
Ex:add(a,b);
Pass (call) by reference:
When passing by reference technique is used, the address of the data item is
passed to the called function. Using & operator we can determine the address of the
data item. Note that function once receives a data item by reference, it acts on data
62
item and the changes made to the data item also reflect on the calling function. Here
you don’t need to return anything to calling function.
Ex:swap(&a,&b);
/* Program on Call by value and Call by Reference */
void swap(int,int);
void swap1(int *,int *);
void main()
{
int a,b;
clrscr();
printf("Enter the values of a and b\n");
scanf("%d%d",&a,&b);
printf("Before call by value a=%d\t b=%d\n",a,b);
swap(a,b);
printf("After call by value a=%d\t b=%d\n",a,b);
printf("Before call by reference a=%d\t b=%d\n",a,b);
swap1(&a,&b);
printf("After call by reference a=%d\t b=%d\n",a,b);
getch();
}
void swap(int p,int q)
{
int t;
t=p;
p=q;
q=t;
printf("In swap() a=%d\t b=%d\n",p,q);
}
void swap1(int *pa,int *pb)
{
int t;
t=*pa;
*pa=*pb;
63
*pb=t;
printf("In swap1() a=%d\t b=%d\n",*pa,*pb);
}
Functions returns more values:
So far we know that the function can return only one value per call. We can also
force the function to return more values per call. It is possible to call by reference
method. The example given before illustrates it.
/* Function Returning more values */
void change(int *,int *);
void main()
{
int a,b;
clrscr();
printf("Enter the values of a and b\n");
scanf("%d%d",&a,&b);
printf("Before call by reference a=%d\t b=%d\n",a,b);
change(&a,&b);
printf("After call by reference a=%d\t b=%d\n",a,b);
getch();
}
void change(int *pa,int *pb)
{
*pa=*pa+*pb;
*pb=*pa+*pb;
printf("In change() a=%d\t b=%d\n",*pa,*pb);
}
Function as an argument:
Till now we have passed the values or address through the functions. It is also
possible to pass a function as an argument.
/* Functions as arguments in function */
void add(int ,int );
void main()
64
{
clrscr();
add(a(),b());
getch();
}
void add(int p,int q)
{
printf("p+q=%d\n",p+q);
}
int a()
{
return 10;
}
int b()
{
return 50;
}
Function with Operators:
1.The assignment operator (=) The use of this operator is to assign some values to
the variable. To assign return value of function to the variable following syntaxes are
used. Syntax: x= square(2);
2. Addition and subtraction (+ & ):Syntax: p=(a()+b());
3.Multiplication and Division (* & /): Syntax: r=(a()*b()/c());
4.Increase and decrease Operators (++ & ): Syntax: m=fun1(++a(),b());
5.Mod((%) and ? Operators: Syntax: n=(m()%2==0);
Function and Decision Statements:
There are two decisionmaking statements in C.
1.ifelse statement:
Syntax: if(a()%2==0) printf(“Number is even\n”); else printf(“Number is odd\n”);
2.switch()……..case Statement:
65
The switch() case statement also makes decision at run time in the program . It has
multiple choices. The switch() requires one argument and its body contains various
case statements like branch. Depending upon the value of the switch() argument
matched case statement is executed.
Syntax: switch(r()) { case 1:………;case 2:……..;default:……}
Function and Loop Statements:
Loop statements are used to repeat program code repetitively for given number
of times or based on certain condition.
1. The for loop: Syntax: for(fun();fun1();m++)
2. The while loop: Syntax: while(fun2());
3. working with do…while() loop:
do{
………
………
}while(fun1());
Function with Arrays and Pointers:
/* To pass array element to the function, use call by value method */
void main()
{
int a,show(int,int);
int num[]={1,2,3,4,5,6,7,8,9,10};
clrscr();
printf(“\n”);
for(a=0;a<10;a++)
{
show(a,num[a]);
}
getch();
}
void show(int p,int q)
{
printf(“num[%d]=%d\t”,p,q);
66
}
/* To pass array elements to the function. Use call by reference */
void main()
{
void show(int *);
int num[]={1,2,3,4,5,6,7};
clrscr();
show(num);
getch();
}
void show(int *pa)
{
int i=0;
printf(“\n num[7]={ “);
while(i<7)
{
printf(“%5d”,*(pa++));
}
printf(“\b}”);
}
Recursion:
Recursive functions are those functions, which functions calls itself within that
function. A recursive function must have the following type of statements.
A statement to test and determine whether the function is calling itself again.
A statement that calls the function itself and must be an argument.
A conditional statement (ifelse)
A return statement
Example: Factorial of a number
67
{
long int f;
if(x==1)
{
return(x);
}
else
return(x*fact(x1));
}
void main()
{
int n;
clrscr();
printf(“Enter a number\n”);
scanf(“%d”,&n);
printf(“Factorial of %d is %ld\n”,n,fact(n));
getch();
}
Pointer to Function
In C every variable has an address except register variables. We can access the
address of the variable using pointers. C functions also have an address. We invoke the
function using its address. Consider the following example.
/* To Display address of user defined function */
void main()
{
void show(); /* Function Prototype */
clrscr();
show(); /* Function Call */
printf(“%u”,show); /* Displays address of Function */
}
void show()
{
printf(“\n Address of function show() is:”);
68
}
69
Preprocessor Directives
Introduction:
Any programs execution needs certain steps. They are:
a) The C programs is written in the editor
b) Compilation
c) Linking and
d) The executable code is generated. In between these steps there also involves one
more stages i.e. preprocessor. The preprocessor is a program that processes the
source program before it is passed on to the compiler.
The program typed in the editor is the source code to the preprocessor. The
preprocessor then passes the source code to the compiler.
One of the most important features of C language is to offer preprocessor
directives. The preprocessor directives are always initialized at the beginning of the
program. It begins with a symbol #(hash). It can be placed anywhere but quite often
it is declared at the beginning before the main() function or any particular function.
The # define Directive:
The syntax of #define directive is as follows
#define identifier <substitute text>
Or
#define identifier (argument 1…..argument N) substitute text
Example:
#define PI 3.14
This statement defines macro templates. During preprocessing the
preprocessor replaces every occurrence of PI (identifier) with 3.14(substitute value).
Here, PI is a macro template and 3.14 is its macro expansion. The macro templates
are generally declared with capital letters for quick identification. One can also
define macros with small letters. The macro templates and its expansions must be
separated with at least one blank space. It is not necessary to provide space between
# and define. It is optional to programmer.
Use the identifier for 3.14 as PI and Write a program to find the area of circle
using it.
# include <stdio.h>
#include <conio.h>
# define PI 3.14
void main()
{
float r,area;
printf(“\n Enter radius of circle in cms.”);
scanf(“%f”,&r);
area=PI*r*r;
printf(“Area of a circle =%.2f cm2”,area);
70
getch();
}
Undefining a Macro:
A macro defined with #define directives can be undefined with # undef directive.
Syntax: # undef identifier
It is useful when we do not want to allow the use of macros in any portion of the
program.
Write a program to undefined a macro.
# define wait getch()
void main()
{
int k;
# undef wait() getch();
clrscr();
for(k=1;k<=5;k++)
printf(“%d\t”,k);
wait;
}
Explanation: In the above program wait() is defined in place of getch(). In the
program # undef directive undefines the same macro. Hence, the compiler flags an
error message “undefined symbol ‘wait’ in function main.”
Token Pasting and Stringizing Operators:
Stringizing operation In this operation macro argument is converted to
string. The sign # carries the operation. It is placed before the argument
Write a program to carry out stringizing operation.
# define say(m) printf(#m)
void main()
{
clrscr();
say(Hello);
}
The # include Directive
The # include directive loads specified file in the current program. The macros
and functions of loaded file can be called in the current program. The included file is
also compile with current program. The syntax is as given below.
a) # define “filename”
b) #include <filename>
Where, # is a symbol used with directives.
a) The file name is included in the double quotation marks which indicate that the
search for the file is made in the current directory and in the standard
directories.
Example # include “stdio.h”
71
b) When the file name is included without double quotation marks, the search for
file is made only in the standard directories.
Example # include <stdio.h>
#include<udf.h>
Write a program to call the function defined in “a.c” file
#include <stdio.h>
#include <conio.h>
#include ”a.c”
void main()
{
clrscr();
display();
}
Contents of a.c file
int display();display(){ printf(“\n Function Called”); return 0; }
Conditional Compilation:
The most frequently used conditional compilation directives are #if, #else, #endif
etc. These directives allow the programmer to include the portions of the codes based on
the conditions. The compiler compiles selected portions of the source codes based on the
condition. The syntax of the #def directives is given below.
Syntax:
#ifdef <identifier>
{
Statement1;
Statement2;
}
#else
{
Statement3;
Statement4;
}
#endif
The #ifdef preprocessor tests whether the identifier has defined substitute
text or not. If the identifier is defined then #if block is compiled and executed. The
compiler ignores #else block even if errors are intentionally made. Error messages
will not be displayed. If identifier is not defined then #else block is compiled and
executed.
Write a program to use conditional compilation statement as to whether the
identifier is defined or not.
#include <stdio.h>
#include <conio.h>
# define LINE 1
void main()
72
{
clrscr();
#ifdef LINE
printf(“This is Line number one.”);
#else
printf(“This is line number two”);
#endif
getch();
}
The #ifndef Directive:
The syntax of the #ifndef directives is given below
Syntax:
#ifndef<identifier>
{
Statement1;
Statement2;
}
#else
{
Statement3;
Statement4;
}
#endif
The #ifndef works exactly opposite to that of #ifdef. The #ifndef preprocessor
tests whether the identifier has defined substitute text or not. If the identifier is
defined then #else block is compiled and executed and the compiler ignores #if
block even if errors are intentionally made. Error messages will not de displayed. If
identifier is not defined then #if block is compiled and executed.
Write a program to use conditional compilation directives #ifndef. If it is
observed display one message otherwise another message.
#include <stdio.h>
#include <conio.h>
# define T 8
void main()
{
clrscr();
#ifndef T
printf(“Macro is not defined.”);
#else
printf(“Macro is defined”);
#endif
getch();
}
The #error Directive:
73
The # error is used to display user defined message during compilation of the
program. The syntax is as given below.
#if !defined (identifier)
# error <ERROR MESSAGE>
#endif
Write a program to display userdefined error message using #error directive.
#include <stdio.h>
#include <conio.h>
# define B 1
void main()
{
clrscr();
#if !defined(A)
#error Macro A is not Defined.
#else
printf(“Macro found”);
#endif
}
Tip The #defined directive will work exactly opposite to #! Defined directive. The
syntax is as given below.
#if defined(identifier)
{
}
#else
#error<ERROR MESSAGE>
#endif
The # line Directive
The syntax of line directive is as follows
#line <constant> [<identifier>]
Causes the compiler to imagine the line number of the next source line as given by
<constant>, and <identifier> gives the current input file. If <identifier> is absent,
then the current file name remains unchanged.
Example #line 15 pragma.c
Structure and Union
Introduction:
74
You are aware that a variable stores a single value of a data type. Arrays can
store many values of similar data type. Data in the array is of the same composition
in nature as far as type is concerned. In real life we need to have different data
types for example to maintain employees information we should have information
such as name, age, qualification, salary etc. Here, to maintain the information of
employees dissimilar data types are requires. Name and qualification o the
employee are char data type, age is integer, and salary is float. All these data types
cannot be expressed in a single array. One may think to declare different arrays for
each data type. But there will be huge increase in sources codes of the program.
Hence, arrays cannot be useful her. For tackling such mixed data types, a special
feature is provided by C. it is known as structure.
A structure is a collection of one or more variables of different data types, grouped
together under a single name. By using structures we can make a group of variables,
arrays, pointer etc.
Feature of Structures: To copy elements of one array to another array of same data
type elements are copied one by one. It is not possible to copy all the elements at a time.
Whereas in structure it is possible to copy the contents of all structure elements of
different data types to another structures variable of its type using assignment (=)
operator. It is possible because the structure elements are stored in successive memory
locations.
Nesting of structure is possible i.e. one can create within the structure.
Using this feature one can handle complex data types.
It is also possible to pass structure elements to functions. This is similar to
passing an ordinary variable to a function. One can pass individual structure elements
or entire structure by value or address.
It is also to create structure pointers. In the pointer we have studied pointing
a pointer to an integer, pointing to a float and pointing to a char. In a similar way we
can create a pointer pointing to structure elements. For this it requires > operator.
Declaration and Initialization of Structures:
Structure can be declared as given below.
struct struct_type
{
Type variable1;
Type variable2;
};
Structure declaration always starts with struct keyword. Here, struct_type is
known as tag. The struct declaration is enclosed within a pair of curly braces. Using
75
struct and tag user can declare structure variables like variable1, variable2 and so
on. These are the members of the structure.
After defining structure we can create variables as given below.
struct struct_type v1, v2, v3
Here, v1, v2 and v3 are variables of structure struct_type. This is similar to
declaring variables of any data type.
int v1, v2, v3 Here, v1, v2 and v3 are variables of integer data type.
The declaration defines the structure but the structure but this process
doesn’t allocate memory. The memory allocation takes places only when variables are
declared.
struct book1
{
char book [30];
int pages;
float prices;
};
struct book1 bk1;
Bk1
Book[30]
Pages
Prices
In the above example a structure of type book1 is created. It consists of three
member’s book [30] of char data type, pages of int type and price of float data type.
Figure 13.1 explains various members of a structure.
struct book1 bk1;
The above line creates variable bk1 of type book1 and it reserves total
36bytes(30bytes for book[30], 2bytes for integer and 4bytes for float). Through bk1 all
the three members of structure can be accessed. In order to initialize structure
elements with certain values following statements is used.
struct book1 bk1= { “Shrinivas”, 500,385.00};
All the members of structure are related to variable bk1.
Structure_variable.member or bk1.book
The period (.) sign is used to access the structure members.
We can directly assign values to members as given below
bk1.book = ”shrinivas”;
bk1.pages=500;
bk1.prices=385.00;
76
#include<stdio.h>
#include<conio.h>
main()
{
struct state
{
char stname[20];
int noofdist;
double population;
};
struct state st;
printf("Enter stname\t noofdist\t population\n");
scanf("%s%d%d",&st.stname,&st.noofdist,&st.population);
printf("Statename=%s\nno.of districts=%d\npopulation=%d\n",
st.stname,st.noofdist,st.population);
getch(); }
Structure within Structure:
We can take any data type for declaring structure members like int, float,
char etc. in the same way we can also take object of one structure as member in
another structure. Thus, structure within structure can be used to create complex data
applications. The syntax of the structure within the structure is as follows.
struct time
{
int second;
int minute;
int hour;
};
struct t
[
int carno;
struct time st;
struct time et;
};
struct t player;
#include<stdio.h>
#include<conio.h>
main()
{
struct population
{
int menp;
int womenp;
};
struct state
{
char stname[20];
77
int no_ofdist;
};
struct data
{
struct population p;
struct state s;
};
struct data d;
printf("Enter the data\n");
scanf("%d%d%s%d",&d.p.menp,&d.p.womenp,&d.s.stname,&d.s.no_ofdist);
printf("menp=%d\nwomenp=%d\nstname=%s\nno_ofdist=
%d\n",d.p.menp,d.p.womenp,d.s.stname,d.s.no_ofdist);
}
Array Of Structrues:
As we know array is a collection of similar data types. In the same way we can
also define array of structure. In such type of array every elements is of structure type.
Array of structure can be declared as follows.
struct time
{
int second;
int minute;
int hour;
} t[3];
In the above example t[3] is an array of 3 elements containing three objects of
time structure. Each element of t[3] has structure of time with 3 members that are
second, minute and hour. A programs is explained as given below.
#include<stdio.h>
#include<conio.h>
main()
{
struct state
{
char stname[20];
int noofdist;
double population;
};
struct state st[3];
int k;
for(k=0;k<3;k++)
{
printf("Enter stname\t noofdist\t population\n");
scanf("%s%d%d",&st[k].stname,&st[k].noofdist,&st[k].population);
}
for(k=0;k<3;k++)
printf("Statename=%s\nno.of districts=%d\npopulation=
%d\n",st[k].stname,st[k].noofdist,st[k].population);
78
getch();
}
Pointers to Structure:
We know that pointer is a variable that holds the address of another data
variable. The variable may be of any data type i.e. int float or double. In same way we
can also define pointer to structure. Here, starting address of the member variables can
be accessed. Thus, such pointers are called structure pointers.
Example:
struct book
{
char name[25];
char author[25];
int pages;
};
struct book *ptr;
In the above example *ptr is pointer to structure book. The syntax for using
pointers with member is as given below.
1) ptr name
2) ptr author
3) ptr pages
By executing these statements starting address of each member can be
estimated.
#include<stdio.h>
#include<conio.h>
main()
{
int *e1;
struct emp
{
int m;
int n;
int o;
}e;
e.m=10;
e.n=20;
e.o=8000;
e1=&e.m;
79
printf("m=%d",*e1);
printf("n=%d",*(++e1));
printf("o=%d",*(++e1));
getch();
}
Structure and function:
Like variables of standard data type structure variables also can be passed
to functions by value or address. The syntax of the same is as under.
struct book
{
char name[35];
char author[35];
int pages;
}
b1;
void main()
{
show(&b1);
}
show (struct book *b2)
{
}
Whenever a structure element is to be passed to any other function, it is
essential to declare the structure outside the main() function i.e. global.
In the above example structure book is declared before main(). It is a global
structure. Its member elements are char name [35], char author[35] and int pages.
They can be accessed by all other functions.
Write a program to pass address of structure variable to user defined function
and display the contents.
/*passing address of structure variable*/
struct book
{
char name[20];
char author[20];
int pages;
};
void main()
80
{
struct book b1= {“Java Complete reference”,”p.naughton”,886};
show(&b1);
}
show (struct book *b2)
{
clrscr();
printf(“\n %s by %s of %d pages”,b2>name,b2>author,b2>pages);
}
typedef
By using typedef we can create new data type. The statement typedef is to be
used while defining the new data type. The syntax is as given under.
typedef type dataname;
Here, type is the datatype and dataname is the userdefined name for that type.
typedef int hours;
Here, hours is another name for int and now we can use hours instead of int in the
program as follows.
hours hrs;
Write a program to create userdefined datatype hours on int data type and
use it in the program.
#define H 60
main()
{
typedef int hours;
hours hrs;
clrscr();
printf(“Enter hours:”);
scanf(“%d”,&hrs);
printf(“\nMinutes = %d”,hrs*H);
printf(“\nSeconds=%d”,hrs*H*H);
}
Create user defined data type from structure. The structure should contain
the variables such as char, int etc. By using these variables display name, sex
& acno. of an employee.
main()
{
typedef struct
{
char name[20];
char sex[2];
int acno;
}info;
info e={“prasad”,”M”,121};
printf(“\n Name\t Sex\t A/C No.\n”);
printf(“%s\t”,e.name);
printf(“%s\t”,e.sex);
81
printf(“%d\n”,e.acno);
}
Enumerated Data Type:
The enum is a keyword. It is used for declaring enumeration types. The
programmer can create his/ her own data type and define what values the variables of
these data types can hold. This enumeration data type helps in reading the program.
Consider the example of 12 months of a year.
enum month {jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec};
This statement creates a user defined data type. The keyword enum is followed by
the tag name month. The enumerated are the identifiers jan, feb, mar, apr, may and
so, on. Their values are constants unsigned integers and start from 0. The identifier jan
refers to 0, feb to 1 and so on. The identifiers are not to be enclosed with in quotation
marks. Please also note that integer constants are also not permitted.
Write a program to create enumerated data type for 12 months. Initialize the
first identifier with 1. Display their values in integer constants.
void main()
{
enum month { Jan=1, Feb, Mar, Apr, May, June, July, Aug, Sep, Oct, Nov, Dec};
clrscr();
printf(“\nJan=%d”,Jan);
printf(“\nFeb=%d”,Feb);
printf(“\nJune=%d”,June);
printf(“\nNovember=%d”,Nov);
}
Union:
Union is a variable, which is similar to the structure. It contains number of
members like structure but it holds only one object at a time. In the structure each
member has its own memory location whereas, member of unions have same memory
locations. It can accommodate one member at a time in a single area of storage. Union
also contains members of typed int, float, long, arrays, pointers etc. it allocate fixed
specific bytes of memory for access of data types irrespective of any data type.
The union requires bytes that are equal to the number of bytes required for the
largest members. For examples the union contains char, integer & long integer then
the number of bytes reserved in the memory for the union is 4bytes. An example is
illustrated below for understanding.
Write a program to find size of union and number of bytes reserved for it.
main()
{
union result
{
int marks;
82
char grade;
};
struct res
{
char name[20];
int age;
union result perf;
}data;
clrscr();
printf(“size of union:%d\n”,sizeof(data.perf));
printf(“size of structure:%d\n”,sizeof(data));
}
Union of Structure:
We know that one structure can be nested within another structure. It the same
way a union can be nested within another union. We can also create structure in a
union or vice versa.
Write a program to use structure within union. Display the contents of structure
elements.
void main()
{
struct x
{
float f;
char p[2];
};
union y
{
struct x set;
};
union z st;
st.set.f=5.5;
st.set.p[0]=65;
st.set.p[1]=66;
clrscr();
printf(“\n%g”,st.set.f);
printf(“\n%c”,st.set.p[0]);
printf(“\n%c”,st.set.p[1]);
}
Files
Introduction
Applications generally involve tremendous amount of data to be read and
written to an auxiliary storage. Hence to save such information on the disk we use data
files. File is a collection of numbers, symbols and text placed on the disk. In due course
83
of time files can be read and modified as per the user requirements. Thus, files allow us
to store information permanently in the disk, access and further it can be altered
depending upon the needs. This process leads to the concept of data files.
a) Definition of File
File is a set of records that can be accessed through the set of library functions.
Streams and File Types
Stream means reading and writing of data. The streams are designed to allow
the user to access the files efficiently. A stream is a file or physical device like
keyboard, printer and monitor. The FILE object uses these devices.
The FILE object contains all the information about stream like current position,
pointer to any buffer, error and EOF (end of file). Using this information of object, c
program uses pointer, which is returned from stream function fopen ().
A) File Types: There are two types of files
1. Sequential file 2.Random accesses file
1. Sequential file:
In this type data are kept sequentially. If we want to read the last record of the file
we need to read all the records before that record. It takes more time. Or if we desire to
access the 10th record then the first 9 records should be read sequentially for reaching
to the 10th record.
2. Random Access File:
In this type data can be read and modified randomly. In this type if we want to
read the last records of the file, we can read it directly. It takes less time as compared
to sequential file.
Steps for file Operations: These are three steps for file operation in C.
A C Language supports many more file handling functions that are
available in standard library. These functions are listed in the table given below. All
the functions that support C are not listed her because all compilers do not support all
the functions. One should check the c library before using them.
Function Operation
fopen() Creates a new file for read/write operation.
fclose() Closes a file associated with file pointer.
closeall() Closes all opened files with fopen().
84
fgetc() Read the character from current pointer position and
advances the pointer to next character.
getc() Same as fgetc()
fprintf() Writes all types of data values to the file.
fscanf() Reads all types of data values from a file
putc() Writes character one by one to a file.
gets() Reads string from the file.
puts() Writes string to the file.
putw() Writes an integer to the file.
getw() Reads an integer from the file.
fread() Reads structured data written by fwrite() function.
fwrite() Writes block of structured data to the file.
fseek() Sets the pointer position anywhere in the file.
feof() Detects the end of file.
ferror() Reports error occurred while read/write operations.
perror() Prints compilers error messages along with user
defined messages
ftell() Returns the current pointer positions.
rewind() Sets the record pointer at the beginning of the file.
unlink() Removes the specified file from the disk.
rename() Changes the name of the file.
a. Opening of file:
A file has to be opened before beginning of read and write operations. Opening
of file creates a link between the opening system and the file functions. We have to
specify the name of file and it’s mode to the operating system. This important task is
carried out by the structure FILE that is defined in stdio.h header file. So this file
must be included.
When a request is made to the operating system for opening a file, it does so
granting the request. If request is granted the operating systems points to the
structure FILE. In case the request is not granted it returns NULL. That is why the
following declaration before opening of the file is to be made.
FILE *fp
Where, fp is file pointer.
Each file that we open has its own FILE structure. The information that the file
contains may be its current size, its locations in memory etc.
The only one function to open a file is fopen()
85
Syntax for opening the file:
FILE *fp;
fp = fopen(“data.txt”,”r”);
Here, fp is a pointer variable that contains address of the structure FILE that
has been defined in the header file”stdio.h”. The function fopen() will open a file
“data.txt” in read mode. The C compiler reads the contents of the file because it finds
the read mode (“r”). Here, “r” is a string and not a character. Hence, it is enclosed with
double quotes and not with single quotes.
The fopen () performs three important tasks:
1. It searches the disks for opening the file.
2. In cases the file exits, it loads the file from the disks into memory. If the file is
found with huge contents then it loads the file part by part.
3. If the file is not exiting this function returns a NULL. NULL is a macro defined
character in the header file ”stdio.h”. This indicates that it is unable to open file.
There may be following reasons for failure of fopen() functions.
A) When the file is in protected or hidden mode.
B) The file may be used by another program.
4. It locates a character pointer, which points the first character of the file.
Whenever a file is opened the character pointer points to the first character of the file.
Given below are different modes in which a file can be opened.
A. Text Modes
1. w(write): This mode opens a pre existing file for reading. If the file doesn’t exist,
then compiler returns NULL to the file pointer. If the file already exists, it will be
overwritten without confirmation.
Syntax: fp=fopen(“data.txt”,w”);
Here, data.txt is the file name and “w” is the mode.
2. r(read): This mode opens a preexisting file for reading. If the file doesn’t exist, then
compiler returns NULL to the file pointer. Using pointer with if statement we can
prompt the user regarding failure of operation.
Syntax: fp= fopen(“data.txt”,”r”);
if(fp==NULL)
printf(“file does not exists”); Or
if(fp=(fopen(“data.txt”,”r”))==NULL)
printf(“File does not exist”):
86
Here, data.txt is opened for reading only. If the file does not exist the fopen()
returns NULL to file pointer ‘fp’. Using the NULL value of fp with if statement we
can prompt the user for failure of fopen() function.
Write a program to write data to text file and read it.
#include<process.h>
main()
{
FILE *fp;
char c;
fp=fopen("data.txt","w");
if(fp==NULL)
{
printf("Cannot open file");
exit(1);
}
printf("Write data & to stop process '.':\n");
while(c!='.')
{
c=getchar();
fputc(c,fp);
}
fclose(fp);
printf("\n Contents Read:\n");
fp=fopen("data.txt","r");
while(!feof(fp))
printf("%c",getc(fp));
}
3. a(append): This mode opens a preexisting file for appending data. If the file doesn’t
exist then new file is opened i.e. if the file does not exist then the mode of ‘a” is same as
“w”
Syntax: fp=fopen(“data.txt”,’a”);
Here, if data.txt file already exists, will be opened. Otherwise a new file will be
opened with the same name.
87
Write a program to open a preexisting file and add information at the end of
file. Display the contents of the file before and after appending.
#include<stdio.h>
#include<conio.h>
#include<process.h>
main()
{
FILE *fp;
char c;
printf("\nContents of file before appending:\n");
fp=fopen("data.txt","r");
while(!feof(fp))
{
c=fgetc(fp);
printf("%c",c);
}
fclose(fp);
fp=fopen("data.txt","a");
if(fp==NULL)
{
printf("File cannot be appended\n");
exit(1);
}
printf("\nEnter string to append:\n");
while(c!='.')
{
c=getchar();
fputc(c,fp);
}
fclose(fp);
printf("Contents of file after appending:\n");
fp=fopen("data.txt","r");
while(!feof(fp))
{
c=fgetc(fp);
printf("%c",c);
}
}
4. w+(write + read): It searches for file, if found its contents are destroyed. If the file
isn’t found a new file is created. Returns NULL if fails to open the file. In this mode file
can be written and read.
Example: fp=fopen(“data.txt”,”w+”);
In the above example data.txt file is open for reading and writing operations.
#include<stdio.h>
#include<conio.h>
88
main()
{
FILE *fp;
char c;
fp=fopen("data1.txt","w+");
if(fp==NULL)
printf("FILE does not exist\n");
printf("Enter the data and to stop press . ");
while(c!='.')
{
c=getchar();
fputc(c,fp);
}
rewind(fp);
printf("Data from the file is\n");
while(!feof(fp))
printf("%c",fgetc(fp));
}
5. a+(append + read): in this mode file can be read and records can be added at the
end of file.
Example: fp=fopen(“data.txt”,”a+”);
Here, data.txt is opened and records are added at the end of file without affecting the
previous contents.
NOTE:
1. In case read operation is done after write operation character pointer should be
set at beginning of file using rewind().
2. In case write/append operation is done after read operation. It is not essential to
set the character pointer at the beginning of file.
6. r+(read+write): This mode is used for both reading and writing. We can read
and write the record in the file. If the file does not exist, the compiler returns NULL to
the file pointer. It can be written as follows.
Example: fp=fopen(“data.dat”,”r+”);
89
if(fp==NULL)
printf(“File not found”);
In the above example, data.dat is opened for read and write operation. If fopen()
fails to open the file it returns NULL. The if statements checks the value of file pointer
fp and if it contains NULL a message is printed and the program terminates.
B. Binary Modes:
1. wb(write): This mode opens a binary file in write mode.
Example: fp= fopen(“data.dat”,”wb”);
Here, data.dat file is opened in binary mode for writing.
main()
{
FILE *fp;
char c;
fp=fopen("text.dat","wb");
if(fp==NULL)
{
printf("cannot open file\n");
exit(1);
}
printf("Write data and to stop press '.' \n");
while(c!='.')
{
c=getchar();
fputc(c,fp);
}
fclose(fp);
printf("\n Contents Read :");
fp=fopen("text.txt","rb");
while(!feof(fp))
printf("%c",fgetc(fp)); }
2. rb(read): This mode opens a binary file in read mode
Example: fp= fopen(“data.dat”,”rb”);
Here, data.dat file is opene din binary mode for reading.
3. ab(append): This mode opens a binary file in append mode i.e data can be added at
the end of file.
Example: fp= fopen(“data.dat”,”ab”);
Here, “data.dat” file is opend in append mode.
4. r+b(read+write): This mode opens a preexisting file in read and write mode i.e. file
can be read and written.
Example: fp= fopen(“data.dat”,”r+b”);
Here, the file “data.dat” is opened for opened for writing in binary mode.
5. w+b(read+write): this mode creates a new file in read and write mode.
Example: fp= fopen(“data.dat”,”w+b”);
90
Here, the file”data.dat” is created for reading and writing in binary mode.
6. a+b(append+ write): this mode opens a file a file in append mode i.e. data can be
written at the end of file. If file does not exit a new file is crate.
Example: fp= fopen(“data.dat”,”a+b”);
Here, the file ”data.dat” is opened in append mode and data can be written at
the end of file.
b. Reading A File:
once the file is operand using fopen(), it’s contents are loaded into the memory
(party or wholly). The pointer points to the very first character of the file. The fgetc()
function is used to read the contents of the file. The syntax for fgetc() is as follows.
ch = fgetc(fp);
Where, fgetc() reads the character from current pointer position and advances
the pointer position so that the next character is pointed. The variable ch contains the
character read by fgetc(). There are also other function to read the contents of the
file, which are explained in the next pages.
c. Closing A File: The file that is opened from the fopen() should be closed after the
work is over i.e. we need to close the file after reading and writing operation are over.
Example: fclose (fp);
This statement closes the file associated with file pointer fp. This function closes
one file at a time. To close one or more file at a time the function fcloseall () is used.
FILE I/O:
1. fprintf(): This function is used for writing characters, strings, integers, floats etc. to
the file. It contains one more parameter that is file pointer, which points the opened
file. Here is a program that illustrate the use of fprintf() functions.
2. fscanf(): This function reads character, strings, integer, floats etc. from the file
pointed by the pointer. A program is illustrated below based on this.
Write a program to enter data into the text file and read the same. Use “w+”
file mode. Use fscanf() to read the contents of the file.
main()
{
FILE *fp;
char text[15];
int age;
fp=fopen(“Text.txt”,”a+”);
clrscr();
printf(“Name\tAge\t”);
scanf(“%s%d”,text,&age);
fprintf(fp, “%s%d”,text,age);
printf(“Name\tAge\t”);
91
fscanf(fp,“%s%d”,text,&age);
printf(“%s\t%d\n”,text,age);
fclose(fp);
}
3. getc(): This function reads a single character from the operand file and moves the
file pointer. It returns EOF, if end of file is reached.
Syntax: getc(fp);
4. putc(): This function is used to write a single character into a file. If an error occurs
it returns EOF. Syntax: putc(c,fp);
5. fgetc(): This function is similar to getc() function. It also reads a character and
increases the pointer position. If any error or end of file is reached it returns EOF.
Syntax: fgetc(fp);
6. fputc(): This function writes the character to the file shown by the file pointer. It
also increases the file pointer.
Syntax: fputc(c,fp); Where, fp is file pointer and c is a variable written to the file
pointed by file pointer.
7. fgets(): This function reads string from a file pointed by file pointer. It also copies
the string to a memory location referred by an array.
8. fputs(): This function is useful when we want to write a string into the opened file.
9. putw(): This function is used to write an integer value to file pointed by file pointer.
10. getw():This function returns the integer value from a file and increases the file
pointer.
Structures Read and Write:
It is important to know how numerical data is stored on the disk by
fprintf() function. Text and characters require one byte for storing them with fprinf().
Similarly for storing numbers in memory two bytes and for floats four bytes are
required.
All the data are treated as character for examples the data 3456, it
occupies two bytes in memory. But when it is transferred to the disk file using
fprintf() function it would occupy four bytes. For each character one byte would be
required. Even for float also each digit including dot (.) requires one byte. For example
it would require five bytes. Thus, large amount of integers or float data requires large
space on the disk. Hence in the text mode storing of numerical data on the disk turns
out to be inefficient. To overcome this problem the files should be read and write in
binary mode, for which we use functions fread() & fwrite().
1. fwrite() & fread:
fwrite():
92
This function is used for writing an entire structure block to a given file.
fread(): This function is used for writing an entire block from a given file.
Other File Function:
a) The fseek() function: It is a file function. It positions file pointer on the stream.
We can pass three arguments through this function.
1. File Pointer.
2. Negative or positive long integer number to reposition the file pointer towards the
backward or forward direction.
3. The current position of file pointer.
Location of File Pointer:
Integer Value Constant Location in the file
0 SEEK_SET Beginning of the file
1 SEEK_CUR Current position of the file pointer
2 SEEK_END End of the file
Example:
fseek(fp,10,0) or fseek(fp,10,SEEK_SET)
The file pointer is repositioned in the forward direction by 10 bytes.
Write a program to read the text file containing some sentence. Use fseek()
and read the text after skipping n characters from beginning of the file.
main()
{
FILE *fp;
int n,ch;
fp=fopen("text.txt","r");
printf("\nContents of file\n");
while((ch=fgetc(fp))!=EOF)
printf("%c",ch);
printf("\n How many characters including spaces would you like to skip ?:");
scanf("%d",&n);
fseek(fp,n,SEEK_END);
printf("\nInformation after %d bytes\n",1*n);
while((ch=fgetc(fp))!=EOF)
printf("%c",ch);
fclose(fp);
}
b) feof(): The macro feof() is used for detecting the file pointer whether it is at the end
of file or not. It returns nonzero if the file pointer is at the end of file, otherwise it
returns zero.
SEARCHING ERRORS IN READING/WRITING FILES:
While performing read or write operations some times we do not get the
result successfully. The reason may be that the attempt of reading or writing the
operation may not be correct. The provision must be provided for searching the error
while read/ write operations are carried out.
93
The ‘C’ language provides standard library function ferror(). This
function is used for detecting any error that might occur during read/ write operation
on a file. It returns a ‘0’ when the attempt is successful otherwise nonzero in case of
failure.
c) ferror(): The ferror() is used to find out error when file read write operation is
carried out.
Write a program to detect an error while read/ write operation of a file is in
use.
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
FILE *fp;
char next= ‘Y’;
char name[25];
int marks;
float p;
fp=fopen(“marks.dat”, “r”);
if(fp==NULL)
{
puts(“can not open file”);
exit(1);
}
clrscr();
while(next==’Y’)
{
printf(“\n enter name, marks percentage”);
scanf(“%s%d%f”, &name,&marks,&p);
p=marks/7;
fprintf(fp,”%s%d%f”, &name,&marks,&p);
if(ferror(fp))
{
94
printf(“\n unable to write data/”);
printf(“\n file opening mode is incorrect”);
fclose(fp);
exit(1);
}
printf(“continue(Y/N)”);
fflush(stdin);
next=getche();
}
fclose(fp);
}
Explanation: In the above program the fprintf() function fails to write the entered
data to the file. Because it is opened in read mode. Hence, write operation can not be
done. The error generated is caught by the ferror() function and the program
terminates.
d) perror():
It is a standard library function which prints the error message
specified by the compiler. A program is illustrated below for understanding.
Write a program to detect and print the error message using perror()
function.
#include<stdio.h>
#include<conio.h>
#include<process.h>
void main()
{
FILE *fr;
char c,file[]=”lines.txt”;
fr=fopen(file,”w”);
clrscr();
while(!feof(fr))
{
c=fgetc(fr);
if(ferror(fr))
95
{
perror(file);
exit(1);
}
else
printf(“%c”,c);
}
fclose(fr);
}
Explanation: In the above program to print the error message user can use
perror() function instead of printf(). The output of the above program is “lines.txt:
permission Denied”. We can also specify our own message together with the system
error message. In the above example ‘file’ variable prints the file name “lines.txt”
together with compiler’s message “Permission Denied”.
e) ftell():
It is a file function. It returns the current position of the file pointer. It
returns the pointer from the beginning of file.
Write a program to print the curren position of the file pointer in the file
using ftell() function
#include<stdio.h>
#include<conio.h>
void main()
{
FILE *fp;
char ch;
fp=fopen(“text.txt”,”r”);
fseek(fp,21,SEEK_SET);
ch=fgetc(fp);
clrscr();
while(!feof(fp))
{
printf(“%c\t’.ch);
printf(“%d\n”,ftell(fp));
96
ch=fgetc(fp);
}
fclose(fp);
}
Explanation: In the above program fseek() function sets the cursor position on byte
21. The fgetc() function in the while loop reads the character after 21st character. The
ftell() function prints the current pointer position in the file. When feof() function is
found at the end of file, the program terminates.
f) rewind():
This function resets the file pointer at the beginning of the file
g) unlink() or remove():
These functions delete the file in the directory. It is similar to del
command in DOS.
h) rename():
This function changes the name of the given file. It is similar to dos
command renames.
COMMAND LINE ARGUMENTS:
An executable program that performs a specific task for operating system is called
as command. The commands are issued from the prompt of operating system are to be
associated with the commands hence these arguments are called as command line
arguments. These associated arguments are passed to the program.
In C language every program starts with a main() function and that it marks
the beginning of the program. We have not provided any arguments so far in the
main() function. Here, we can make arguments in the main like other functions.
The main() function can receive two arguments and they are 1) argc 2) argv. The
information contained in the command line is passed on to the program through these
arguments when the man() is called up by the system.
1. Arguments argc: An argument argc counts total number of arguments passed from
command prompt. It returns a value which is equal to total number of arguments
passed through the main().
2. Argument argv: It is a pointer to an array of character strings which contains
means of arguments. Each word is an argument.
Example: Copy file1 file2.
Here, file1 and file2 are arguments and copy is a command.
97
The first argument is always an executable program followed by
associated arguments. If you do not specify arguments the first program name itself is
an argument but the program will not run properly and will flag an error.
Write a program to display number of arguments and their names.
#include<stdio.h>
#include<conio.h>
main(int argc,char *argv[])
{
int x;
printf("\nTotal number of arguments are %d\n",argc);
for(x=0;x<argc;x++)
{
printf("%s\t",argv[x]);
}
getch();
}
Explanation: To execute this program one should create its executable file and run
it from the command prompt with required arguments. The above program is
executed using following steps.
a) Compile program.
b) Makes its exe file(executable file).
c) Switch to command prompt (c:\turboc2> )
d) Make sure that the exe file is available in the current directory.
e) Type following bold line.
C:\turboc2> c. exe Hai how are you
In the above example c.exe is an executable file and “Hai how are you” are
taken as arguments. The total number of arguments including the program file
name is 5.
Application of Command Line Arguments:
The following programs can be used on command prompt similar to that of DOS
commands.
98
Type: IN MSDOS this command is used to display contents of file. The
following program shows how it is done.
Del: In MSDOS this command is used to delete file.
Rename: In MSDOS this commands changes the home of a file.
Dynamic memory allocation in C
The concept of dynamic memory allocation in c language enables the C
programmer to allocate memory at runtime. Dynamic memory allocation in c
language is possible by 4 functions of stdlib.h header file.
1. malloc()
2. calloc()
3. realloc()
4. free()
static memory allocation dynamic memory allocation
memory is allocated at compile time. memory is allocated at run time.
memory can't be increased while executing memory can be increased while executing
program. program.
used in array. used in linked list.
Before learning above functions, let's understand the difference between static memory allocation
and dynamic memory allocation.
malloc() allocates single block of requested memory.
calloc() allocates multiple block of requested memory.
realloc() reallocates the memory occupied by malloc() or calloc() functions.
99
free() frees the dynamically allocated memory.
Now let's have a quick look at the methods used for dynamic memory allocation.
malloc() function in C
The malloc() function allocates single block of requested memory.
It doesn't initialize memory at execution time, so it has garbage value initially.
It returns NULL if memory is not sufficient.
The syntax of malloc() function is given below:
ptr=(casttype*)malloc(bytesize)
Let's see the example of malloc() function.
1. #include <stdio.h>
2. #include <stdlib.h>
3. void main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)malloc(n*sizeof(int)); //memory allocated using calloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. }
Output:
Enter number of elements : 3
100
Enter elements of array: 10
10
10
Sum=30
calloc() function in C
The calloc() function allocates multiple block of requested memory.
It initially initializes all bytes to zero.
It returns NULL if memory is not sufficient.
The syntax of calloc() function is given below:
ptr=(casttype*)calloc(number, bytesize)
Let's see the example of calloc() function.
1. #include <stdio.h>
2. #include <stdlib.h>
3. void main(){
4. int n,i,*ptr,sum=0;
5. printf("Enter number of elements: ");
6. scanf("%d",&n);
7. ptr=(int*)calloc(n,sizeof(int)); //memory allocated using calloc
8. if(ptr==NULL)
9. {
10. printf("Sorry! unable to allocate memory");
11. exit(0);
12. }
13. printf("Enter elements of array: ");
14. for(i=0;i<n;++i)
15. {
16. scanf("%d",ptr+i);
17. sum+=*(ptr+i);
18. }
19. printf("Sum=%d",sum);
20. free(ptr);
21. }
101
Output:
Enter elements of array: 3
Enter elements of array: 10
10
10
Sum=30
realloc() function in C
If memory is not sufficient for malloc() or calloc(), you can reallocate the memory by
realloc() function. In short, it changes the memory size.
Let's see the syntax of realloc() function.
ptr=realloc(ptr, newsize)
free() function in C
The memory occupied by malloc() or calloc() functions must be released by calling
free() function. Otherwise, it will consume memory until program exit.
Let's see the syntax of free() function.
free(ptr)
102