You are on page 1of 40

Programming in C Ms. A.

Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

CS8251 PROGRAMMING IN C LTPC3003


SYLLABUS
OBJECTIVES:
 To develop C Programs using basic programming constructs
 To develop C programs using arrays and strings
 To develop applications in C using functions , pointers and structures
 To do input/output and file handling in C
UNIT I BASICS OF C PROGRAMMING 9
Introduction to programming paradigms - Structure of C program - C programming: Data Types
– Storage classes - Constants – Enumeration Constants - Keywords – Operators: Precedence and
Associativity - Expressions - Input/Output statements, Assignment statements – Decision making
statements - Switch statement - Looping statements – Pre-processor directives - Compilation
process
UNIT II ARRAYS AND STRINGS 9
Introduction to Arrays: Declaration, Initialization – One dimensional array – Example Program:
Computing Mean, Median and Mode - Two dimensional arrays – Example Program: Matrix
Operations (Addition, Scaling, Determinant and Transpose) - String operations: length, compare,
concatenate, copy – Selection sort, linear and binary search
UNIT III FUNCTIONS AND POINTERS 9
Introduction to functions: Function prototype, function definition, function call, Built-in
functions (string functions, math functions) – Recursion – Example Program: Computation of
Sine series, Scientific calculator using built-in functions, Binary Search using recursive functions
– Pointers – Pointer operators – Pointer arithmetic – Arrays and pointers – Array of pointers –
Example Program: Sorting of names – Parameter passing: Pass by value, Pass by reference –
Example Program: Swapping of two numbers and changing the value of a variable using pass by
reference
UNIT IV STRUCTURES 9
Structure - Nested structures – Pointer and Structures – Array of structures – Example Program
using structures and pointers – Self referential structures – Dynamic memory allocation - Singly
linked list - typedef

1
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

UNIT V FILE PROCESSING 9


Files – Types of file processing: Sequential access, Random access – Sequential access file -
Example Program: Finding average of numbers stored in sequential access file - Random access
file - Example Program: Transaction processing using random access files – Command line
arguments
OUTCOMES: Upon completion of the course, the students will be able to
 Develop simple applications in C using basic constructs
 Design and implement applications using arrays and strings
 Develop and implement applications in C using functions and pointers.
 Develop applications in C using structures.
 Design applications using sequential and random access file processing.
TEXT BOOKS:
T1. Reema Thareja, ―Programming in C‖, Oxford University Press, Second Edition, 2016.
T2. Kernighan, B.W and Ritchie,D.M, ―The C Programming language‖, Second Edition,
Pearson Education, 2006
REFERENCES:
R1. Paul Deitel and Harvey Deitel, ―C How to Program‖, Seventh edition, Pearson Publication
R2. Juneja, B. L and Anita Seth, ―Programming in C‖, CENGAGE Learning India pvt. Ltd.,
2011
R3. Pradip Dey, Manas Ghosh, ―Fundamentals of Computing and Programming in C‖, First
Edition, Oxford University Press, 2009.
R4. Anita Goel and Ajay Mittal, ―Computer Fundamentals and Programming in C‖, Dorling
Kindersley (India) Pvt. Ltd., Pearson Education in South Asia, 2011.
R5. Byron S. Gottfried, "Schaum's Outline of Theory and Problems of Programming with
C",McGraw-Hill Education, 1996.

2
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

UNIT - I
BASICS OF C PROGRAMMING
PART - A
1. Define compiler.
It is a program used to convert the high level language program into machine language.
2. What are the types of programming language?
· Machine language
· Assembly language
· High level language
3. What are the different data types available in „C‟?
There are four basic data types available in „C‟.
1. int
2. float
3. char
4. Double
4. What are Keywords?
Keywords are certain reserved words that have standard and pre-defined meaning in„C‟.
These keywords can be used only for their intended purpose.
5. What is an Operator and Operand?
An operator is a symbol that specifies an operation to be performed on operands.
Example: *, +, -, / are called arithmetic operators.
The data items that operators act upon are called operands.
Example: a+b; In this statement a and b are called operands.
6. What is Ternary operators or Conditional operators?
Ternary operators is a conditional operator with symbols ? and :
Syntax: variable = exp1 ? exp2 : exp3
If the exp1 is true variable takes value of exp2. If the exp2 is false, variable takes the
value of exp3.
7. What are the Bitwise operators available in „C‟?
& - Bitwise AND
| - Bitwise OR
3
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

~ - One‟s Complement
>> - Right shift
<< - Left shift
^ - Bitwise XOR are called bit field operators
8. What are the logical operators available in „C‟?
The logical operators available in „C‟ are
&& - Logical AND
|| - Logical OR
! - Logical NOT
9. What is the difference between Logical AND and Bitwise AND?
Logical AND (&&): Only used in conjunction with two expressions, to test more than
one condition. If both the conditions are true the returns 1. If false then return0.AND (&): Only
used in Bitwise manipulation. It is a unary operator.
10. What is the difference between „=‟ and „==‟ operator?
Where = is an assignment operator and == is a relational operator.
Example: while (i=5) is an infinite loop because it is a non zero value and while (i==5) is true
only when i=5.
11. What is type casting?
Type casting is the process of converting the value of an expression to a particular data
type.
Example: int x,y;c = (float) x/y; where a and y are defined as integers. Then the result of x/y is
converted into float.
12. What is the difference between „a‟ and “a”?
„a‟ is a character constant and “a” is a string.
13. What is the difference between while loop and do…while loop?
In the while loop the condition is first executed. If the condition is true then it executes
the body of the loop. When the condition is false it comes of the loop. In the do…while loop
first the statement is executed and then the condition is checked. The do…while loop will
execute at least one time even though the condition is false at the very first time.
14. What is a Modulo Operator?

