C Programming Sample Questions For Exams and Interviews Useful For Students in Exams and Interviews
C Programming Sample Questions For Exams and Interviews Useful For Students in Exams and Interviews
Published by Rashmi
Version 1.0
Copyright 2020
Author: Rashmi
Preface
The Author is in Computer Science and Engineering teaching
field for Engineering colleges.
During the service when the questions are asked on any sub-topic
of C programming, many students used to get confusion to give the
right answer. The same way they used to get confusion from the
questions raised by the interviewer also for Jobs.
In order to share the knowledge in the form of questions and
show the C program solutions in the form of Kindle book.
The are many C Programming books. In general the students seek
the real programming questions either for their exams or for the job
interviews.
The current version of this kindle book contains the basic syntax
or usage of the C program’s sub-topic with a solved C program for the
students understanding. The programs are tested and the same output
is written in this book.
The reader can right away look into the questions and the answers
with program.
This book will have periodical updates.
Good Luck!
Contents
1. What is Problem Solving?
1.1 What are the Problem Solving Tools?
1.2 What are The Problem Solving Techniques?
1.3 How the Computer Acts as a Problem Solving Tool?
1.4 What are the Programming languages?
1.5 How to Create and Run Programs?
1.6 What is an Algorithm?
1.7 What is a Flowchart?
1.8 What is Top Down Design?
2. How To Write C Program?
2.1 How the Structure of C program look like?
2.3 What are the Basic Data Types?
2.4 What are C Tokens?
2.5 What are Identifiers?
2.6 What are Constants?
2.7 What are Variables?
2.8 What are the Input and Output Statements?
3. What are the Control statements?
3.1 What are the Conditional Statements?
3.1.1 What is Simple if Statement?
3.1.2 What is if else Statement?
3.1.3 What is else-if Statement?
3.1.4 What is Nested if?
3.1.5 What are Multiway Selection Statements Using switch Case?
3.2 What are the Iterative Statements?
3.2.1 What Is The Use Of Looping Using The while Statement?
3.2.2 How to do More Looping Using The do-while Statement?
3.2.3 How to do Still More Looping Using The for Statement?
3.3 What is break Statement?
3.4 What is continue Statement?
3.5 What is goto Statement?
4. What is an Array?
4.1 How to Declare an Array?
4.2 How to Find Elements of Array?
4.3 How to Initialize an Array?
4.4 What are the Different Types of Array?
4.5 What are the Application of Arrays?
5. What is a String?
5.1 How to Declare a String?
5.2 What are String Input and Output functions?
5.3 What are C String Manipulation Operations?
6. What are Functions?
6.1 What are the Different Category of functions?
6.2 What are the Variable Storage Classes?
6.3 What is Recursion?
6.4 What are the Standard Library Functions?
7. What are Pointers?
7.1 What are the Pointers And Function Arguments?
7.2 What is Dangling Memory?
7.3 What are Pointers And Function Arguments?
7.4 What is Pointer to Pointer?
7.5 What is Pointers And Multidimensional Arrays?
7.6 What is Dynamic Memory Management Functions?
8. What is an Enumerated Datatype?
9. What is a Structure?
9.1 How to Initialize a Structure?
9.2 How to Access Structure Members?
9.3 What is a Nested Structure?
9.4 What is Arrays of Structures?
9.5 How to use Structure as Function Arguments?
9.6 How to Use Pointers to Structures?
9.7 What are Self Referential Structures?
10. What is Union?
11. What are File Operations?
11.1 How to Create a File?
11.2 How to do Input/Output Operations in a File?
1. What is Problem Solving ?
1.1 What are the Problem Solving Tools?
In order to solve any problem the following should be done. They are:
1) Problem definition phase
2) Getting started on a problem
3) Use of specific examples
4) Similarities among problem
5) Working backwards from solution
6) General problem-solving strategies
1) Problem definition phase: Initially the problem should be identified from
the given question required by the user.
2) Getting started on a problem: Based on the problem we should identify the
requirements.
3) Use of specific examples: Consider a simple example for the given problem
and solve it.
4) Similarities among problem: Based on the examples identify the
similarities and identify a solution to solve a large number of problems.
5) Working backwards from solution: After identification of the solution we
have to check if it correct or not.
6) General problem-solving strategies: Steps involved in the problem solving
process are shown as following.
2. Input and output indicators : Parallelograms are used to represent input and
output operations. Statements like INPUT, READ and PRINT are represented in
these Parallelograms.
4. Decision Makers: The diamond is used for indicating the step of decision
making and therefore known as decision box. Decision boxes are used to test the
conditions or ask questions and depending upon the answers, the appropriate
actions are taken by the computer. The decision box symbol is
5. Flow Lines: Flow lines indicate the direction being followed in the flowchart.
In a Flowchart, every line must have an arrow on it to indicate the direction. The
arrows may be in any direction
6. On- Page connectors: Circles are used to join the different parts of a
flowchart and these circles are called on-page connectors. The uses of these
connectors give a neat shape to the flowcharts. Ina complicated problems, a
flowchart may run in to several pages. The parts of the flowchart on different
pages are to be joined with each other. The parts to be joined are indicated by the
circle.
7. Off-page connectors: This connector represents a break in the path of
flowchart which is too large to fit on a single page. It is similar to on-page
connector. The connector symbol marks where the algorithm ends on the first
page and where it continues on the second.
EXAMPLE 2: Draw flowchart to find the largest among three different numbers
entered by user.
Fig. 1.3: Flowchart to find the largest among three different numbers entered by user
1. Type
2. Size
Question: What are the different data types?
Answer: There are five data types
Primary data types include integer data type, floating point data type and
character data types.
Integer Data Type:
Keyword: int
Memory size : 2 bytes
Range: -215 to -215 -1
Signed: -32,768 to 32,767
Control String: %d
Unsigned: 0 to 216 -1: 0 to 65,535
Floating Point Data Type:
Keyword: float
Memory rage: 4 bytes (32) bits
Range: -3276999 to 3276998
Control String: %f
Character Data Type:
Keyword: char
Memory Size: 1 byte
Range: -128 to 127 (ASCII code)
Control String: %c
Note: every character should denote between in single quotations (‘a’)
ASCII: The American Standard Code for Information Interchange (ASCII) is a
character-encoding scheme based on the ordering of the English alphabet. ASCII
codes represent text in computers, communications equipment, and other devices
that use text. Most modern character-encoding schemes are based on ASCII,
though they support many more characters than ASCII does.
For example ASCII code for character A is 65.
1. Integer Constant:
Integer constants again classified into three types
1. Decimal integer
2. Octal integers
3. Hexa decimal integer
Decimal integer :
An integer value with base 10 is called decimal integer.
This integer value consists of digits from 0 to 9.
This integer is prefix with 1-9 sign(+/-)
Valid decimal integers are 100, 456, -345, 23456, -19202 etc.
Octal integers:
An integer value with base 8 is called octal integer.
This integer value consists of digits from 0 to 7.
This integer is prefix with ‘0’
Ex: 0123, 0725 …etc are the valid octal integers.
Ex: 0128, 4647……etc are the invalid octal integers.
Hexa decimal integer:
An integer value with base 16 is called Hexa decimal integer.
This integer value consists of digits from 0 to9 and A-F or a-f.
This integer value is prefix with “ox”
Ex: 1ab - invalid
Ox1ab - valid
2. Real constants:
Real constants are also called as floating point constants.
Real constants are having both decimal and fractional parts.
Alpha numeric constants:
Character constants again classified into two types.
Note : one variable contain only one value. If you change the value of the
variable then old value will be erased and new value will be stored.
scanf ():-
✓ Scanf function is a predefined function by using scanf() function we can
read the data at run time.
✓ Scanf function returning an integer value i.e. total number of scanned
values.
✓ The complete behavior of scanf() function will depends on format
specifying only but not on argument list.
✓ When we working with scanf() function if you not provide ampersand to
the argument then scanf() will read the values but those not stored in
memory.
Syntax:
scanf (‘’format string ‘’, & (variables));
Example:
scanf (‘’%d %d ‘”, &a,& b);
3. What are the Control statements ?
3.1 What are the Conditional Statements?
Question: What are Selection statements?
Answer:
These statements are also called ‘Branching Statements or conditional
statements. Because they are used to transfer control from one statement to
another statement.
Conditional statements are mainly classified into two types they are
1) if statements
2) switch statement.
3.1.1 What is Simple if Statement?
“C” uses the keyword “if” to implement the decision control statement or
instructions. The general form of its statement looks like is
Syntax:
if (condition)
{
Statements 1;
Statements n;
}
Flow chart for if condition
Question #1: Write a program to print the given value is even or odd.
PROGRAM:
//Program to print the given value is even or odd
#include<stdio.h>
#include<conio.h>
void main()
{
int a;
clrscr();
printf("enter a value=");
scanf("%d", &a);
if(a%2==0)
{
printf("a is even ", a );
}
else
{
printf("a is odd", a);
}
getch();
}
OUTPUT:
enter a value=50
a is even
Question: Write a C program using a nested for loop to find the prime
numbers from 2 to 10.
PROGRAM:
//program uses a nested for loop to find the prime numbers from 2 to 10
#include <stdio.h>
#include<conio.h>
int main ()
{
int i, j;
clrscr();
for(i = 2; i<10; i++)
{
for(j = 2; j <= (i/j); j++)
if(!(i%j)) break; // if factor found, not prime
if(j > (i/j))
printf("%d is prime\n", i);
}
return 0;
}
3.3 What is break Statement?
The break statement in C programming has the following two usages −
1. When a break statement is encountered inside a loop, the loop is
immediately terminated and the program control resumes at the next
statement following the loop.
2. It can be used to terminate a case in the switch statement (covered
in the next chapter).
If you are using nested loops, the break statement will stop the execution of
the innermost loop and start executing the next line of code after the block.
Syntax:
break;
Flow Diagram for break statement:
Disadvantages:
The disadvantage of array is wastage of memory because of its static behavior.
4.1 How to Declare an Array?
To declare an array,
Syntax:
data_type array_name[array_size];
For example,
float mark[6];
Here, we declared an array, mark, of floating-point type and size 6. Meaning, it
can hold 6 floating-point values.
4.2 How to Find Elements of Array?
Access of elements in an array is done by indices.
Suppose you declared an array mark as above. The first element is mark[0],
second element is mark[1] and etc.
One dimensional array is a list of values of the same data type. A one
dimensional array contains only one subscripts
A subscript is a number inside a bracket that follows an array's name.
This number can identify the number of individual elements in the
array.
Array elements are stored in sequential memory locations
Syntax:
<data-type> <variable> [size] ;
Example:
int rno[100];
float sal[200];
chat name[50];
Initialization:
Syntax:
<Data-type> <arrayname> [size]={ele1,ele2,ele3,..,.,.,.,.,.elen};
Ex:
int eno[5] = { 26, 47, 55, 69, 45};
char ename[] = { ‘a’, ‘b’, ‘c’, ‘d’ } ;
float base[] = { 56.19, 900.25, 527 } ;
NOTE:
Remember that array elements start with 0 but not 1. Also remember that the last
element is one less than the number of elements in the array. For example, an
array with 10 elements contains elements 0 through 9.
int disp[2][4] = { 19, 11, 12, 13, 14, 15, 16, 17};
Fixed length strings : When implementing a fixed length string format the first
decision is the size of the variable. If we make it too small, we can‟t store all
the data. If we make it too big, we waste memory.
Example :
1. char str[15]=”Have a nice day”;
2. char str[100]=”Hi”;
Variable length strings : In variable length strings the user can use the required
memory only. So reduce the memory wastage and data losses.
Example : char str[]=”Good day”;
1. Length controlled strings : Length controlled strings add a count that
specifies the number of characters in the string.
2. Delimited strings : Another techniques used to identify the end of the
string is the delimiter at the ends of delimited strings.
Strings and characters : Data can be stored in two ways.
1. Data as character literal.
2. Data as string literal.
Data stored as character literal, we can use single quote marks.
Example:
‘a’ - Here a is a character.
“a” - Here a is a string.
‘ ‘ - It is an empty character.
“ “ -It is an empty string..
5.1 How to Declare a String?
String declaration defines memory for a string when it is declared as an
array in local memory.
Syntax : 1. char str[9];
Syntax : 2. string pointer declaration.
char *pstr;
Initializing strings :
We can initialize a string the same way that we initialize any storage
structure by assigning a value to it when it is defined.
Example:
1. getstring → (gets/fgets)
2. putstring→ (puts/fputs)
1. getchar()
2. getch()
3. getche()
Above three statements used for read a single character from keyboard at a
time.
1) getchar(): This function is used read a character from the keyboard and
assigned the character to variable, the variable stored the character.
Syntax :
variable=getchar();
PROGRAM :
#include<stdio.h>
void main()
{
char c;
printf(“Enter your character\n”);
c=getchar();
printf(“Entered character is \n”);
putchar(c);
getch();
}
OUTPUT:
Enter your character:A
Entered character is A
2) getch(): It is also read the characters from the keyboard and passes it
immediately to the program with echoing on the screen.
PROGRAM:
#include<stdio.h>
void main()
{
char ch;
printf(“Enter a character\n”);
ch=getch();
printf(“Entered character is %c”,ch);
getch();
}
OUTPUT:
Enter your character:A
Entered character is A
3) getche() : Accepts a character and passes it to the program and
echos(displays) the same character on the screen also.
PROGRAM:
#include<stdio.h>
void main()
{
char ch;
printf(“Enter your character \n”); ch=getche();
printf(“Entered character is \n”); putchar(ch);
getch();
}
OUTPUT:
Enter your character:A
Entered character is A
strcpy(): This function is used to copy the data of one string to another string
variable.
Syntax:
strcpy(stringvariable,stringvariable1);
The string in the second position is the source string that contains the data to
be copied. The string in the first position is destination string that receives the
data.
PROGRAM:
#include< string.h>
#include<conio.h>
void main()
{
char str[20],str1[20];
clrscr();
puts(“Enter your string:”);
gets(str);
strcpy(str1,str);
puts(str1);
getch();
}
OUTPUT:
Enter your string:Hello
Hello
PROGRAM:
#include< string.h>
#include<conio.h>
#include<stdio.h>
void main()
{
int i;
char str1[20],str2[20];
clrscr();
puts(“Enter both strings:”);
gets(str1);
gets(str2);
i=strcmp(str1,str2);
printf(“Difference is %d”,i);
getch();
}
OUTPUT:
Enter both strings:Rashmi
Rashmi
Difference is 0
strrev() : This function is used to get the reverse string of a given string.
Syntax:
strrev(string);
PROGRAM:
#include< string.h>
#include<conio.h>
#include<stdio.h>
void main()
{
char str[20];
clrscr();
puts(“Enter a string:”);
gets(str);
strrev(str);
puts(“Reverse string of the given string is:”);
puts(str);
getch();
}
OUTPUT:
Enter a string:RASHMI
Reverse string of the given string is:IMHSAR
strlwr(): This function is used to convert the uppercase string to lower case
string.
Syntax:
strlwr(string);
PROGRAM:
#include< string.h>
#include<stdio.h>
#include<conio.h>
void main()
{
char str[20];
clrscr();
puts(“Enter the string in uppercase:”);
gets(str);
strlwr(str);
printf(“Entered string in lowercase:”);
puts(str);
getch();
}
OUTPUT:
Enter the string in uppercase:YEAR
Entered string in lowercase:year
1. Debugging is easier
2. It is easier to understand the logic involved in the program
3. Testing is easier
4. Recursive call is possible
5. Irrelevant details in the user point of view are hidden in functions
6. Functions are helpful in generalizing the program
1. Pre defined
2. User defined.
1. PREDEFINED:
A function which has own definition and comes along with the software is
called as predefined functions. Or library functions are called as predefined.
Ex: printf, scanf, get char() , put char() etc.
✓ We can’t change the predefine function operation.
✓ We can’t modify predefined function.
2. USER DEFINED:
A function which is defined by user for a particular purpose is called as user
defined functions.
➢ User defined functions follow the c language functions pre- defined rules.
➢ Pre defined rules user can’t change.
➢ In user defined functions user can implement their own operation.
➢ User defined functions names and the operations can change when user
want.
Example:
void main()
int abc(int a, int b);
float addition(float a, float b);
1. Actual parameter:
The values which are send/pass from calling function to called function are
called actual parameters are actual arguments
2. Formal parameter:
Function parameters are called formal parameters. These are local variable
which receive values from calling function.
Question: If global variables can be used anywhere in the program, why not
make all variables global?
Answer:
As your programs get bigger, you will begin to declare more and more
variables. There are limits on the amount of memory available. Variables
declared as global take up memory for the entire time the program is running;
however, local variables don't. For the most part, a local variable takes up
memory only while the function to which it is local is active. Additionally,
global variables are subject to unintentional alteration by other functions. If this
occurs, the variables might not contain the values you expect them to when
they're used in the functions for which they were created.
Question: How does the computer knows the difference between a global
variable and a local variable that have the same name?
Answer:
The important thing to know is that when a local variable is declared with
the same name as a global variable, the program temporarily ignores the global
variable. It continues to ignore the global variable until the local variable goes
out of scope.
Question: Can I declare a local variable and a global variable that have the
same name, as long as they have different variable types?
Answer:
Yes. When you declare a local variable with the same name as a global
variable, it is a completely different variable. This means that you can make it
whatever type you want. You should be careful, however, when declaring global
and local variables that have the same name
6.1 What are the Different Category of functions?
Functions are categories depending on whether arguments are present or not
and whether a value is returned or not. In C language functions May belong to
one of the following categories
1) Functions with no arguments and no return values.
2) Functions with arguments and no return values.
3) Functions with arguments and returns values.
1. Function With No Arguments And No Return Values:
` When a function has no arguments it does not receive, any data from the
calling function. Similarly, when it does not return a value the calling function
does not receive any data from the called function. It shows in the figure. The
dotted lines indicate that there is only a transfer of control but not data..
Question: Write a C program with arguments and with return value using
functions.
PROGRAM:
/*arguments with return value functions*/
#include<stdio.h>
#include<conio.h>
int add (int x, int y)
{
int z;
z=x+y;
return z;
}
int subtr(int p, int q)
{
return (p-q);
}
int mult (int, int);
int div (int, int);
int main()
{
int a,b,c;
clrscr();
printf("Enter any two numbers \n");
scanf("%d%d", &a, &b);
c=add(a, b);
printf("\n the addition is %d", c);
printf("\n the subtraction %d", subtr(a, b));
c=mult(a, b);
printf("\n the multiplication %d", mult(a,b));
printf("\n the division %d", div(a,b));
getch();
return(0);
}
int mult (int a, int b)
{
return a*b;
}
int div(int m, int n)
{
int p=m/n;
return p;
}
OUTPUT:
Enter any two numbers
10
3
the addition is 13
the subtraction 7
the multiplication 30
the division 3
1. Call by value
2. Call by reference
1. Call by value:
➢ In this technique the values of actual arguments in the calling function are
copied into the formal arguments in the called function.
➢ Here the data transfer done in only one direction i.e. from calling function
to called function, so any changes happen in formal arguments does not
effect on the actual arguments.
➢ But if any changes will happen in the actual arguments, formal arguments
automatically effected.
3. Static Variable
4. Register Variable
Advantages of recursion:-
In the recursive program, the solution to the base case is provided and the
solution of the bigger problem is expressed in terms of smaller problems.
i) It is very flexible in data structures like stacks, queues, linked lists
and trees.
ii) Using recursion, the length of the program is reduced.
Disadvantages of recursion:-
i) It requires extra storage space(memory).
ii) Whenever there is no exit condition then program will be executed
out of memory and takes into infinite calls.
iii) It takes more time and less speed for execution.
The following are the applications(example problems ) of recursion:
Step 1:
Step 2:
Step 3:
Step 4:
Step 5:
Step 6:
Step 7:
PROGRAM:
#include <stdio.h>
int main()
{
int n = 4; // Number of disks
towerOfHanoi(n, 'A', 'C', 'B');// A, B and C are names of rods in towers of hanoi
return 0;
}
// C recursive function to solve tower of hanoi puzzle
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
Here,
For n disks, total 2n – 1 moves are required.
Example: For 4 disks 24 – 1 = 15 moves are required.
For n disks, total 2n-1 function calls are made.
Example: For 4 disks 24-1 = 8 function calls are made.
● You request to use a header file in your program by including it with the C
preprocessing directive #include , like you have seen inclusion of stdio.h
header file, which comes along with your compiler.
● Including a header file is equal to copying the content of the header file but
we do not do it because it will be error-prone and it is not a good idea to
copy the content of a header file in the source files, especially if we have
multiple source files in a program.
● Both the user and the system header files are included using the
preprocessing directive #include . It has the following two forms.
#include <file>
This form is used for system header files. It searches for a file named 'file' in a
standard list of system directories.
#include "file"
It searches for a file named 'file' in the directory containing the current file.
Writing Of Single And Multiple Uses Of Header Files:
In case, when a header file needs to be included twice within your program,
your compiler will be going to process the contents inside it - twice which will
eventually lead to an error in your program. So to eliminate this, you have to use
conditional preprocessor directives.
Syntax:
#ifndef HEADER_FILE_NAME
#define HEADER_FILE_NAME
the entire header file
#endif
Multiple conditional preprocessors can be used like this:
Syntax:
#if FIRST_SYSTEM
#include "sys.h"
#elif SEC_SYSTEM
#include "sys2.h"
#elif THRID_SYSTEM
....
#endif
For example, I am calling an external function named swap in my main.c file.
Example:
#include<stdio.h>
#include"swap.h"
void main()
{
int a=10;
int b=30;
swap (&a,&b);
printf ("a=%d\n", a);
printf ("b=%d\n",b);
}
Swap method is defined in swap.h file, which is used to swap two numbers by
using a temporary variable.
Example:
void swap (int* a, int* b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
Preprocessors Examples
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 10
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH
with 10. Use #define for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add
the text to the current source file. The next line tells CPP to get myheader.h from
the local directory and add the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 32
It tells the CPP to undefine existing FILE_SIZE and define it as 32.
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
EXAMPLE C PROGRAM:
#include<stdio.h>
#define PI 3.14
void main()
{
printf(“PI value is %f”,PI);
}
The compiler will allocate the memory for the above two dimensional
array row-wise meaning the first element of the second row will be placed after
the last element of the first row.
Fig. 7.9: Row Wise Memory Allocation for One Dimensional Array
Assume that the first element of the array is at address 1000 and the size of
type int is 2 bytes then the elements of the array will get the following allocated
memory locations.
Fig. 7.10: Value and Address Representation for One Dimensional Array
Create pointer for the two dimensional array.
The two dimensional integer array num so, our pointer will also be of type
int.
We will assign the address of the first element of the array num to the
pointer ptr using the address of & operator.
int *ptr = &num[0][0];
Accessing the elements of the two dimensional array via pointer
The two dimensional array num will be saved as a continuous block in the
memory. So, if we increment the value of ptr by 1 we will move to the next
block in the allocated memory.
In the following code we are printing the content of the num array using for
loop and by incrementing the value of ptr.
PROGRAM:
#include <stdio.h>
int main(void) {
// 2d array
int num[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
// the pointer ptr pointing at array num
int *ptr = &num[0][0];
// the other variables
int ROWS = 3, COLS = 4, TOTAL_CELLS = ROWS * COLS, i;
/* printing the elements of the array num via pointer ptr*/
for (i = 0; i < TOTAL_CELLS; i++) {
printf("%d ", *(ptr + i)) ;
}
return 0;
}
OUTPUT:
1 2 3 4 5 6 7 8 9 10 11 12
7.6 What is Dynamic Memory Management Functions?
❖ An array is a collection of a fixed number of values. Once the size of an
array is declared, you cannot change it.
❖ Sometimes the size of the array you declared may be insufficient. To solve
this issue, you can allocate memory manually during run-time. This is
known as dynamic memory allocation in C programming.
❖ To allocate memory dynamically, library functions are malloc(), calloc(),
realloc() and free() are used. These functions are defined in the <stdlib.h>
header file.
C malloc():
The name "malloc" stands for memory allocation.
The malloc() function reserves a block of memory of the specified number
of bytes. And, it returns a pointer of void which can be casted into pointers of
any form.
Syntax of malloc()
ptr = (castType*) malloc(size);
Example:
ptr = (int*) malloc(100 * sizeof(float));
The above statement allocates 400 bytes of memory. It's because the size of
float is 4 bytes. And, the pointer ptr holds the address of the first byte in the
allocated memory. The expression results in a NULL pointer if the memory
cannot be allocated.
C calloc()
The name "calloc" stands for contiguous allocation.
The malloc() function allocates memory and leaves the memory
uninitialized. Whereas, the calloc() function allocates memory and initializes all
bits to zero.
Syntax of calloc()
ptr = (castType*)calloc(n, size);
Example:
ptr = (float*) calloc(25, sizeof(float));
The above statement allocates contiguous space in memory for 25 elements of
type float.
C free()
Dynamically allocated memory created with either calloc() or malloc()
doesn't get freed on their own. You must explicitly use free() to release the
space.
Syntax of free()
free(ptr);
This statement frees the space allocated in the memory pointed by ptr.
PROGRAM: Using malloc() and free()
// Program to calculate the sum of n numbers entered by the user
#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));
// if memory cannot be allocated
if(ptr == NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
printf("Enter elements: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
// deallocating the memory
free(ptr);
return 0;
}
Here, we have dynamically allocated the memory for n number of int.
PROGRAM: Using calloc() and free()
// Program to calculate the sum of n numbers entered by the user
#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: ");
for(i = 0; i < n; ++i)
{
scanf("%d", ptr + i);
sum += *(ptr + i);
}
printf("Sum = %d", sum);
free(ptr);
return 0;
}
C realloc()
If the dynamically allocated memory is insufficient or more than required,
you can change the size of previously allocated memory using the realloc()
function.
Syntax of realloc()
ptr = realloc(ptr, x);
Here, ptr is reallocated with a new size x.
PROGRAM: Using realloc()
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr, i , n1, n2;
printf("Enter size: ");
scanf("%d", &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf("Addresses of previously allocated memory: ");
for(i = 0; i < n1; ++i)
printf("%u\n",ptr + i);
printf("\nEnter the new size: ");
scanf("%d", &n2);
// rellocating the memory
ptr = realloc(ptr, n2 * sizeof(int));
printf("Addresses of newly allocated memory: ");
for(i = 0; i < n2; ++i)
printf("%u\n", ptr + i);
free(ptr);
return 0;
}
OUTPUT:
Enter size: 2
Addresses of previously allocated memory: 26855472
26855476
Enter the new size: 4
Addresses of newly allocated memory: 26855472
26855476
26855480
26855484
In the above code snippet, we have seen that structure is declared and as
soon as after declaration we have initialized the structure variable.
std1 = { "Pritesh",67,78.3 }
This is the code for initializing structure variable in C programming
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
std1 = {"Pritesh",67,78.3};
std2 = {"Don",62,71.3};
PROGRAM:
#include <stdio.h>
struct Bookinfo
{
char[20] bname;
int pages;
int price;
}book[3];
int main(int argc, char *argv[])
{
int i;
for(i=0;i<3;i++)
{
printf("\nEnter the Name of Book : ");
gets(book[i].bname);
printf("\nEnter the Number of Pages : ");
scanf("%d",book[i].pages);
printf("\nEnter the Price of Book : ");
scanf("%f",book[i].price);
}
printf("\nBook Details");
for(i=0;i<3;i++)
{
printf("\nName of Book : %s",book[i].bname);
printf("\nNumber of Pages : %d",book[i].pages);
printf("\nPrice of Book : %f",book[i].price);
}
return 0;
}
OUTPUT:
Enter the Name of Book :C
Enter the Number of Pages : 100
Enter the Price of Book : 200
Enter the Name of Book : CPP
Enter the Number of Pages : 200
Enter the Price of Book : 300
Enter the Name of Book : Java
Enter the Number of Pages : 300
Enter the Price of Book : 500
Book Details
Name of Book :C
Number of Pages : 100
Price of Book : 200
Name of Book : CPP
Number of Pages : 200
Price of Book : 300
Name of Book : Java
Number of Pages : 300
Price of Book : 500
9.5 How to use Structure as Function Arguments?
A structure as a function argument can be passed in the same way as you
pass any other variable or pointer.
PROGRAM:
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books book );
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Rashmi");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6495403;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Sharmila");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6495788;
/* print Book1 info */
printBook( Book1 );
/* Print Book2 info */
printBook( Book2 );
return 0;
}
void printBook( struct Books book )
{
printf( "Book title : %s\n", book.title);
printf( "Book author : %s\n", book.author);
printf( "Book subject : %s\n", book.subject);
printf( "Book book_id : %d\n", book.book_id);
}
OUTPUT:
Book title : C Programming
Book author : Rashmi
Book subject : C Programming Tutorial
Book book_id : 6495403
Book title : Telecom Billing
Book author : Sharmila
Book subject : Telecom Billing Tutorial
Book book_id : 6495788
9.6 How to Use Pointers to Structures?
Defining pointers to structures in the same way as you define pointer to any
other variable.
struct Books *struct_pointer;
To find the address of a structure variable, place the '&'; operator before the
structure's name as follows:
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you
must use the → operator as follows:
struct_pointer->title;
PROGRAM:
#include <stdio.h>
#include <string.h>
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;
};
/* function declaration */
void printBook( struct Books *book );
int main( ) {
struct Books Book1; /* Declare Book1 of type Book */
struct Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
strcpy( Book1.title, "C Programming");
strcpy( Book1.author, "Rashmi");
strcpy( Book1.subject, "C Programming Tutorial");
Book1.book_id = 6995407;
/* book 2 specification */
strcpy( Book2.title, "Telecom Billing");
strcpy( Book2.author, "Sharma");
strcpy( Book2.subject, "Telecom Billing Tutorial");
Book2.book_id = 6995700;
/* print Book1 info by passing address of Book1 */
printBook( &Book1 );
/* print Book2 info by passing address of Book2 */
printBook( &Book2 );
return 0;
}
void printBook( struct Books *book )
{
printf( "Book title : %s\n", book->title);
printf( "Book author : %s\n", book->author);
printf( "Book subject : %s\n", book->subject);
printf( "Book book_id : %d\n", book->book_id);
}
OUTPUT:
Book title : C Programming
Book author : Rashmi
Book subject : C Programming Tutorial
Book book_id : 6995407
Book title : Telecom Billing
Book author : Sharma
Book subject : Telecom Billing Tutorial
Book book_id : 6995700
9.7 What are Self Referential Structures?
Self Referential structures are those structures that have one or more
pointers which point to the same type of structure, as their member.
1. Linked Lists
2. Stacks
3. Queues
4. Trees
5. Graphs
10. What is Union?
A union is a special data type available in C that allows to store different
data types in the same memory location. You can define a union with many
members, but only one member can contain a value at any given time. Unions
provide an efficient way of using the same memory location for multiple-
purpose.
Defining a Union
To define a union, you must use the union statement in the same way as you
did while defining a structure. The union statement defines a new data type with
more than one member for your program. The format of the union statement is
as follows −
Syntax:
union [union tag] {
member definition;
member definition;
...
member definition;
} [one or more union variables];
The union tag is optional and each member definition is a normal variable
definition, such as int i; or float f; or any other valid variable definition. At the
end of the union's definition, before the final semicolon, you can specify one or
more union variables but it is optional. Here is the way you would define a union
type named Data having three members i, f, and str.
Example:
union Data {
int i ;
float f;
char str[20];
} data;
Now, a variable of Data type can store an integer, a floating-point number,
or a string of characters. It means a single variable, i.e., same memory location,
can be used to store multiple types of data. You can use any built-in or user
defined data types inside a union based on your requirement.
The memory occupied by a union will be large enough to hold the largest
member of the union. For example, in the above example, Data type will occupy
20 bytes of memory space because this is the maximum space which can be
occupied by a character string. The following example program displays the total
memory size occupied by the above union.
PROGRAM:
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[10];
};
int main( ) {
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}
OUTPUT:
Memory size occupied by data : 10
Question: What are the difference between Text File and Binary File
Answer:
Text File Binary File
1) Bits represent character.. 1) Bits represent a custom data.
2) Less prone to get corrupt as 2) Can easily get corrupted, even a
changes reflect as soon as the file is single bit change may corrupt the file.
opened and can easily be undone.
3) Can store only plain text in a file.
3) Can store different types of data
(image, audio, text) in a single file.
4) Widely used file format and can 4) Developed especially for an
be opened using any simple text application and may not be understood
editor. by other applications.
5) Mostly .rtf and .txt are used as 5) Can have any application defined
extension as text files. extension.
We can also limit the number of digits or characters that can be input or
output, by adding a number with the format string specifier, like "%1d" or
"%3s", the first one means a single numeric digit and the second one means 3
characters, hence if you try to input 42, while scanf() has "%1d", it will take only
4 as input. Same is the case for output.
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 a loop in case you want to read more than one character.
❖ The putchar() function displays the character passed to it on the screen and
returns the same character. This function too displays only a single character
at a time. In case you want to display more than one characters, use
putchar() method in a loop.
PROGRAM:
#include <stdio.h>
void main( )
{
int c;
printf("Enter a character:");
c = getchar();
printf(“Entered character:”);
putchar(c);
}
OUTPUT:
Enter a character:k
Entered character:k
gets() & puts() functions:
❖ The gets() function reads a line from stdin(standard input) into the buffer
pointed to by str pointer, until either a terminating newline or EOF (end of
file) occurs.
❖ The puts() function writes the string str and a trailing newline to stdout.
PROGRAM:
#include<stdio.h>
void main()
{
char str[100];
printf("Enter a string:");
gets( str );
printf(“Entered string:”);
puts( str );
getch();
}
OUTPUT:
Enter a string:rashmi
Entered string:rashmi
When you will compile the above code, it will ask you to enter a string.
When you will enter the string, it will display the value you have entered.
Difference between scanf() and gets():
➢ The main difference between these two functions is that scanf() stops
reading characters when it encounters a space, but gets() reads space as
character too.
➢ If you enter name as Rashmi Devi using scanf() it will only read and store
Rashmi and will leave the part after space. But gets() function will read it
completely.
OTHER BOOKS BY AUTHOR: