C Programming
C Programming
1. C Introduction
Brief Introduction
Simple program with explanation
3. C Data Types
Fundamental Data types
Derived Data types
Qualifiers
6. Operators
Types of Operator
11. Functions
Library Functions
User Defined Functions
Call by value
Call by reference
Yuva Technologies 1
Command line Arguments
Type Casting Functions
12. Array
One Dimensional Array
Multi-Dimensional Array
13. Strings
Strings Functions
14. Pointers
15. Dynamic Memory Allocation
Types of Dynamic Memory Allocation
17. Files
File Operations
Yuva Technologies 2
1. C Introduction
Introduction
The C programming language is a Procedure oriented programming language, developed at Bell
Laboratories in 1972 by Dennis Ritchie
C programming language features were derived from an earlier language called “B” (Basic Combined
Programming Language – BCPL)
C language was invented for implementing UNIX operating system
In 1978, Dennis Ritchie and Brian Kernighan published the first edition “The C Programming
Language”
In 1983, the American National Standards Institute (ANSI) established a committee to provide a
modern, comprehensive definition of C.
1. Problem oriented language or High level language: It will give better programming efficiency, i.e. faster
program development.
Ex: Basic, Pascal, C++, Java
2. Machine oriented language or Low level language: It will give better machine efficiency, i.e. faster
program execution
Ex: Assembly language and Machine language
Yuva Technologies 3
C Basic Program:
#include <stdio.h>
int main()
{
/* Our first simple C basic program */
printf(“Hello World! “);
getch();
return 0;
}
A C program basically consists of the following parts −
1 #include <stdio.h> This is a preprocessor command that includes standard input output header file(stdio.h) from the
C library before compiling a C program
2 int main() This is the main function from where execution of any C program begins.
4 /*_some_comments_*/ Whatever is given inside the command “/* */” in any C program, won’t be considered for
compilation and execution.
5 printf(“Hello World! printf command prints the output onto the screen.
“);
6 getch(); This command waits for any character input from keyboard.
Yuva Technologies 4
2. C Input and Output
Printf and Scanf
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.
printf() function is used to print the “character, string, float, integer, octal and hexadecimal values” onto
the output screen.
We use printf() function with %d format specifier to display the value of an integer variable.
To generate a newline, we use “\n” in C printf() statement.
1. printf("format string",argument_list);
The format string can be %d (integer), %c (character), %s (string), %f (float) etc.
scanf() function
The scanf() function is used for input. It reads the input data from the console.
scanf() function is used to read character, string, numeric data from keyboard
1. scanf("format string",argument_list);
The scanf("%d",&i) statement reads integer number from the console and stores the given value in i variable.
The printf("You entered: %d ",i) statement prints the number on the console.
Yuva Technologies 5
getchar() & putchar() functions
The getchar() function reads a character from the terminal and returns it as an integer. This function
reads only single character at a time. You can use this method in the loop in case you want to read more than
one characters.
The putchar() function prints the character passed to it on the screen and returns the same character.
This function puts only single character at a time. In case you want to display more than one characters, use
putchar() method in the loop.
#include <stdio.h>
#include <conio.h>
void main( )
{
int c;
printf("Enter a character");
c=getchar();
putchar(c);
getch();
}
gets() & puts() functions
The gets() function reads a line from stdin into the buffer pointed to by s until either a terminating
newline or EOF (end of file).
The puts() function writes the string s and a trailing newline to stdout.
#include<stdio.h>
#include<conio.h>
void main()
{
char str[100];
printf("Enter a string");
gets( str );
puts( str );
getch();
}
Yuva Technologies 6
fflush(stdin) in c
the use of fflush(stdin) is to clear the input buffer bcoz when ever we take an input the space is allocated to it
but after its scope gets over, the input is removed but the space allocated is as it is. it can be used only by using
headerfile
#include <stdio.h>
int main()
{
int i;
char c;
printf("Enter the value:");
scanf("%d",&i);
fflush (stdin);
printf("Enter Charecter:");
scanf("%c",&c);
printf("Num=%d\n",i);
printf("Char=%c",c);
return 0;
}
#include <stdio.h>
int main()
{
int i;
char c[12];
float j;
printf("Enter the roll_no:");
scanf("%d",&i);
fflush (stdin);
printf("Enter Name:");
gets(c);
printf("Enter Marks:");
scanf("%f",&j);
printf("Roll_no=%d\n",i);
printf("Name=");
puts(c);
printf("Marks=%.2f",j);
return 0;
}
Yuva Technologies 7
Assignment
Write a function that prompts for a name (up to 20 Characters) and address (up to 30 characters) and accepts
them one at a time. Finally the name and address are displayed in the following way.
Hello,
Your name is:
(name)
Your address is:
(address)
3. C Data Types
Data types in C
Data types are the keywords, which are used for assigning a type to a variable.
A data type specifies the type of data that a variable can store such as integer, floating, character etc.
Data types will allocate some byte of memory for their variables.
Yuva Technologies 8
“int” keyword is used to refer integer data type.
The storage size of int data type is 2 or 4 or 8 byte.
It varies depend upon the processor in the CPU that we use. If we are using 16 bit processor, 2 byte (16
bit) of memory will be allocated for int data type.
Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory for 64 bit
processor is allocated for int datatype.
If you want to use the integer value that crosses the above limit, you can go for “long int” and “long long
int” for which the limits are very high.
The following table provides the details of standard integer types with their storage sizes and value
ranges −
Type Storage size Value range
Yuva Technologies 9
2. double:
Double data type is also same as float data type which allows up-to 10 digits after decimal.
The range for double datatype is from 1E–37 to 1E+37.
The following table provide the details of standard floating-point types with storage sizes and value
ranges and their precision −
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a;
char b;
float c;
double d;
printf("Storage size for int data type:%d \n",sizeof(a));
printf("Storage size for char data type:%d \n",sizeof(b));
printf("Storage size for float data type:%d \n",sizeof(c));
printf("Storage size for double data type:%d\n",sizeof(d));
return 0;
}
Yuva Technologies 10
3. Derived data type in C:
Array, pointer, structure and union are called derived data type in C language.
We will see this in next topics: “C – Array“ , “C – Pointer” , “C – Structure” and “C – Union”
Qualifiers
Qualifiers alter the meaning of base data types to yield a new data type.
Size qualifiers:
Size qualifiers alter the size of basic data type. The keywords long and short are two size qualifiers.
For example:
long int i;
The size of int is either 2 bytes or 4 bytes but, when long keyword is used, that variable will be either
4 bytes of 8 bytes. If the larger size of variable is not needed then, short keyword can be used in
similar manner as long keyword.
Sign qualifiers:
Yuva Technologies 11
Whether a variable can hold only positive value or both values is specified by sign qualifiers.
Keywords signed and unsigned are used for sign qualifiers.
unsigned int a;
// unsigned variable can hold zero and positive values only
%u Unsigned Integer
It is not necessary to define variable using keyword signed because, a variable is signed by default.
Sign qualifiers can be applied to only int and char data types. For a int variable of size 4 bytes it can
hold data from -2 31 to 2 31 -1 but, if that variable is defined unsigned, it can hold data from 0 to 2 32 -1.
Constant qualifiers
Constant qualifiers can be declared with keyword const. An object declared by const cannot be
modified.
const int p=20;
The value of p cannot be changed in the program.
Yuva Technologies 12
4. Keyword and Identifiers
C tokens:
C tokens are the basic buildings blocks in C language which are constructed together to write a C
program.
Each and every smallest individual units in a C program are known as C tokens.
C tokens are of six types. They are,
Keywords in C
A keyword is a reserved word used in programming. Each keywords has fixed meaning and that cannot
be changed by user.
As, C programming is case sensitive, all keywords must be written in lowercase. Here is the list of all
keywords predefined by ANSI C.
Yuva Technologies 13
Keywords in C Language
Do If static While
Identifiers
Identifiers is a user defined name.
In C programming, identifiers are names given to C entities, such as variables, functions, structures etc.
Identifier are created to give unique name to C entities to identify it during the execution of program. For
example:
int money;
int mango_tree;
Here, money is a identifier which denotes a variable of type integer. Similarly, mango_tree is another identifier,
which denotes another variable of type integer.
Yuva Technologies 14
5. Constants and Variables
Variables
Variables are memory location in computer's memory to store data. To indicate the memory location,
each variable should be given a unique name called identifier. Variable names are just the symbolic
representation of a memory location. Examples of variable name: sum, car_no, count etc.
Example:
int num;
Here, num is a variable of integer type.
Rules for naming C variable:
1. Variable name must begin with letter or underscore.
2. Variables are case sensitive
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than underscore.
5. sum, height, _value are some examples for variable name
1. Local variable in C:
Local variables are declared inside a function, and can be used only inside that function.
Yuva Technologies 15
#include<stdio.h>
int main()
{
int m = 22, n = 44; // m, n are local variables of main function
printf(“\nvalues : m = %d and n = %d”, m, n);
}
2. Global variable in C:
Global variables are declared outside any function, and they can be accessed (used) on any function in the program.
The scope of global variables will be throughout the program. These variables can be accessed from
anywhere in the program.
A global variable (DEF) is a variable which is accessible in multiple scopes.
#include<stdio.h>
int m = 22, n = 44;
int main()
{
printf(“All variables are accessed from main function”);
printf(“\nvalues: m=%d:n=%d”, m,n);
return 0;
}
Example 1:
#include <stdio.h>
int main()
{
int m=10;
printf("m=%d\n",m);
{
int n=20;
printf("n=%d\n",n);
}
printf("m=%d,n=%d",m,n);
return 0;
}
Example 2:
#include <stdio.h>
int m=30, n=40;
int main()
{
int m=10;
Yuva Technologies 16
printf("m=%d\n",m);
{
int n=20;
printf("n=%d\n",n);
}
printf("m=%d,n=%d",m, n);
return 0;
}
#include <stdio.h>
int a=20;
int main()
{
int a;
printf("%d\n", a);
return 0;
}
1 Declaration tells the compiler about data type and size Definition allocates memory for the variable.
of the variable.
2 Variable can be declared many times in a program. It can happen only one time for a variable in a
program.
Constants
Constants are the fixed values or terms that can't be changed during the execution of a program.
These fixed values are also called literals.
Syntax: const data_type variable_name; (or) const data_type *variable_name;
For example: 1, 2.5, "Programming is easy." etc. In C, constants can be classified as:
Yuva Technologies 17
1. Integer constants
Integer constants are the numeric constants (constant associated with number) without any
fractional part or exponential part. There are three types of integer constants in C language: decimal
constant (base 10), octal constant (base 8) and hexadecimal constant (base 16).
Decimal digits: 0 1 2 3 4 5 6 7 8 9
Octal digits: 0 1 2 3 4 5 6 7
Hexadecimal digits: 0 1 2 3 4 5 6 7 8 9 A B C D E F.
For example:
Notes:
1. You can use small caps a, b, c, d, e, f instead of uppercase letters while writing a hexadecimal
constant.
2. Every octal constant starts with 0 and hexadecimal constant starts with 0x in C programming.
2. Floating-point constants
Floating point constants are the numeric constants that has either fractional form or exponent form.
For example:
-2.0
0.0000234
-0.22E-5
int main()
{
float f;
f=-0.22E-5;
printf("F=%f",f);
return 0;
}
Yuva Technologies 18
3. Character constants
Character constants are the constant which use single quotation around characters. For example: 'a', 'l',
'm', 'F' etc.
Escape Sequences
Escape Sequences
\b Backspace
\n Newline
\r Return
\t Horizontal tab
\\ Backslash
4. String constants
String constants are the constants which are enclosed in a pair of double -quote marks. For example:
5. Enumeration constants
Keyword enum is used to declare enumeration types. For example:
enum color {yellow, green, black, white};
Here, the variable name is color and yellow, green, black and white are the enumeration constants
having value 0, 1, 2 and 3 respectively by default.
Yuva Technologies 19
1. Example program using const keyword in C:
#include <stdio.h>
void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
const char backslash_char = '\?'; /*special char cnst*/
printf("value of height :%d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
}
Yuva Technologies 20
6. Operators
C Operators
Types of C operators:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
1. Arithmetic Operators in C:
C Arithmetic operators are used to perform mathematical calculations like addition, subtraction,
multiplication, division and modulus in C programs.
Yuva Technologies 21
printf("a/b=%d\n",c);
c=a%b;
printf("Remainder when a divided by b=%d\n",c);
return 0;
}
2. Assignment Operators
The most common assignment operator is =. This operator assigns the value in right side to the left
side. For example:
= a=b a=b
+= a+=b a=a+b
-= a-=b a=a-b
*= a*=b a=a*b
/= a/=b a=a/b
%= a%=b a=a%b
Yuva Technologies 22
# include <stdio.h>
int main()
{
int a=10,b=20;
a+=b;
printf("a=%d\n",a);
a-=b;
printf("a=%d",a);
return 0;
}
3. Relational Operator
Relational operator’s checks relationship between two operands. If the relation is true, it returns value
1 and if the relation is false, it returns value 0. For example:
a>b
Here, > is a relational operator. If a is greater than b, a>b returns 1 if not then, it returns 0.
Relational operators are used in decision making and loops in C programming.
Example1:
#include <stdio.h>
int main()
{
int m=40,n=20,z;
z=m > n;
{
printf("Z=%d",z);
}
return 0;
}
Yuva Technologies 23
Example2:
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf(“m and n are equal”);
}
else
{
printf(“m and n are not equal”);
}
}
4. Logical Operators
Logical operators are used to combine expressions containing relation operators. In C, there are 3
logical operators:
#include <stdio.h>
int main() {
int a = 6;
int b = 2;
int c = 0;
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;
printf("Line 3 - Value of c is %d\n", c );
c = ~a;
printf("Line 4 - Value of c is %d\n", c );
c = a << 1;
Yuva Technologies 25
printf("Line 5 - Value of c is %d\n", c );
c = a >> 1;
printf("Line 6 - Value of c is %d\n", c );
return 0;
}
6. Conditional Operator
Conditional operator takes three operands and consists of two symbols ? and : Conditional operators
are used for decision making in C. For example:
Yuva Technologies 26
#include<stdio.h>
int main(){
int c=2,d=2;
printf("%d\n",c++);
printf("%d",++c);
return 0;
}
8. Special Operators in C:
S.no Operators Description
1 & This is used to get the address of the variable.
Example : &a will give address of a.
2 * This is used as pointer to a variable.
Example : * a where, * is pointer to the variable a.
3 Sizeof () This gives the size of the variable.
Example: size of (char) will give us 1.
In this program, “&” symbol is used to get the address of the variable and “*” symbol is used to get the
value of the variable that the pointer is pointing to. Please refer C – pointer topic to know more about
pointers.
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
ptr = &q; /* address of q is assigned to ptr */
printf(“%d”, *ptr); /* display q’s value using ptr variable */
return 0;
}
Yuva Technologies 27
3. Program to show swap of two no’s without using third variable
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:
if(expression){
//code to be executed
}
Flowchart of if statement in C
#include<stdio.h>
void main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
}
Yuva Technologies 28
C if...else statement
The if...else statement is used if the programmer wants to execute some statement/s when the test
expression is true and execute some other statement/s if the test expression is false.
1. if(expression){
2. //code to be executed if condition is true
3. }else{
4. //code to be executed if condition is false
5. }
Yuva Technologies 29
Example: Program to Check Alphabet or Not
#include <stdio.h>
int main()
{
char c;
printf("Enter a character: ");
scanf("%c",&c);
if( (c>='a' && c<='z') || (c>='A' && c<='Z'))
printf("%c is an alphabet.",c);
else
printf("%c is not an alphabet.",c);
return 0;
}
Yuva Technologies 30
Example 3: C nested if else statement
Write a C program to relate two integers entered by user using = or > or < sign.
#include<stdio.h>
int main(){
int numb1, numb2;
printf("Enter two integers to check\n");
scanf("%d %d",&numb1,&numb2);
if(numb1==numb2) //checking whether two integers are equal.
printf("Result: %d = %d",numb1,numb2);
else
if(numb1>numb2) //checking whether numb1 is greater than numb2.
printf("Result: %d > %d",numb1,numb2);
else
printf("Result: %d > %d",numb2,numb1);
return 0;
}
Yuva Technologies 31
8. Loop Control Statements
C Programming Loops
Loops cause program to execute the certain block of code repeatedly until test condition is false.
Consider these scenarios:
You want to execute some code/s 100 times.
You want to execute some code/s certain number of times depending upon input from user.
These types of task can be solved in programming using loops.
There are 3 types of loops in C programming:
1. for loop
2. while loop
3. do...while loop
1. for loop in C
It iterates the code until condition is false. Here, initialization, condition and increment/decrement is
given before the code. So code may be executed 0 or more times.
Yuva Technologies 32
Example of for loop in C language
Let's see the simple program of for loop that prints table of 1.
#include <stdio.h>
void main(){
int i=0;
for(i=1;i<=10;i++){
printf("%d \n",i);
}
}
1. main()
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",i);
}
printf("\n");
}
}
Yuva Technologies 33
2. while loop in C
Loops causes program to execute the certain block of code repeatedly until some conditions are
satisfied
The syntax of while loop in c language is given below:
1. while(condition){
2. //code to be executed
3. }
Flowchart of while loop in C
#include<stdio.h>
int main(){
int number,factorial;
printf("Enter a number.\n");
scanf("%d",&number);
factorial=1;
while(number>0){/* while loop continues util test condition number>0 is true */
Yuva Technologies 34
factorial=factorial*number;
--number;
}
printf("Factorial=%d",factorial);
return 0;
}
1. Write a function that accept 5 characters and at the end, displays the smallest and the largest of all
characters.
main ()
{
int i = 0;
char chr, max, min;
printf("Enter a character : ");
chr = getchar();
fflush (stdin);
max = min = chr; /* set max and min to first character input */
while (i < 4)
{ printf ("Enter a character : ");
chr = getchar();
fflush (stdin);
if (chr > max)
max = chr;
if (chr < min)
min = chr;
i =i + 1;
}
printf("smallest character : "),
putchar(min);
putchar ('\n') ;
printf ("largest character : ");
putchar(max);
putchar('\n');
}
do while loop in C
To execute a part of program or code several times, we can use do-while 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 lease one
time. In other words, we can say it is executed 1 or more times.
Yuva Technologies 35
do while loop syntax
The syntax of C language do-while loop is given below:
1. do{
2. //code to be executed
3. }while(condition);
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>
void main(){
int i=1;
do{
printf("%d \n",i);
i++;
}while(i<=10);
}
Yuva Technologies 36
2. Write a program, which allows the user to enter characters until the input is ‘0’. Each time a
character is entered, the program should display whether it is greater/lesser than or equal to the
previous character entered.
main ()
{
char ch, prev;
int i = 0;
do
{
printf("Enter a character : ");
ch = getchar();
fflush(stdin);
if (i == 0)
i = i + 1;
else /* do this only from second character */
{
if (ch == prev)
puts("new character is equal to previous character");
else if (ch > prev)
puts("new character is greater than previous character");
else
puts("new character is lesser than previous character");
}
prev = ch;
} while ( ch != '0');
}
Assignment:
Write a function to accept twenty characters from the character set, and to display whether the number of lower-
case character is greater than, less than, or equal to number of upper-case characters. Display an error message
if the input is not an alphabet.
Yuva Technologies 37
The Infinite Loop
A loop becomes an infinite loop if a condition never becomes false. The for loop is traditionally used for this
purpose. Since none of the three expressions that form the 'for' loop are required, you can make an endless loop
by leaving the conditional expression empty.
#include <stdio.h>
int main () {
for( ; ; ) // When the conditional expression is absent, it is assumed to be true.
{
printf("This loop will run forever.\n");
}
return 0;
}
1. Write a Program to draw a box with a dimension of 10*30(i.e. 10 rows and 30 coloumn)
1. break statement in C:
The break statement in C language is used to break the execution of loop (while, do while and for) and switch
case.
Syntax of break statement
break;
The break statement can be used in terminating all three loops for, while and do...while loops.
The figure below explains the working of break statement in all three type of loops.
Yuva Technologies 38
Example of break statement
Write a C program to find average of maximum of n positive numbers entered by user. But, if
the input is negative, display the average (excluding the average of negative input) and end the
program.
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs\n");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
break;//for loop breaks if num<0.0
sum=sum+num;
}
average=sum/(i-1);
printf("Average=%.2f",average);
return 0;
}
Yuva Technologies 39
2. Continue Statement
Continue statement is used to continue the next iteration of for loop, while loop and do-while loops.
It is sometimes desirable to skip some statements inside the loop. In such cases, continue statements
are used.
Syntax of continue Statement
continue;
For better understanding of how continue statements works in C programming. Analyze the figure
below which bypasses some code/s inside loops using continue statement.
Yuva Technologies 40
3. switch case statement in C:
The switch statement in C language is used to execute the code from multiple conditions.
Switch case statements are used to execute only specific case statements based on the switch expression.
Below is the syntax for switch case statement.
switch (expression)
{
case label1: statements;
break;
case label2: statements;
break;
default: statements;
break;
}
Yuva Technologies 41
The break statement at the end of each case cause switch statement to exit. If break statement is not
used, all statements below that case statement are also executed.
Example: Program to accept a number from 0 to 9, along with a string. The string should then
be displayed the number of times specified.
main ()
{
char str [15], inp;
puts ("Enter number of times to display a string (0 to 9)");
inp = getchar (); fflush (stdin);
puts ("Enter string to display");
gets (str);
switch (inp)
{
case '9' : puts (str);
case '8' : puts (str);
case '7' : puts (str);
case '6' : puts (str);
case '5' : puts (str);
case '4' : puts (str);
case '3' : puts (str);
case '2' : puts (str);
case '1' : puts (str);
case '0' : break;
}
}
Write a program to display the following menu and accept a choice number. If an invalid choice is
entered then an appropriate error message must be displayed, else the choice number entered must be
displayed.
Menu
1.Create a Directory
2.Delete a Directory
3.Show a Directory
4.Exit
Your Choice:
4. goto statement in C:
goto statements is used to transfer the normal flow of a program to the specified label in the program.
Below is the syntax for goto statement in C.
Yuva Technologies 42
Syntax of goto statement
goto label;
.............
.............
.............
label:
statement;
In this syntax, label is an identifier. When, the control of program reaches to goto statement, the
control of the program will jump to the label: and executes the code below it.
# include <stdio.h>
int main(){
float num,average,sum;
int i,n;
printf("Maximum no. of inputs: ");
scanf("%d",&n);
for(i=1;i<=n;++i){
printf("Enter n%d: ",i);
scanf("%f",&num);
if(num<0.0)
goto jump;/* control of the program moves to label jump */
sum=sum+num;
}
jump:
average=sum/(i-1);
printf("Average: %.2f",average);
return 0;
}
Yuva Technologies 43
10. Storage Class Specifiers
Storage class specifiers in C language tells the compiler where to store a variable, how to store the
variable.
There are 4 types of storage class:
1. automatic
2. external
3. static
4. register
Automatic variables
A variable declared inside a function without any storage class specification, is by default an automatic variable.
They are created when a function is called and are destroyed automatically when the function exits.
void main()
{
int detail;
or
auto int detail; //Both are same
}
External Variable
An external variable is a variable defined outside any function block.
Example 1:
extern int var;
int main()
{
printf("Hello");
return 0;
}
Analysis: This program is compiled successfully. Here var is declared only. Notice var is never used so no
problems.
Example 2:
extern int var;
int main()
{
var = 10;
printf("%d",var);
return 0;
}
Analysis: This program throws error in compilation. Because var is declared but not defined anywhere.
Essentially, the var isn’t allocated any memory. And the program is trying to change the value to 10 of a
variable that doesn’t exist at all.
Example 3:
extern int var = 0;
int main()
{
var = 10;
printf("%d",var);
return 0;
}
Yuva Technologies 45
Analysis: Guess this program will work? Well, here comes another surprise from C standards. They say that..if
a variable is only declared and an initializer is also provided with that declaration, then the memory for that
variable will be allocated i.e. that variable will be considered as defined. Therefore, as per the C standard, this
program will compile successfully and work.
So that was a preliminary look at “extern” keyword in C.
int number;
void main()
{
number=10;
}
fun1()
{
number=20;
}
fun2()
{
number=30;
}
Here the global variable number is available to all three functions.
Static variables
A static variable tells the compiler to persist the variable until the end of program.
static is initialized only once and remains into existence till the end of program. A static variable can either be
internal or external depending upon the place of declaraction.
They are assigned 0 (zero) as default value by the compiler.
void test();
main()
{
test();
test();
test();
}
void test()
{
static int a = 0; //Static variable
a = a+1;
printf("%d\t",a);
}
Yuva Technologies 46
Example 2:
void staticDemo()
{
static int i;
{
static int i = 1;
printf("%d ", i);
i++;
}
printf("%d\n", i);
i++;
}
int main()
{
staticDemo();
staticDemo();
}
Register variable
A register declaration is equivalent to an auto declaration, Register variable inform the compiler to store the
variable in register instead of memory. Register variable has faster access than normal variable. Frequently used
variables are kept in register. Only few variables can be placed inside register.
NOTE: We can never get the address of such variables.
Syntax:
register int number;
#include <stdio.h>
#include <stdlib.h>
int main()
{
register int i = 10;
int *p = &i; //error: address of register variable requested
Yuva Technologies 47
11. Functions
1. WHAT IS C FUNCTION?
2. USES OF C FUNCTIONS:
C functions are used to avoid rewriting same logic/code again and again in a program.
There is no limit in calling C functions to make use of same functionality wherever required.
We can call functions any number of times in a program and from any place in a program.
A large C program can easily be tracked when it is divided into functions.
The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve the
functionality and to improve understandability of very large C programs.
3. Advantage of functions in C
There are many advantages of functions.
1) Code Reusability:
Writing functions avoids rewriting the same code over and over.
2) Code optimization:
Using functions it becomes easier to write programs and keep track of what they are doing. If the operation of a
program can be divided into separate activities, and each activity placed in a different function, then each
could be written and checked more or less independently.
4. Types of C functions
There are two types of functions in C programming:
Library function
User defined function
1. Library function
The standard library functions are built-in functions in C programming to handle tasks such as mathematical
computations, I/O processing, string handling etc.
These functions are defined in the header file. When you include the header file, these functions are available
for use. For example:
Yuva Technologies 48
The printf() is a standard library function to send formatted output to the screen (display output on the screen).
This function is defined in "stdio.h" header file.
There are other numerous library functions defined under "stdio.h", such as scanf(), fprintf(), getchar() etc.
Once you include "stdio.h" in your program, all these functions are available for use.
int main()
{
Yuva Technologies 49
char c;
c='5';
printf("Result when numeric character is passed: %d", isdigit(c));
c='+';
printf("\nResult when non-numeric character is passed: %d", isdigit(c));
return 0;
}
#include <stdio.h>
#include <math.h>
int main(){
int num;
float squareRoot;
printf("Enter a number: ");
scanf("%d",&num);
squareRoot = sqrt(num);
printf("Square root of %d=%.2f ",num,squareRoot);
return 0;
}
Yuva Technologies 50
S.no C function aspects Syntax
return_type function_name ( arguments list )
1 function definition { Body of function; }
2 function call function_name ( arguments list );
3 function declaration return_type function_name ( argument list );
OR
Yuva Technologies 51
Passing arguments to a function
In programming, argument refers to the variable passed to the function. In the above example, two
variables n1 and n2 are passed during function call.
The parameters a and b accepts the passed arguments in the function definition. These arguments are called
formal parameters of the function.
Yuva Technologies 52
Arguments that are passed in function call and arguments that are accepted in function
definition should have same data type.
A function can be called with or without an argument.
If you have grasped the concept of ‘calling’ a function you are prepared for a call to more than one
function. Consider the following example:
main( )
{
printf ( "\nI am in main" ) ;
Mysore( ) ;
Mandya( ) ;
Banglore( ) ;
}
void Mysore ( )
{
printf ( "\nI am in Mysore " ) ;
}
void Mandya ( )
{
printf ( "\nI am in Mandya " ) ;
}
void Banglore ( )
{
printf ( "\nI am in Banglore " ) ;
}
Example:
main( )
{
printf ( "\nI am in main" ) ;
Mysore( ) ;
}
void Mysore ( )
Yuva Technologies 53
{
printf ( "\nI am in Mysore " ) ;
Mandya( ) ;
}
void Mandya ( )
{
printf ( "\nI am in Mandya " ) ;
Banglore( ) ;
}
void Banglore ( )
{
printf ( "\nI am in Banglore " ) ;
}
Return Statement
The return statement terminates the execution of a function and returns a value to the calling function.
The program control is transferred to the calling function after return statement.
Return statement is used for returning a value from function definition to calling function.
Syntax of return statement
return (expression);
For example:
return a;
return (a+b);
There is no restriction on the number of return statements that may be present in a function. Also, the
return statement need not always be present at the end of the called function. The following program
illustrates these facts.
Yuva Technologies 54
Example : Function that return some value
#include<stdio.h>
#include<conio.h>
int larger(int a,int b); // function declaration
void main()
{
int i,j,k;
clrscr();
i=99;
j=112;
k=larger(i,j); // function call
printf("%d",k);
getch();
}
int larger(int a,int b) // function declaration
{
if(a>b)
return a;
else
return b;
}
int main(){
char s;
s=fun();
printf("%c",s);
}
int fun( )
{
char ch ;
printf ( "\nenter any alphabet " ) ;
scanf ( "%c", &ch ) ;
if ( ch >= 65 && ch <= 90 )
return ( ch ) ;
else
return ( ch + 2 ) ;
}
A function can return only one value at a time. Thus, the following statements are invalid.
return ( a, b ) ;
return ( x, 12 ) ;
Yuva Technologies 55
Calling Convention
Calling convention indicates the order in which arguments are passed to a function when a function call is
encountered. There are two possibilities here:
Arguments might be passed from left to right.
Arguments might be passed from right to left.
1. CALL BY VALUE:
In call by value, original value is not modified.
In call by value method, the value of the variable is passed to the function as parameter.
The value of the actual parameter can not be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is
copied to formal parameter.
Note:
Actual parameter – This is the argument which is used in function call.
Formal parameter – This is the argument which is used in function definition
Let's try to understand the concept of call by value in c language by the example given below:
#include <stdio.h>
void change(int num) {
printf("Before adding value inside function num=%d \n",num);
num=num+100;
printf("After adding value inside function num=%d \n", num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(x);//passing value in function
printf("After function call x=%d \n", x);
Yuva Technologies 56
return 0;
}
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=100
2. CALL BY REFERENCE:
In call by reference, original value is modified because we pass reference (address).
In call by reference method, the address of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used by both parameters.
Let's try to understand the concept of call by reference in c language by the example given below:
#include <stdio.h>
void change(int *num) {
printf("Before adding value inside function num=%d \n",*num);
(*num) += 100;
printf("After adding value inside function num=%d \n", *num);
}
int main() {
int x=100;
printf("Before function call x=%d \n", x);
change(&x);//passing reference in function
printf("After function call x=%d \n", x);
return 0;
}
Output
Before function call x=100
Before adding value inside function num=100
After adding value inside function num=200
After function call x=200
Yuva Technologies 57
No. Call by value Call by reference
2 Changes made inside the function is Changes made inside the function is reflected outside the function
not reflected on other functions also
3 Actual and formal arguments will be Actual and formal arguments will be created in same memory
created in different memory location location
Yuva Technologies 58
int function ( int ); // function declaration
function ( a ); // function call
with arguments and with int function( int a ) // function definition
1 return values {statements; return a;}
void function ( int ); // function declaration
function( a ); // function call
with arguments and without void function( int a ) // function definition
2 return values {statements;}
void function(); // function declaration
function(); // function call
without arguments and without void function() // function definition
3 return values {statements;}
int function ( ); // function declaration
function ( ); // function call
without arguments and with int function( ) // function definition
4 return values {statements; return a;}
Note:
If the return data type of a function is “void”, then, it can’t return any values to the calling function.
If the return data type of the function is other than void such as “int, float, double etc”, then, it can return
values to the calling function.
Yuva Technologies 59
else
printf("%d is prime",num);
}
Yuva Technologies 61
C Programming Recursion
When function is called within the same function, it is known as recursion in C. The function which calls the
same function, is known as recursive function.
A function that calls itself, and doesn't perform any task after function call, is know as tail recursion. In tail
recursion, we generally call the same function with return statement. An example of tail recursion is given
below.
Yuva Technologies 62
if(n==0)
return n;
else
return n+sum(n-1);/*self call to function sum() */
}
Output
Enter a positive integer:
5
15
For better visualization of recursion in this example:
sum(5)
=5+sum(4)
=5+4+sum(3)
=5+4+3+sum(2)
=5+4+3+2+sum(1)
=5+4+3+2+1+sum(0)
=5+4+3+2+1+0
=5+4+3+2+1
=5+4+3+3
=5+4+6
=5+10
=15
Every recursive function must be provided with a way to end the recursion. In this example when, n is
equal to 0, there is no recursive call and recursion ends.
int main()
{
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n >= 1)
return n*multiplyNumbers(n-1);
else
Yuva Technologies 63
return 1;
}
convert(z)
{
return z-32; /* 32 less from z for ASCII value of uppercase */
}
Syntax :
int main( int argc, char *argv[])
Here argc counts the number of arguments on the command line and argv[ ] is a pointer array which holds
pointers of type char which points to the arguments passed to the program.
Note:
It is best practice to convert lower data type to higher data type to avoid data loss.
Data will be truncated when higher data type is converted to lower. For example, if float is converted to int,
data which is present after decimal point will be lost.
Type Conversion in C
A type cast is basically a conversion from one type to another. There are two types of type conversion:
1.Implicit Type Conversion Also known as ‘automatic type conversion’.
Done by the compiler on its own, without any external trigger from the user.
Yuva Technologies 65
Generally takes place when in an expression more than one data type is present. In such condition type
conversion (type promotion) takes place to avoid lose of data.
All the data types of the variables are upgraded to the data type of the variable with largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
It is possible for implicit conversions to lose information, signs can be lost (when signed is implicitly converted
to unsigned), and overflow can occur (when long long is implicitly converted to float).
Example of Type Implicit Conversion:
// An example of implicit conversion
#include<stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
Output:
x = 107, z = 108.000000
2. Explicit Type Conversion– This process is also called type casting and it is user defined. Here the user can
type cast the result to make it of a particular data type.
The syntax in C:
(type) expression
Type indicated the data type to which the final result is converted.
Yuva Technologies 66
int main()
{
double x = 1.2;
return 0;
}
C – atof() function
atof() function in C language converts string data type to float data type. Syntax for atof() function is given
below.
double atof (const char* string);
“stdlib.h” header file supports all the type casting functions in C language.
Yuva Technologies 67
12. Array
C Array is a collection of variables belongings to the same data type. You can store group of data of
same data type in an array.
An array is a collection of data that holds fixed number of values of same type. For example: if you want
to store marks of 100 students, you can create an array for it.
float marks[100];
1. One-dimensional arrays
Declaration of an array
data_type array_name[array_size];
For example,
float mark[5];
Elements of an Array
You can access elements of an array by indices.
The maximum number of elements an array can hold depends upon the size of an array. Consider this
code below:
int age[5];
This array can hold 5 integer elements.
Yuva Technologies 68
Initialization of an array in C
It's possible to initialize an array during declaration. For example,
int mark[5] = {19, 10, 8, 17, 9};
Another method to initialize array during declaration:
int mark[] = {19, 10, 8, 17, 9};
Example:
#include <stdio.h>
int main()
{
int i, a[5]={1,2,3,4,5};
for(i=0;i<5;i++)
printf("a[%d]=%d\n",i,a[i]);
return 0;
}
Output:
a[0]=1
a[1]=2
a[2]=3
a[3]=4
a[4]=5
Yuva Technologies 69
Program to Read & Display the marks of 6 sub and calculate average of 6 sub
#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;
/* for loop for receiving inputs from user and storing it in array*/
for (x=0; x<=5;x++)
{
printf("enter the Marks of Subject%d\n", x+1);
scanf("%d", &num[x]);
}
for (x=0; x<=5;x++)
{
printf("Marks of Subject%d=%d\n",x+1,num[x]);
sum = sum+num[x];
}
printf("Sum=%d\n", sum);
avg = sum/6;
printf("Average=%d", avg);
return 0;
}
2. Multidimensional Arrays
In C programming, you can create array of an array known as multidimensional array. For example,
float x[3][4];
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as
table with 3 row and each row has 4 column.
Yuva Technologies 70
You can think this example as: Each 2 elements have 4 elements, which makes 8 elements and each 8 elements
can have 3 elements. Hence, the total number of elements is 24.
Write a C program to find sum of two matrix of order 2*2 using multidimensional arrays where,
elements of matrix are entered by user.
#include<stdio.h>
int main(){
float a[2][2], b[2][2], c[2][2];
int i,j;
printf("Enter the elements of 1st matrix\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("Enter a%d%d: ",i,j);
scanf("%f",&a[i][j]);
}
printf("Enter the elements of 2nd matrix\n");
for(i=0;i<2;++i)
for(j=0;j<2;++j){
printf("Enter b%d%d: ",i,j);
scanf("%f",&b[i][j]);
}
for(i=0;i<2;++i)
for(j=0;j<2;++j){
Sum Of Matrix:
2.2 0.5
-0.9 25.0
int i, j, k, test[2][3][2];
main()
{
char name[5][10];
int i;
for(i=0;i<5;i++)
{
printf(" Enter a name which you want to register\n");
scanf("%s",name[i]);
}
for(i=0;i<5;i++)
{
printf(" Registerd Name%d: ",i+1);
printf("%s\n",name[i]);
}
}
main()
{
Yuva Technologies 74
float avg, marks[] = { 23.4, 55, 22.6, 3, 40.5, 18 };
return 0;
int i;
sum += marks[i];
return avg;
Yuva Technologies 75
13. 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.
Declaration of strings
Strings are declared in a similar manner as arrays. Only difference is that, strings are of chartype.
Using arrays
char s[5];
Using pointers
Strings can also be declared using pointer.
char *p;
Initialization of strings
In C, string can be initialized in a number of different ways.
For convenience and ease, both initialization and declaration are done in the same step.
Using arrays
char c[] = "abcd";
OR,
char c[50] = "abcd";
OR,
char c[] = {'a', 'b', 'c', 'd', '\0'};
OR,
char c[5] = {'a', 'b', 'c', 'd', '\0'};
Yuva Technologies 76
Using pointers
String can also be initialized using pointers as:
char *c = "abcd";
Yuva Technologies 77
ch = getchar();
name[i] = ch;
i++;
}
name[i] = '\0'; // inserting null character at end
printf("Name: %s", name);
return 0;
}
Yuva Technologies 79
Function Work of Function
C strlen() Prototype
size_t strlen(const char *str);
The function takes a single argument, i.e, the string variable whose length is to be found, and returns the length
of the string passed.
The strlen() function is defined in <string.h> header file.
Example: C strcpy()
#include <stdio.h>
#include <string.h>
int main()
{
char str1[10]= "Mandya";
char str2[10];
char str3[10];
strcpy(str2, str1);
strcpy(str3, "Yuva Tech");
puts(str2);
puts(str3);
return 0;
}
Yuva Technologies 81
It is important to note that, the destination array should be large enough otherwise it may result in undefined
behavior.
C strcat() Prototype
char *strcat(char *dest, const char *src)
It takes two arguments, i.e, two strings or character arrays, and stores the resultant concatenated string in the
first string specified in the argument.
The pointer to the resultant string is passed as a return value.
C strcmp() Prototype
int strcmp (const char* str1, const char* str2);
The strcmp() function takes two strings and return an integer.
The strcmp() compares two strings character by character. If the first character of two strings are equal, next
character of two strings are compared. This continues until the corresponding characters of two strings are
different or a null character '\0' is reached.
It is defined in string.h header file.
Return Value from strcmp()
Yuva Technologies 82
Return Value Remarks
Negative if the ASCII value of first unmatched character is less than second.
positive integer if the ASCII value of first unmatched character is greater than second.
#include<stdio.h>
#include<string.h>
int main()
{
char a[100], b[100];
printf("Enter the first string\n");
gets(a);
Yuva Technologies 83
printf("Enter the second string\n");
gets(b);
if( strcmp(a,b) == 0 )
printf("Entered strings are equal.\n");
else
printf("Entered strings are not equal.\n");
return 0;
}
C strlwr() Prototype
strlwr():Converts string to lowercase
C strupr() Prototype
strupr():Converts string to uppercase
Program to Convert String into Uppercase Using Library Function
#include<stdio.h>
#include<string.h>
Yuva Technologies 84
int main() {
char string[100];
printf("Enter String : ");
gets(string);
strupr(string);
printf("String after strupr : %s", string);
return (0);
}
C – strchr() function
strchr( ) function returns pointer to the first occurrence of the character in a given string. Syntax for
strchr( ) function is given below.
char *strchr(const char *str, int character);
Example program for strchr() function in C:
o In this program, strchr( ) function is used to locate first occurrence of the character ‘i’ in the
string ”This is a string for testing”. Character ‘i’ is located at position 3 and pointer is returned at
first occurrence of the character ‘i’.
#include <stdio.h>
#include <string.h>
int main ()
{
char string[55] ="This is a string for testing";
char *p;
p = strchr (string,'i');
C – strstr() function
strstr( ) function returns pointer to the first occurrence of the string in a given string. Syntax for strstr( )
function is given below.
char *strstr(const char *str1, const char *str2);
Yuva Technologies 85
Example program for strstr() function in C:
In this program, strstr( ) function is used to locate first occurrence of the string “test” in the string ”This
is a test string for testing”. Pointer is returned at first occurrence of the string “test”.
#include <stdio.h>
#include <string.h>
int main ()
{
char string[55] ="This is a test string for testing";
char *p;
p = strstr (string,"test");
if(p)
{
printf("string found\n" );
printf ("First occurrence of string \"test\" in \"%s\" is"\
" \"%s\"",string, p);
}
else printf("string not found\n" );
return 0;
}
Output:
string found
First occurrence of string “test” in “This is a test string for testing” is “test string for testing”
Yuva Technologies 86
#define Directive (macro definition)
The C preprocessor is a macro preprocessor (allows you to define macros) that transforms your program
before it is compiled. These transformations can be inclusion of header file, macro expansions etc.
These macro definitions allow constant values to be declared for use throughout your code.
All preprocessing directives begins with a # symbol. For example,
Example
Let's look at how to use #define directives with numbers, strings, and expressions.
Number
The following is an example of how you use the #define directive to define a numeric constant:
#define NUM 10
In this example, the constant named NUM would contain the value of 10.
String
You can use the #define directive to define a string constant.
For example:
#define NAME "Google.com"
In this example, the constant called NAME would contain the value of "Google.com".
Yuva Technologies 87
Example:
#include <stdio.h>
#include <string.h>
#define FOUND 1
#define NOTFOUND 0
main( )
{
char Usernames[6][10] = {
"akash",
"suma",
"ramu",
"srinivas",
"gopal",
"rajesh" } ;
int i, flag, a ;
char name[10] ;
printf ( "\nEnter your name " ) ;
scanf ( "%s", name ) ;
flag = NOTFOUND ;
for ( i = 0 ; i <= 5 ; i++ )
{
a = strcmp ( Usernames[i], name ) ;
if ( a == 0 )
{
printf ( "Welcome %s",name ) ;
flag = FOUND ;
break ;
}
}
if ( flag == NOTFOUND )
printf ( "Please Check Your Username" ) ;
}
Yuva Technologies 88
Predefined Macros
C Program to find the current time
#include <stdio.h>
int main()
{
printf("Current time: %s",__TIME__); //calculate the current time
}
14. Pointers
The pointer in C language is a variable, it is also known as locator or indicator that points to an address of a
value.
C Pointer is a variable that stores/points the address of another variable. C Pointer is used to allocate
memory dynamically i.e. at run time. The pointer variable might be belonging to any of the data type such
as int, float, char, double, short etc.
Where, * is used to denote that “p” is pointer variable and not a normal variable.
Usage of pointer
There are many usage of pointers in c language.
1) Dynamic memory allocation
In c language, we can dynamically allocate memory using malloc() and calloc() functions where pointer is used.
Yuva Technologies 89
Symbols used in pointer
Symbol Name Description
& (ampersand sign) address of operator determines the address of a variable.
Yuva Technologies 90
printf("Address of pointer pc:%d\n",pc);
printf("Content of pointer pc:%d\n\n",*pc);
*pc=2;
printf("Address of c:%d\n",&c);
printf("Value of c:%d\n\n",c);
return 0;
}
Output
Address of c: 2686784
Value of c: 22
Address of c: 2686784
Value of c: 2
int c, *pc;
*pc = &c; // Wrong! *pc is the value pointed by address whereas, %amp;c is an address.
*pc = c; // Correct! *pc is the value pointed by address and, c is also a value.
Yuva Technologies 91
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 );//%x for printing Hexadecimal
return 0;
}
Pointers in Detail
1. Pointer arithmetic
There are four arithmetic operators that can be used in pointers: ++, --, +, -
Incrementing a Pointer
We prefer using a pointer in our program instead of an array because the variable pointer can be incremented,
unlike the array name which cannot be incremented because it is a constant pointer. The following program
increments the variable pointer to access each succeeding element of the array −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr;
ptr = &var; /* let us have array address in pointer */
for ( i = 0; i < MAX; i++) {
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
ptr++; /* move to the next location */
}
return 0;
}
Output:
Address of var[0] = bf882b30
Value of var[0] = 10
Address of var[1] = bf882b34
Value of var[1] = 100
Address of var[2] = bf882b38
Value of var[2] = 200
Yuva Technologies 92
2. Array of pointers
Arrays are closely related to pointers in C programming but the important difference between them is that, a
pointer variable can take different addresses as value whereas, in case of array it is fixed. This can be
demonstrated by an example:
#include <stdio.h>
int main( )
{
int i,val[7] = { 11, 22, 33, 44, 55, 66, 77 } ;
/* for loop to print value and address of each element of array*/
for (i = 0 ; i <= 6 ; i++ )
{
printf("val[%d]: value is %d and address is %u\n", i, val[i], &val[i]);
}
return 0;
}
Output:
val[0]: value is 11 and address is 88820
val[1]: value is 22 and address is 88824
val[2]: value is 33 and address is 88828
val[3]: value is 44 and address is 88832
val[4]: value is 55 and address is 88836
val[5]: value is 66 and address is 88840
val[6]: value is 77 and address is 88844
3. Pointer to Pointer
A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the
address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second
pointer, which points to the location that contains the actual value as shown below.
A variable that is a pointer to a pointer must be declared as such. This is done by placing an additional asterisk
in front of its name. For example, the following declaration declares a pointer to a pointer of type int −
int **var;
#include <stdio.h>
int main () {
int var;
int *ptr;
int **pptr;
var = 3000;
Yuva Technologies 93
ptr = &var; /* take the address of var */
pptr = &ptr; /* take the address of ptr using address of operator & */
/* take the value using pptr */
printf("Value of var = %d\n", var );
printf("Value available at *ptr = %d\n", *ptr );
printf("Value available at **pptr = %d\n", **pptr);
return 0;
}
Output:
Value of var = 3000
Value available at *ptr = 3000
Value available at **pptr = 3000
Yuva Technologies 95
15. Dynamic Memory Allocation
The process of allocating memory at runtime is known as dynamic memory allocation.
Library routines known as "memory management functions" are used for allocating and freeing memory
during execution of a program.
These functions are defined in stdlib.h.
1. malloc()
2. calloc()
3. realloc()
4. free()
Before learning above functions, let's understand the difference between static memory allocation and dynamic
memory allocation.
static memory allocation dynamic memory allocation
memory can't be increased while executing memory can be increased while executing
program. program.
Yuva Technologies 96
Function Description
malloc()
The name malloc stands for "memory allocation". The function malloc() reserves a block of memory
of specified size and return a pointer of type void which can be casted into pointer of any form.
Syntax of malloc()
ptr=(cast-type*)malloc(byte-size)
Here, ptr is pointer of cast-type. The malloc() function returns a pointer to an area of memory with
size of byte size. If the space is insufficient, allocation fails and returns NULL pointer.
ptr=(int*)malloc(100*sizeof(int));
This statement will allocate either 200 or 400 according to size of int 2 or 4 bytes respectively and the
pointer points to the address of first byte of memory.
calloc()
The name calloc stands for "contiguous allocation". The only difference between malloc() and calloc()
is that, malloc() allocates single block of memory whereas calloc() allocates multiple blocks of
memory each of same size and sets all bytes to zero.
Syntax of calloc()
ptr=(cast-type*)calloc(n,element-size);
This statement will allocate contiguous space in memory for an array of n elements. For example:
Yuva Technologies 97
ptr=(float*)calloc(25,sizeof(float));
This statement allocates contiguous space in memory for an array of 25 elements each of size of float,
i.e, 4 bytes.
free()
Dynamically allocated memory with either calloc() or malloc() does not get return on its own. The
programmer must use free() explicitly to release space.
syntax of free()
free(ptr);
This statement cause the space in memory pointer by ptr to be deallocated.
Write a C program to find sum of n elements entered by user. To perform this program, allocate
memory dynamically using malloc() function.
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)malloc(n*sizeof(int));//memory allocated using malloc
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
Yuva Technologies 98
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
Write a C program to find sum of n elements entered by user. To perform this program, allocate memory
dynamically using calloc() function.
#include<stdio.h>
#include<stdlib.h>
int main(){
int n,i,*ptr,sum=0;
printf("Enter number of elements: ");
scanf("%d",&n);
ptr=(int*)calloc(n,sizeof(int));
if(ptr==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements of array: ");
for(i=0;i<n;++i)
{
scanf("%d",ptr+i);
sum+=*(ptr+i);
}
printf("Sum=%d",sum);
free(ptr);
return 0;
}
realloc()
If the previously allocated memory is insufficient or more than sufficient. Then, you can change memory size
previously allocated using realloc().
Syntax of realloc()
Yuva Technologies 99
ptr=realloc(ptr,newsize);
Here, ptr is reallocated with size of newsize.
#include<stdio.h>
#include<stdlib.h>
int main(){
int*ptr,i,n1,n2;
printf("Enter size of array: ");
scanf("%d",&n1);
ptr=(int*)malloc(n1*sizeof(int));
printf("Address of previously allocated memory: ");
for(i=0;i<n1;++i)
printf("%u\t",ptr+i);
printf("\nEnter new size of array: ");
scanf("%d",&n2);
ptr=realloc(ptr,n2);
for(i=0;i<n2;++i)
printf("%u\t",ptr+i);
return 0;
}
Defining structure
The struct keyword is used to define structure. Let's see the syntax to define structure in c.
1. struct structure_name
2. {
3. data_type member1;
4. data_type member2;
5. .
6. .
7. data_type memeberN;
8. };
Here, struct is the keyword, employee is the tag name of structure; id, name and salary are the members or
fields of the structure. Let's understand it by the diagram given below:
2nd way:
Let's see another way to declare variable at the time of defining structure.
struct employee
{ int id;
char name[50];
float salary;
}e1,e2;
If no. of variables are fixed, use 2nd approach. It saves your code to declare variable in main() fuction.
Example of structure
Write a C program to add two distances entered by user. Measurement of distance should be in
inch and feet.(Note: 12 inches = 1 feett)
#include<stdio.h>
struct Distance{
int feet;
float inch;
}d1,d2,sum;
int main(){
printf("1st distance\n");
printf("Enter feet: ");
scanf("%d",&d1.feet);/* input of feet for structure variable d1 */
printf("Enter inch: ");
scanf("%f",&d1.inch);/* input of inch for structure variable d1 */
printf("2nd distance\n");
printf("Enter feet: ");
scanf("%d",&d2.feet);/* input of feet for structure variable d2 */
printf("Enter inch: ");
scanf("%f",&d2.inch);/* input of inch for structure variable d2 */
sum.feet=d1.feet+d2.feet;
sum.inch=d1.inch+d2.inch;
if(sum.inch>12){//If inch is greater than 12, changing it to feet.
++sum.feet;
sum.inch=sum.inch-12;
}
printf("Sum of distances=%d\'-%.1f\"",sum.feet,sum.inch);
C – Typedef
Typedef is a keyword that is used to give a new symbolic name for the existing name in a C program. This
is same like defining alias for the commands.
Here, typedef keyword is used in creating a type comp (which is of type as struct complex). Then,
two structure variables c1 and c2 are created by this comp type.
int main()
{
struct student stud={"Suma",12};
display(stud);
printf("\n\n2nd Output\nName: %s",stud.name);
printf("\nRoll: %d",stud.roll); // passing structure variable stud as argument
return 0;
}
void display(struct student stu){
printf("Enter student's name: ");
scanf("%s", &stu.name);
printf("Enter roll number:");
scanf("%d", &stu.roll);
printf("\n1st Output\nName: %s",stu.name);
printf("\nRoll: %d",stu.roll);
}
Passing structure by reference
The memory address of a structure variable is passed to function while passing it by reference.
If structure is passed by reference, changes made to the structure variable inside function definition reflects in
the originally passed structure variable.
C program to add two distances (feet-inch system) and display the result without the return statement.
#include <stdio.h>
struct distance
{
int feet;
float inch;
};
void add(struct distance d1,struct distance d2, struct distance *d3);
Yuva Technologies 107
int main()
{
struct distance dist1, dist2, dist3;
printf("First distance\n");
printf("Enter feet: ");
scanf("%d", &dist1.feet);
printf("Enter inch: ");
scanf("%f", &dist1.inch);
printf("Second distance\n");
printf("Enter feet: ");
scanf("%d", &dist2.feet);
printf("Enter inch: ");
scanf("%f", &dist2.inch);
//passing structure variables dist1 and dist2 by value whereas passing structure variable dist3 by reference
printf("\nSum of distances = %d\'-%.1f\"", dist3.feet, dist3.inch);
return 0;
}
void add(struct distance d1,struct distance d2, struct distance *d3)
{
//Adding distances d1 and d2 and storing it in d3
d3->feet = d1.feet + d2.feet;
d3->inch = d1.inch + d2.inch;
Like structure, Union in c language is a user defined datatype that is used to hold different type of elements.
But it doesn't occupy sum of all members size. It occupies the memory of largest member only. It shares
memory of largest member.
int main()
{
printf("Enter name:\n");
scanf("%s", &job1.name);
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d", sizeof(uJob));
printf("\nsize of structure = %d", sizeof(sJob));
return 0;
}
Output
size of union = 32
size of structure = 40
File Handling in c language is used to open, read, write, search or close file. It is used for permanent storage.
Advantage of File
It will contain the data even after program exit. Normally we use variable or array to store data, but data is lost
after program exit. Variables and arrays are non-permanent storage medium whereas file is permanent storage
medium.
Types of Files
When dealing with files, there are two types of files you should know about:
1. Text files
2. Binary files
2. Binary files
Binary files are mostly the .bin files in your computer.
Instead of storing data in plain text, they store it in the binary form (0's and 1's).
They can hold higher amount of data, are not readable easily and provides a better security than text
files.
If a large amount of numerical data it to be stored, text mode will be insufficient. In such case binary file
is used.
FILE *ptr;
For Example:
fopen("E:\\cprogram\\newprogram.txt","w");
fopen("E:\\cprogram\\oldprogram.bin","rb");
Let's suppose the file newprogram.txt doesn't exist in the location E:\cprogram. The first function creates
a new file named newprogram.txt and opens it for writing as per the mode 'w'.
The writing mode allows you to create and edit (overwrite) the contents of the file.
File
Meaning of Mode During Inexistence of file
Mode
R Open for reading. If the file does not exist, fopen() returns NULL.
Rb Open for reading in binary mode. If the file does not exist, fopen() returns NULL.
r+ Open for both reading and writing. If the file does not exist, fopen() returns NULL.
Open for both reading and writing in If the file exists, its contents are overwritten. If the file
wb+
binary mode. does not exist, it will be created.
a+ Open for both reading and appending. If the file does not exists, it will be created.
Closing a File
The file (both text and binary) should be closed after reading/writing.
Yuva Technologies 116
Closing a file is performed using library function fclose().
fclose(fptr); //fptr is the file pointer associated with file to be closed.
#include <stdio.h>
int main()
{
int n;
FILE *fptr;
fptr=fopen("C:\\program.txt","w");
if(fptr==NULL){
printf("Error!");
exit(1);
}
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
return 0;
}
#include <stdio.h>
int main()
{
int n;
FILE *fptr;
if ((fptr=fopen("C:\\program.txt","r"))==NULL){
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
fclose(fptr);
return 0;
}
Yuva Technologies 117
Output:
Value of n=10
int main()
{
int n;
FILE *fptr;
fptr=fopen("program.bin","wb");
if(fptr==NULL){
printf("Error!");
exit(1);
}
printf("Enter n: ");
scanf("%d",&n);
fprintf(fptr,"%d",n);
fclose(fptr);
if ((fptr=fopen("program.bin","rb"))==NULL){
printf("Error! opening file");
exit(1); /* Program exits if file pointer returns NULL. */
}
fscanf(fptr,"%d",&n);
printf("Value of n=%d",n);
fclose(fptr);
return 0;
}
#include <stdio.h>
int main ()
{
FILE *fp;
fp = fopen("file.txt","w+");
fputs("This is a File Program", fp);
fp = fopen("file.txt","r");
while(1)
{
c = fgetc(fp);
if( feof(fp) )
{
break;
}
printf("%c", c);
}
fclose(fp);
return(0);
}
Output:
This is C Programming Language
printf("Enter a sentence:\n");
gets(sentence);
fprintf(fptr,"%s", sentence);
fclose(fptr);
return 0;
}
Output
Enter sentence:
I am awesome and so are files.
#include <stdio.h>
#include <stdlib.h> // For exit() function
int main()
{
char c[1000];
FILE *fptr;
Multiple Write
#include<stdio.h>
int main()
{
FILE *fp1, *fp2;
fp1=fopen("file.c", "w");
fp2=fopen("file.c", "w");
fputc('A', fp1);
fputc('B', fp2);
fclose(fp1);
fclose(fp2);
return 0;
}
Write a C program to read name and marks of n number of students from user and store them in a file
#include <stdio.h>
int main(){
char name[50];
int marks,i,n;
printf("Enter number of students: ");
scanf("%d",&n);
FILE *fptr;
fptr=(fopen("student.txt","w"));
Yuva Technologies 121
if(fptr==NULL){
printf("Error!");
exit(1);
}
for(i=0;i<n;++i)
{
printf("For student%d\nEnter name: ",i+1);
scanf("%s",&name);
printf("Enter marks: ");
scanf("%d",&marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n",name,marks);
}
fclose(fptr);
fptr=(fopen("student.txt","r"));
for(i=0;i<n;++i)
{
fscanf(fptr,"\nName: %s \nMarks=%d \n",&name,&marks);
printf("\nDetails of student%d\n",i+1);
printf("Name:%s\n",name);
printf("Marks:%d",marks);
}
return 0;
}
int main()
{
int n;
struct threeNum num;
FILE *fptr;
if ((fptr = fopen("program.bin","rb")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
for(n = 1; n < 5; ++n)
{
fread(&num, sizeof(struct threeNum), 1, fptr);
printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);
}
fclose(fptr);
return 0;
}
Write a C program to write all the members of an array of strcures to a file using fwrite(). Read the
array from the file and display on the screen.
struct s
{
char name[50];
int marks;
};
int main(){
struct s a[10],b[10];
FILE *fptr;
int i,n;