4
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

„%‟ is modulo operator. It gives the remainder of an integer division


Example: a=17, b=6. Then c=%b gives 5.
15. How many bytes are occupied by the int, char, float, long int and double?
int - 2 Bytes
char - 1 Byte
float - 4 Bytes
long int - 4 Bytes
double - 8 Bytes
16. What are the types of I/O statements available in „C‟?
There are two types of I/O statements available in „C‟.
Formatted I/O Statements
Unformatted I/O Statements
17. What is the difference between ++a and a++?
++a means do the increment before the operation (pre increment)
a++ means do the increment after the operation (post increment)
Example:
a=5;
x=a++; /* assign x=5*/
y=a; /*now y assigns y=6*/
x=++a; /*assigns x=7*/
18. What is a String?
String is an array of characters.
19. What is a global variable?
The global variable is a variable that is declared outside of all the functions. The global
variable is stored in memory, the default value is zero. Scope of this variable is available in all
the functions. Life as long as the program‟s execution doesn‟t come to an end.
20. What are the Escape Sequences present in „C‟
\n - New Line
\b - Backspace
\t - Form feed

5
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

\‟ - Single quote
\\ - Backspace
\t - Tab
\r - Carriage return
\a - Alert
\” - Double quotes
21. Construct an infinite loop using while?
while (1)
{} Here 1 is a non zero, value so the condition is always true. So it is an infinite loop.
22. Write the limitations of getchar( ) and sacnf( ) functions for reading strings (JAN 2009)
getchar( )
To read a single character from stdin, then getchar() is the appropriate.
scanf( )
scanf( ) allows to read more than just a single character at a time.
23. What is the difference between scanf() and gets() function?
In scanf() when there is a blank was typed, the scanf() assumes that it is an end.
gets() assumes the enter key as end. That is gets() gets a new line (\n) terminated string of
characters from the keyboard and replaces the „\n‟ with „\0‟.
24. What is meant by Control String in Input/Output Statements?
Control Statements contains the format code characters, specifies the type of data that the
user accessed within the Input/Output statements.
25. What is the output of the programs given below?
main()
{{
float a; float a;
int x=6, y=4; int x=6, y=4;
a=x\y; a=(float) x\y;
printf(“Value of a=%f”, a); printf(“Value of a=%f”,a);
}}
Output 1. 1.500000

6
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

26. What is the output of the following program when, the name given with spaces?
main()
{
char name[50];
printf(“\n name\n”);
scanf(“%s, name);
printf(“%s”,name);
}
Output:
Lachi (It only accepts the data upto the spaces)
27. What is the difference between while(a) and while(!a)?
while(a) means while(a!=0)
while(!a) means while(a==0)
28. Why we don‟t use the symbol „&‟ symbol, while reading a String through scanf()?
The „&‟ is not used in scanf() while reading string, because the character variable
itself specifies as a base address.
Example: name, &name[0] both the declarations are same.
29. What is the output of the program?
main() increment()
{{
increment(); static int i=1;
increment(); printf(“%d\n”,i)
increment(); i=i+1;
}}
Output:
123
30. Why header files are included in „C‟ programming?
This section is used to include the function definitions used in the program. Each header
file has „h‟ extension and include using ‟# include‟ directive at the beginning of a program.

7
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

All statements should be written in lower case letters. Upper case letters are only for
symbolic constants. Blank spaces may be inserted between the words. This improves the
readability of statements. It is a free-form language; we can write statements anywhere
between„{„ and „}‟.a = b + c;d = b*c;

31. What do you mean by variables in „C‟?


A variable is a data name used for storing a data value. Can be assigned different values
at different times during program execution. Can be chosen by programmer in a meaningful way
so as to reflect its function in the program. Some examples are: Sum percent_1class_total.
32. List the types of operators.
Arithmetic operators
Relational operators
Logical operators
Increment and Decrement operators
Assignment operators
Bitwise operators
Comma operator
Conditional operator
33. Give the syntax for the „for‟ loop statement
for (Initialize counter; Test condition; Increment / Decrement)
{
statements;
}
34. What is the use of sizeof( ) operator?
The sizeof ( ) operator gives the bytes occupied by a variable. No of bytes occupied
varies from variable to variable depending upon its data types.
Example:
int x,y;
printf(“%d”,sizeof(x));

8
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

Output:
2
35. Write a program to swap the values of two variables (without temporary variable).
#include <stdio.h>
#include <conio.h>
void main( )
{
int a =5; b = 10;
clrscr( );
prinf(“Before swapping a = %d b = %d “, a , b);
a = a + b;
B = a – b;
a = a – b;
prinf(“After swapping a = %d b = %d”, a,b);
getch( );
}
Output:
Before swapping a = 5 b = 10
After swapping a = 10 b = 5
36. Write short notes about main ( ) function in ‟C‟ program. (MAY 2009)
i) Every C program must have main ( ) function.
ii) All functions in C, has to end with „( )‟ parenthesis.
iii) It is a starting point of all „C‟ programs.
iv) The program execution starts from the opening brace „{„ and ends with closing brace
„}‟, within which executable part of the program exists.
PART - B
1. Explain in detail about programming paradigms.
Machine code
Procedural languages
 COBOL

9
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

 FORTRAN
 ALGOL
 PL/I
 BASIC
Features of C Programming Language
Advantages of C
Disadvantages of C
Object-oriented programming
2. Explain in detail about structure of C program.
Draw the diagram for structure of C program
Documentation section
Link section
Definition section
Global declaration section
main () function section
Subprogram section
3. Explain in detail about decision control statements or two way selection in C language
with syntax.
Decision making statement is depending on the condition block need to be executed or
not which is decided by condition
 if
 if-else
 switch
Write the syntax and example program for each control statements
4. Explain detail about looping statements.
Process of repeatedly executing a collection of statement
 while loops
 do while loops
 for loops
Write the syntax and example program for each looping statements

10
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

5. Discuss about preprocessor directives.


o #include
o #define
o #undef
o #ifdef
o #ifndef
o #if
o #else
o #elif
o #endif
o #error
o #pragma
6. Describe storage classes with examples.
o auto
o extern
o static
o register
Write the example program for each classes
7. What is an operator? Explain the arithmetic, relational, logical and assignment
operators in C language.
Write all operator symbols and explain with example program.
8. Write a program to calculate the area of a circle.
9. Write a C program to convert an integer into the corresponding floating point number.
10. Write a program to find whether a number is even or odd.
11. Write a C program to calculate the sum of numbers from m to n.
12. Write a C program to calculate the average of first n numbers.
13. Write a C program to determine whether a given number is a prime or a composite
number.
14. Write a C program to determine whether the entered character is a vowel or not.
UNIT - II

11
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

ARRAYS AND STRINGS


PART - A
1. What is an array?
An array is a group of similar data types stored under a common name.
int a[10];
Here a[10] is an array with 10 values.
2. List the characteristics of Arrays.
All elements of an array share the same name, and they are distinguished form one
another with help of an element number. Any particular element of an array can be modified
separately without disturbing other elements.
3. What are the types of Arrays?
1.One-Dimensional Array
2. Two-Dimensional Array
3. Multi-Dimensional Array
4. What is the use of „\0‟ character?
When declaring character arrays (strings), „\0‟ (NULL) character is automatically added
at end. The „\0‟ character acts as an end of character array.
5. Define Strings.
The group of characters, digit and symbols enclosed within quotes is called as String (or)
character Arrays. Strings are always terminated with „\0‟ (NULL) character. The compiler
automatically adds „\0‟ at the end of the strings.
6. Write an example for declaring ARRAYS.
Arrays may consist of any of the valid data types. Arrays are declared along with all other
variables in the declaration section of the program.
/* Introducing array's */
#include <stdio.h>
main()
{
int numbers[100];
float averages[20];

12
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

numbers[2] = 10;
--numbers[2];
printf("The 3rd element of array numbers is %d\n", numbers[2]);
}
7. Write an example for assigning values to arrays.
The declaration is preceded by the word static. The initial values are enclosed in braces,
Example
#include <stdio.h>
main()
{
int x;
static int values[] = { 1,2,3,4,5,6,7,8,9 };
static char word[] = { 'H','e','l','l','o' };
for( x = 0; x < 9; ++x )
printf("Values [%d] is %d\n", x, values[x]);
}
8. Define Multi-dimensional array.
Multi-dimensioned arrays have two or more index values which specify the element in
the array.
multi[i][j];
Declaration:
int m1[10][10];
static int m2[2][2] = { {0,1}, {2,3} };
9. Example for character arrays [strings].
#include <stdio.h>
main()
{
static char name1[] = {'H','e','l','l','o'};
static char name2[] = "Hello";
printf("%s\n", name1);

13
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

printf("%s\n", name2);
}
10. With syntax and example mention the method declaring an array.
Syntax: data_type array_name[array_size]={list_of_values};

Example:
int rollno[5]={4001,4002,4003,4004,4005};
11. Given an array int salary[5]={10000,8500,15000,7500,9000}. Calculate the address of
salary[4] if the base address=1000.
Here, the size of the datatype int is 2.
The value for w=2
Address of salary[4] =1000+2(4-0)
=1000+8
=1008
12. Given an array int a[10]={101,012,103,104,105,106,107,108,109,110}. Show the memory
representation and calculate its length.
Memory Representation:
101 102 103 104 105 106 107 108 109 110
a[0] a[1] a[2] a[3] a[4] a[5] a[6] a[7] a[8] a[9]
Length calculation:
Length of an array=upper_bound - lower_bound + 1
Here, upper_bound = 9 and lower_bound = 0
Thus, length of an array = 9-0+1 = 10
13. Write a C program to get 10 inputs for an array. Output:
#include<stdio.h> Enter ten numbers:23
45
#include<conio.h> 67
89
void main() 10
20
{ 30
40
int i,number[5]; 50
printf("Enter ten numbers:"); The inputs of given array
23
45
14 67
89
10
20
30
40
50
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

for(i=0;i<10;i++)
scanf("%d",&number[i]);
printf("The inputs of given array\n");
for(i=0;i<10;i++)
printf("%d",number[i]);
}
14. Write a program to copy the value of an array to another.
#include<stdio.h>
#include<conio.h>
void main()
Output:
{ The content of Array A:
int i,a[5],b[5]={1,2,3,4,5}; 1
2
for(i=0;i<5;i++) 3
4
a[i]=b[i]; 5
printf("The content of array A:\n);
for(i=0;i<5;i++)
printf("%d",a[i]);
}
15. List the applications of array.
The arrays are used in C programming frequently because,
 Mathematical vectors and matrices can be easily implemented using arrays.
 One dimensional array can be used as database where the elements are the records.
 Strings, stacks, queue, heaps and hash tables can be implemented using arrays.
 Sorting of elements into ascending order and descending order can be performed using
arrays.
16. List the different methods for reading and writing a string.
The different methods for reading a string are,
 scanf()
 gets()
 getchar()

15
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

 getch() or getche()
The different methods for writing a string are,
 printf()
 puts()
 putchar()
17. Write a C program to get a string input and print it.
#include<stdio.h>
#include<conio.h>
void main()
Output:
{ Excellent
char str[20]; The given string
Excellent
gets(str);
printf("The given string\n");
printf("%s",str);
}
18. Why is it necessary to give the size of an array in an array declaration?
When an array is declared, the compiler allocates a base address and reserves enough
space in the memory for all the elements of the array. The size is required to allocate the required
space. Thus, the size must be mentioned.
19. What is the use of gets() function?
The gets() function allows a full line entry from the user. When the user presses the enter
key to end the input, the entire line of characters is stored to a string variable.
20. Mention the various string manipulation function in C.
S.No Function Purpose
1 strcpy(s1,s2) Copies string s2 into string s1.
2 strcat(s1,s2) Concatenates string s2 onto the end of string s1.
3 strlen(s1) Returns the length of string s1
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
4 strcmp(s1,s2)
s1>s2.
5 strchr(s1,ch) Returns a pointer to the first occurrence of character ch in string s1.

16
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

6 strst(s1,s2) Returns a pointer to the first occurrence of sting s2 in string s1.

21. Write a C program to find the average of n (n < 10) numbers using arrays
#include <stdio.h>
int main()
{ Output:
Enter n: 6
int marks[10], i, n, sum = 0, average; Enter number 1:30
Enter number 2:40
printf("Enter n: "); Enter number 3:76
Enter number 4:80
scanf("%d", &n); Enter number 5:100
Enter number 6:142
for(i=0; i<n; ++i) Average= 78
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;
printf("Average = %d", average);
return 0;
}
22. Write a C program to find the length of given string.
#include <stdio.h>
int main()
{
char s[1000], i;
Output:
printf("Enter a string: "); Enter a string:
Programming in C
scanf("%s", s); Length of string:16

for(i = 0; s[i] != '\0'; ++i);


printf("Length of string: %d", i);
return 0;
}

17
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

23. Write a C program to Read & write Strings in C using Printf() and Scanf() functions
#include <stdio.h>
#include <string.h>
int main()
{
Output:
char nickname[20]; Enter your Nick name: Negan
Negan
printf("Enter your Nick name:");
scanf("%s", nickname);
printf("%s",nickname);
return 0;
}
24. Write a C program to Read & Write Strings in C using gets() and puts() functions
#include <stdio.h>
#include <string.h>
int main()
{
char nickname[20];
puts("Enter your Nick name:");
gets(nickname); Output:
Enter your Nick name: Negan
puts(nickname); Negan
return 0;
}
25. How to compare two string using function?
#include <stdio.h>
#include <string.h>
int main()
{
Output:
char s1[20] = "BeginnersBook"; string 1 and 2 are different
char s2[20] = "BeginnersBook.COM";
if (strcmp(s1, s2) ==0)

18
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

{
printf("string 1 and string 2 are equal");
}else
{
printf("string 1 and 2 are different");
}
return 0;
}
PART-B
1. Write a C program to find the greatest element in an array. Get the input from the user
and the number of elements in the array should be greater than 10.
2. Write a C program to merge and sort the elements of two different arrays.
3. Write a C program to find the number of vowels and consonants in a sentence.
4. Write a C program to perform linear search using array.
5. Write a C program to perform binary search using array.
6. Write a C program to perform matrix operations using array.
7. Write a C program to find the standard deviation using array.
8. Write a C program to count number of words in a sentence.
9. Write a C program to check whether a string is palindrome.
10. Explain the standard string functions with example to support each type.
Array of characters
String functions:
 strlen()
 strcmp()
 strcat()
 strcpy()
11. Define arrays. Explain the array types with an example program for each type.
Collection or group of elements
 one dimensional array
 two dimensional array

19
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

 multi dimensional array


UNIT - III
FUNCTIONS AND POINTERS
PART - A
1. What is function?
To break a program into segments are commonly known as functions. Each of which can
be written more or less independently of the others. Every function in the program is supposed to
perform a well-defined task.
2. Why are functions needed?
 Dividing the program into separate well defined functions facilitates each function to be
written and tested separately. This simplifies the process of getting the total program to
work.
 Understanding, coding and testing multiple separate functions is easier than doing the
same for one big function.
 If a big problem has to be developed without using any function other than main(), then
there will be countless lines in the main() function and maintaining that program will be
difficult task.

3. What is function prototype or function interface?


A function definition specifies how the function does what it does (implementation), a
function prototype merely specifies its interface, (i.e) what data types go in and come out of it.
The term function prototype is particularly used in forward declarations of functions in header
files allows for splitting a program into translation units.
4. What is function declaration?
Before using a function, the compiler must know the number of parameters and the type
of parameters that the function expects to receive and the datatype of value that it will return to
the calling program. Placing the function declaration statement prior to its use enables the
compiler to make a check on the arguments used while calling that function.
5. Write the function parts.
The functions have two parts are,

20
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

 Function header
 Function body
6. Write the syntax of function.
Syntax:
Return_datatype function_name(datatype var1, datatype var2,...)
{
..........
Statements
.........
return (variable);
}
7. What is function call?
The function call statement invokes the function. When a function is invoked, the
compiler jumps to the called function to execute the statements that are a part of that function.
Once the called function is executed, the program control passes back to the calling function.
Syntax:
function_name(var1,var2,...);

8. What are the points are to be noted while calling a function?


 Function name and number of arguments, type of arguments in the function call must be
same as that given in the function declaration and the function header of the function
definition.
 Names (not types) of variables in the function declaration, function call and header of
function definition may vary.
 Arguments may be passes in the form of expressions to the called function. In such a
case, arguments are first evaluated and converted to the type of formal parameter and
then the body of the function gets executed.
10. Differentiate call by value and call by reference.
 Call by value: The values of the variables are passed by the calling function to the called
function.
 Call by reference: The addresses of the variables are passed by the calling function to

21
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

the called function.


11. Write the advantages of call by reference technique.
The advantages of call by reference technique are,
 Arguments are not copies into the new variables, it provides greater time and space
efficiency.
 Function can change the value of the argument and the change is reflected in the calling
function.
12. Write the disadvantages of call by reference technique.
However, the drawback of using this technique is that if inadvertent changes are caused
to variables in the called function then these changes would be reflected in calling function as
original values would have been overwritten.
13. What is recursion?
Recursion is the process of repeating items in a self similar way. In programming
languages, if a program allows you to call a function inside the same function, then it is called a
recursive call of the function.
14. What is pointer?
Every variable in C has a name and a value associated with it. When a variable is
declared, a specific block of memory within the computer is allocated to hold the value of that
variable. The size of the allocated block depends on the datatype. A pointer is a variable that
contains the address of another variable.
15. How to declaring pointer variables?
The general syntax of declaring pointer variables can be given as below.

data_type *ptr_name;

16. Define Null pointers.


Null pointer which is a special pointer value and does not point to any value. This means
that a null pointer does not point to any valid memory address.
To declare a null pointer, you may use the predefined constant NULL which is defined in
several standard header files including <stdio.h>, <stdlib.h> and <string.h>
17. Define generic pointers.

22
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

A generic pointer is a pointer variable that has void as its data type. The void pointer or
generic pointer is a special type of pointer that can point to variables of any data type. It is
declared like a normal pointer variable but using the void keyword as the pointer's data type.
Example: void *ptr;
18. Define pointer to pointer.
The pointers in turn point to data or even to other pointers. To declare pointer to pointer,
just add an asterisk * for each level of reference.
19. Write the drawbacks of pointers.
Pointers are very useful in C, they are not free from limitations. If used incorrectly,
pointers can lead to bugs that are difficult to unearth.
Example: If you use a pointer to read a memory location but that pointer is pointing to an
incorrect location, then you may end up reading a wrong value. An erroneous input always leads
to an erroneous output. Thus however efficient our program code may be, the output will always
be disastrous.
20. Differentiate * and &.
* Value at operator Gives value stored at particular address
& Address operator Gives address of variable
21. What does the following declaration tells compiler?
int *ptr;
 'ptr' is declared as that 'ptr' will be used only for storing the address of the integer valued
variables.
 We can also say that 'ptr' points top integer value at the address contained in 'ptr' as
integer.
22. How to passing an entire one-dimensional array to a function?
While passing arrays as arguments to the function, only the name of the array is passed
(,i.e, starting address of memory area is passed as argument).
Example:
#include <stdio.h>
float average(float age[]);
int main()

23
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

{
float avg, age[] = { 23.4, 55, 22.6, 3, 40.5, 18 };
avg = average(age); /* Only name of array is passed as argument. */
printf("Average age=%.2f", avg);
return 0;
}
float average(float age[])
{
int i;
float avg, sum = 0.0;
for (i = 0; i < 6; ++i)
{
sum += age[i];
}
avg = (sum / 6);
return avg;
}
23. Differentiate between an array and pointer?
The difference between arrays and pointers are as follows.
No. Array Pointer
Array allocates space automatically Pointer is explicitly assigned to point to an
1
allocated space.
2 It cannot be resized. It can be resized using realloc().
3 It cannot be reassigned. Pointers can be reassigned.
Size of (array name) gives the number of Size of (pointer name) returns the number of
4
bytes occupied by the array. bytes used to store the pointer variable.

24. Write a C program to swap two numbers.


#include<stdio.h>
int main()
Output:

24 Enter the value of x and y:32 18

Before swapping

X=32

Y=18
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

{
int x,y,temp;
printf("Enter the value of x and y:\n");
scanf("%d%d",&x,&y);
PRIntf("Before swapping\nX=%d\nY=%d\n",x,y);
temp=x;
x=y;
y=temp;
printf("After swapping\nX=%d\nY=%d\n",x,y);
return 0;
}
25. Demonstrate use of reference operator in C program.
#include <stdio.h>
int main()
{
int var = 5; Output:

printf("Value: %d\n", var); Value: 5


Address: 2686778
printf("Address: %u", &var); //Notice, the ampersand(&) before var.
return 0;
}
PART-B
1. Explain in detail about recursion with example.
Function is called within the same function
Write factorial program
2. Explain in detail about pointers with example.
Address of a value
Advantage of pointer
Usage of pointer
Address Of Operator
Declaring a pointer

25
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

NULL Pointer
3. Write a C program to compute sine series.
4. Design a scientific calculator using built-in functions in C.
5. Explain detail about pointers and arrays.
A pointer variable takes different addresses as value whereas, in case of array it is fixed.
Relation between Arrays and Pointers
6. Write a C program to access array elements using Pointers.
7. Write a program in C to find the number of 500, 100, 50, 20, 10, 5, 2, 1 rupee notes in a
given amount.
8. Write a C program to sort a list in alphabetic order using pointers.
UNIT - IV
STRUCTURES
PART - A
1. Define structure.
Structure is a user defined data type in C. structure helps to construct a complex data type
in more meaningful way. It is somewhat similar to an array. The only difference is that array is
used to store collection of similar data types while structure can store collection of any type of
data. A structure is therefore a collection of variables under a single name. structure is used to
represent a record.
2. Define self referential structure.
A self referential structure is one of the data structures which refer to the pointer to
another structure of the same type. That is, a self referential structure, in addition to other data,
contains a pointer to a data that is of the same type as that of the structure. A self referential
structure is used to create data structures like linked lists, stacks, etc.
3. Define dynamic memory allocation.
C dynamic memory allocation refers to performing manual memory management in the C
programming language via a group functions in the C standard library, namely malloc, realloc,
calloc and free. To access structure member using pointers, memory can be allocated
dynamically using malloc() function defined under "stdlib.h" header file.
4. Define typedef.

26
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

The typedef keyword enables the programmer to create a new data type name by using an
existing data type. By using typedef, no new data is created, rather an alternate name is given to
a known data type.
Syntax: typedef existing_data_type new_data_type;
Where, typedef statement does not occupy any memory; it simply defines a new type.
5. Define nested structure.
A structure can be placed within another structure, i.e., a structure may contain another
structure as its member. A structure that contains another structure as its member is called a
nested structure. The easier and clearer way is to declare the structures separately and then group
them in the higher level structure. When you do this, take care to check that nesting must be done
from inside out (from lowest level to the most inclusive level), i.e., declare the innermost
structure, then the next level structure, working towards the outer (most inclusive) structure.
6. What is malloc()?
 malloc() takes a single argument (the amount of memory to allocate in bytes).
 malloc() does not initialize the memory allocated.
7. What is calloc()?
 calloc() needs two arguments (the number of variables to allocate in memory and the size
in bytes of a single variable).
 calloc() guarantees that all bytes of the allocated memory block have been initialized to 0.
8. What is linked list?
A linked list is a collection of data elements called nodes in which the linear
representation is given by links from one node to the next node.
9. What are the basic operations on linked list?
The basic operations on linked list are,
(i) Create (ii) Delete (iii) Search (iv) Insert (v) Display
10. Differentiate structure and union.

No. Description Structure Union


Keyword The keyword struct is used to The keyword union is used to define
1
define a structure a union.
Size The compiler allocates the The compiler allocates the memory
2 memory for each structure by considering the size of the largest
member. Size of the structure is ≥ memory. So, size of union is equal to
27
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

to the sum of the each member's the size of largest member.


size.
Memory Each member within a structure Memory allocated is shared by
3 is assigned unique storage area of individual members of union.
location.
Value altering Altering the value of a member Altering the value of any of the
4 will not affect other members of member will alter other member
the structure. values.
Accessing Individual member can be Only one member can be accessed at
5
members accessed at a time. a time.
Initialization Several members of a structure Only the first member of a union can
6
of members can initialize at once. be initialized.

11. Difference between array and structure.

No. Arrays Structure


An array is a collection of data items A structure is a collection of data items of
1
of same data types. different data types.
Arrays can only be declared. There is Structures can be declared and defined. The
2
no keyword for arrays. keyword for structures is struct.
An array name represents the address A structure name is known as tag. It is a
3
of the starting element. shorthand notation of the declaration.
4 An array cannot have bit fields. A structure may contain bit fields.

12. Notes on deletion in single linked list.


There are 3 situations for deleting the elements in a list.
 Deletion at beginning of the list.
 Deletion at the middle of the list.
 Deletion at the end of the list.
13. How traversing is happen in a linked list?
Traversing a linked list means accessing the nodes of the list in order to perform some
processing on them. Remember a linked list always contains a pointer variable start which stores
the address of the first node of the list. End of the list is marked by storing NULL or -1 in the
NEXT field of the last node.
For traversing the linked list, we also make use of another pointer variable ptr which
points to the node that is currently being accessed.
14. Define searching for a value in a linked list.

28
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

Searching a linked list means to find a particular element in the linked list. A linked list
consists of nodes which are divided into two fields, the data field and next field. So searching
means finding whether a given value is present in the data field of the node or not. If it is present,
the algorithm returns the address of the node that contains the value.
15. What are the functions supports for dynamic memory allocation?
The functions supports for dynamic memory allocation are,
i. malloc
ii. realloc
iii. calloc
iv. free
16. Write the routines to delete the first node.
When the element is at first

temp=head
head=head->next
if(head==NULL)
printf(”Element is not found”);
else if(head->data==x)
{
temp=head;
head=head->next;
free(temp);
}
17. How to traverse or display the linked list?
if(temp==NULL)
printf("The list is empty");

29
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

while(temp!=NULL)
{
cout<<temp->data;
temp=temp->next;
}
18. Write the routines to delete the middle node.
Deletion at middle

ptr=head;
while(ptr->next!=NULL)
{
if(ptr->next->data= =2)
{
temp=ptr->next;
ptr->next=temp->next;
free(temp);
}
}
19. How to represent a linked list using structure?
typedef struct node
{
int data; //data field
struct node*next; //link field

30
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

}ptr;
20. Write the routine for create a linked list.
When the list is empty

When the list is not empty

if(head==NULL) //When nothing in the list


head=temp;
else
{
ptr=head;
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=temp;
}
21. Write the routine for Inserting a node at first.

temp->next=head;
head=temp;
22. Write the routine for Insert at middle.

31
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

ptr=head;
while(ptr!=NULL)
{
if(ptr->data==y)
{
temp->next=ptr->next;
ptr->next=temp;
}
ptr=ptr->next;
23. How to access the members of structure.
A structure member variable is generally accessed using a '.' (dot) operator. The syntax of
accessing a structure or a member of a structure can be given as:

struct_var.member_name;

A dot operator is used to select a particular member of the structure.


24. How to copy and compare structure.
We can assign a structure to another structure of the same type.
Example:
If we have two structure variables emp1 and emp2 of type struct employee given as,
struct employee emp1={111,'aaron','pc',750000};
struct employee emp2;
then to assign one structure variable to another, we will write emp2=emp1;
25. Write short notes on inserting a new node in a linked list.

32
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

There are three situations for inserting element in a list.


i. Insertion at the front of list.
ii. Insertion in the middle of the list.
iii. Insertion at the end of the list.
PART - B
1. Explain linked list and its operation
Store a collection of elements
Node
Declaring a Linked list
Creating a Node
Traversing the list
Write the routines for deleting a node, inserting a node
2. Explain dynamic memory allocation.
Enables the C programmer to allocate memory at runtime
Four functions
1. malloc()
2. calloc()
3. realloc()
4. free()
Difference between static memory allocation and dynamic memory allocation
3. Explain nested structure.
Another structure as a member
Two ways to define: Separate structure, Embedded structure
Accessing Nested Structure
4. Explain self referential structure.
To create data structures like linked lists, stacks, etc
5. How to define and use the structure?
Allows you to hold different type of elements
Defining structure
Declaring structure variable

33
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

Accessing members of structure

6. Write a C program to store information in structure and display it


7. Write a C program to add two complex numbers.
UNIT - V
FILE PROCESSING
PART - A
1. What do meant by file?
A file is a collection of related records. A file can have fixed length records or variable
length records.
2. How a file does is represented?
A file represents a sequence of bytes on the disk where a group of related data is stored.
File is created for permanent storage of data.
3. What are the needs of files?
To execute the program with large amount of input data is time consuming to enter the
entire data. But, if file is created, this information can be accesses using few commands.
4. What is file pointer?
A file pointer is a pointer to a structure, which contains information about the file,
including its name, current position of the file, whether the file is being read or written and
whether errors or end of the file have occurred.
5. List the file attributes.
(i) File name (ii) File position (iii) File structure (iv) Read only (v) Hidden (vi) Volume label
(vii) Directory (viii) Archive
6. Differentiate text file and binary file.
No. Text file Binary file
Stores data in the form of alphabets, digits and Contains a sequences or a collection
1 other special symbols by storing their ASCII of bytes made of 0 and 1.
values.
Small error in a textual file can be recognized and Small error in a binary file corrupts
2
eliminated when we see. the file and it is not easy to detect.
3 It can be readable by the human. It cannot be readable by the human.
Text file is created by the programmer. Binary file is generated by the
4
compiler.
7. What are the basic operations of file?
34
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

The basic operations in files are,


i. Creation of a new file
ii. Opening an existing file
iii. Reading data from a file
iv. Writing data in a file
v. Closing a file.
8. Write the steps for processing a file.
i. Declare a file pointer variable.
ii. Open a file using fopen() function.
iii. Process the file using suitable function.
9. Give the syntax to open the file.
*fp = FILE *fopen(const char *filename, const char *mode);
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.filename is the name of the file to be opened and mode specifies the purpose of
opening the file.
10. What does the mode a+ represent?
The file can be opened for reading and appending and create the file if it does not exist.
The reading will start from the beginning but writing can only be appended.
11. What is getc() and getw()?
getc() is used to read a character from a file that has been opened in read mode by fopen()
function.
Syntax:
int getc(FILE*stream);

getw() is used to read a integer from a file that has been opened in read mode.

Syntax: int getc(FILE*stream);

12. What is feof()?


The feof() function returns true in case if end of file is reached. It detects end of file
marker in a file.

35
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

Syntax:
int feof(FILE*stream);

13. What is the function fseek() and ftell()?


fseek():
It is used to move the reading control to different positions using fseek function.
Syntax:

fseek( file pointer, displacement, pointer position);

Where
file pointer ---- It is the pointer which points to the file.
displacement ---- It is positive or negative. This is the number of bytes which are skipped
backward (if negative) or forward( if positive) from the current position. This is attached with L
because this is a long integer.
ftell():It tells the byte location of current position of cursor in file pointer.
Syntax:
ftell(fptr);

14. What are the benefits of file organization methods?


 Rapid access to one or more records.
 Ease of inserting/updating/deleting one or more records without disrupting the speed of
accessing records.
 Efficient storage of records.
 Using redundancy to ensure data integrity.
15. Is random access is the best access method? If yes justify your answer.
Yes, the data or file can be accessed from any location in the memory. There is no
wastage of time to reach the exact location of the file.
16. What are the types of file access methods?
The files can be accessed in two ways. They are,
Sequential access file: The data are placed in the file in a sequence like beads on a string. Data
are processed in sequence, one after another. To reach particular item of a data, all the data that
proceeds must read it first.

36
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

Random access file: The data are placed into the file by going directly to the location in the file
assigned to each data item. Data are processed in any order. Particular item of data can be
reached by going directly to it, without looking at any other data.
17. Where does the sequential file access is suitable?
Sequential files are generally used to generate reports or to perform sequential reading of
large amount of data which some programs need to do such as payroll processing of all the
employees of an organization.
18. Differentiate random and sequential access methods.
No. Sequential Access Random Access
1 Read and write operation is dome A random-access data file enables you read
sequentially, starting from the beginning of or write information anywhere in the file
the file.
2 Record length can be different. Record length is same.
19. What is the use of key in sequential access?
The key field uniquely identifies a record in a file. Thus, every record has a different
value for the key filed. Records can be sorted in either ascending or descending order.
20. give the advantages of sequential access.
 Simple and easy to handle.
 No extra overheads involved.
 Sequential files can be stored on magnetic disks as well as magnetic tapes.
 Well suited for batch oriented applications.
21. Give the disadvantages of sequential access.
 Records can be read only sequentially.
 If ith record has to be read, then all the i-1 records must be read.
 Does not support any update operation.
 A new file has to be created and the original file has to be replaced with the new file that
contains the desired changes.
 Cannot be used for interactive applications.
22. What do you meant by random access?
To read data in the middle of the file and same can be accessed directly. File organization
provides random access by directly jumping to the record which has to be accessed.
23. Why does random access files is very much essential?
37
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

 Real time applications require immediate response.


 Example: Respond to customer query about a bill sequencing through records for account
is time-intensive.
 Airline reservation systems.
 Banking systems.
 Point-of sale systems.
24. How does the address of the record to be accesses is calculated in random access
method?
The address of the record to be accesses is calculated in random access method by,
Address of ith record=base_address+(i-1)*record_length
25. Give the features of random access method.
 Provides an effective way to access individual records.
 The record number represents the location of the record relative to the beginning of the
file.
 Records in a relative file are of fixed length.
 Relative files can be used for both random as well as sequential access.
 Every location in the table either stores a record or is marked as FREE.
26. How can you say random access is the best method.
 Ease of processing.
 If the relative record number of the record that has to be accessed is known, then the
record can be accesses instantaneously.
 Random access of records makes access to relative files fast.
 Allows deletion and updation in a same file.
 Provides random as well as sequential access of records with low overhead.
 New records can be easily added in the free locations based on the relative record number
of the record to be inserted.
 Well suited for interactive applications.
27. What is meant by command line arguments? How many arguments used in command
line?

38
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

Command line argument is a parameter supplied to the program when it is involved. It is


mostly used when it is essential to control the user program from outside, command line
arguments are passes to main() function. It accepts arguments from command line or from other
shell scripts by following commands:

int main(int argc,char *argv[])


Where, argc-Counts the number of arguments on the command line.
argv[] - Pointer array which holds pointer of type char which points to the arguments
passed to the program.
PART - B
1. Explain the various operations can be carried out in the file with example.
1. Creating a new file
2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file
Write the functions in file operations
Difference between Append and Write Mode
2. List the types of files. Discuss the different functions will be performed on the file.
Sequential file
Random file
fseek()
ftell()
rewind()
3. Describe in detail about the command line argument.
Parameter supplied to the program when it is invoked
Write the syntax and example program.
4. Write a C program to read name and marks of n number of students from user and
store them in a file.
5. Write a C program to read character by character from the user and write them into a
file using fputc() and read the same data from the file using fgetc() and display that on the
screen.

39
Programming in C Ms. A.Mary JaNiS, Assistant Professor/CSE, Alpha College of Engineering

6. Write a program to read integer data from the user and write it into the file using putw()
and read the same integer data from the file using getw() and display it on the output
screen.

40

You might also like