0% found this document useful (0 votes)
6 views51 pages

APIC Q ALL

The document provides a comprehensive overview of various programming concepts in C, including variables, pointers, functions, arrays, and file handling. It explains key differences between local and global variables, the use of void pointers, and the distinctions between structures and unions. Additionally, it covers array declarations, function implementations, recursion, and file opening modes, along with examples and code snippets for better understanding.

Uploaded by

vanshkhandwala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views51 pages

APIC Q ALL

The document provides a comprehensive overview of various programming concepts in C, including variables, pointers, functions, arrays, and file handling. It explains key differences between local and global variables, the use of void pointers, and the distinctions between structures and unions. Additionally, it covers array declarations, function implementations, recursion, and file opening modes, along with examples and code snippets for better understanding.

Uploaded by

vanshkhandwala
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 51

2 marks Questions

1 What is the difference between Local variable and Global variable?

In C, variables can be declared before they are used in the programs. Here the main difference
between a local and a global variable is that, a local variable is declared inside a function block, where as
the global variable is declared outside the functions in the program.
2 How to declare and define string?

The general form of declaration of a string variable is:


Syntax: char string_name[size];

The size determines the number of characters in the string_name. Some examples are:
Example: char city[10];
char name[30];

string can be initialized in the following forms:


Example: char str[9
\
When the compiler assigns a character string to a character array, it automatically supports a null character
\

3 What is void pointer?

Void pointer or generic pointer is a special type of pointer that can be pointed at objects of any data type.

Pointers defined using specific data type cannot hold the address of the some other type of variable.
Declaration of void pointer:
Syntax:
void *pt_name;
Example:
void *v;
int *i;
int ivar;

4 Differentiate printf() and fprintf() functions?


give an output in a formatted way to a display device such as computer screen.
The syntax of printf function is as follows.

prinf("Format specifers",value1,value2,..);

Formatted string and list of parameters are passed to printf function.

The fprinf function is used to output a formatted string to a file. The syntax for fprintf is as follows;
File pointer, formatted string and list of parameters are passed to the fprintf function. e.g.

5 Give limitations of array.

The number of element, which is to be stored in an array, must be known first.


When an array is declared, memory is allocated to it. If array is not filled completely, then vacant
place occupies memory.
These are static structure, Static in the sense that memory is allocated at compilation time their
memory used by them cannot be reduced or extended.
6 Differentiate actual and dummy arguments.

The terms & are synonymous to the


terms & respectively.

Formal Argument :

The formal arguments are the arguments in the function declaration. The scope of formal arguments is
local to the function definition in which they are used. They belong to the called function.

Actual arguments :

The arguments that are passed in a function call are called actual arguments. These arguments are defined
in the calling function.

To sum up in one line Calling programs pass information to called functions in

7 Define pointer. Write advantages of a pointer


A pointer is a variable that contains address or location of another variable

Pointer is a derived data type in C.

Example:

void main()

int a=10, *p;

p = &a; // Assign memory address of a to pointer variable p


}

Output: 10 10 5000

Variable Value Address

A 10 5000

P 5000 5048

Advantages :

(i) Pointers reduce the length and complexity of a program.


(ii) They increase execution speed.
(iii) A pointer enables us to access a variable that is defined outside the function.
(iv) Pointers are more efficient in handling the arrays and structures.
(v) The use of a pointer array of character strings results in saving of data storage space
in memory.

8 Define fseek() function.

fseek() is used to move file pointer associated with a given file to a specific position.

Syntax: int fseek(FILE *pointer, long int offset, int position)

The fseek() function takes three arguments, first is the file pointer, second is the offset that specifies
the number of bytes to moved and third is the position from where the offset will move.
It will return zero if successfully move to the specified position otherwise return nonzero value.
There are three positions from where offset can move.

Constant Name Constant Value Description

SEEK_SET 0 The beginning of file

SEEK_CUR 1 The current position in file

SEEK_END 2 The end of file

9 Define typedef.
The C programming language provides a keyword called typedef, which you can use to give a type a new
name. Following is an example to define a term BYTE for one-

typedef int BYTE;

After this type definition, the identifier BYTE can be used as an abbreviation for the type int, for example.

BYTE b1, b2;


10 Define array. Give examples where array can be used.

An array is a group of elements with same data type referred by common name.

An array is a data structure, which can store a fixed-size collection of elements of the same data type. An
array is used to store a collection of data, but it is often more useful to think of an array as a collection of
variables of the same type.
11 List the elements those are included in function implementation.

A function is a block of code that performs a specific task.


The functions which are created by programmer are called user-defined functions.
The functions which are implemented in header libraries are known as library functions.
It has a unique name and it is reusable i.e. it can be called from any part of a program.
Parameter or argument passing to function is optional.
It is optional to return a value to the calling program. Function which is not returning any value
from function, their return type is void.
While using function, three things are important

1) Function Declaration:
Like variables, all the functions must be declared before they are used.
The function declaration is also known as function prototype or function signature. It
consists of four parts,

a) Function type (return type).


b) Function name.
c) Parameter list.
d) Terminating semicolon

Syntax: <return type> FunctionName (Argument1, Argument2,

Example: int sum (int , int) ;

In this example, function return type is int, name of function is sum, 2 parameters are passed to function
and both are integer.

2) Function Definition:

Function Definition is also called function implementation.


It has mainly two parts.
a) Function header: It is same as function declaration but with argument name.
b) Function body: It is actual logic or coding of the function

3) Function call:

Function is invoked from main function or other function that is known as function call.
Function can be called by simply using a function name followed by a list of actual argument
enclosed in parentheses.
Syntax or general structure of a Function:

{
Statement-1;
Statement-2;
Statement-3;
Functions
}
An example of function:

#include<stdio.h>
int sum(int, int); \\ Function Declaration or Signature
void main()
{
int a, b, ans;

ans = sum(a, b); \\ Function Calling

int sum (int x, int y) \\ Function Definition


{
int result;
result = x + y;
return (result);
}

12 Write the advantages and disadvantages of recursion.

Advantages:
Reduce unnecessary calling of function.
Easy solution for recursively defined solution.
Complex programs can be easily written with less code.
Disadvantages:
Recursive code is difficult to understand and debug.
Terminating condition is must; otherwise it will go in an infinite loop.
Execution speed decreases because of function call and return activity many times.
13 Give the differences between structure and union.

Structure Union
Each member is assigned its own uniqstorage
All members share the same storage area.
area.
Maximum memory requi red by the member is
Total memory requi red by all memberallocated.
allocated.
Only one member is active a time.
All members are active at a time.
Only the first member can be initialized.
All members can be initialized.
Requires more memory. Requires less memory.
Example:
Example:
struct SS
union UU
{
{
int a;
int a;
float b;
float b;
char c;
char c;
};
};
4 bytes b a c
1 byte for c
for
2 bytes for a
c,b,a
4 bytes for b
4 bytes are there between a,b and c because
Total bytes = 1 + 2 + 4 = 7 bytes. largest memory occupies by float which is 4
bytes.
14 What are the different modes in which a file can be opened?

When we open any file for processing, at that time we have to give file opening mode.
We can do limited operations only based on mode in which file is opened.

C has 6 different file opening modes for text files:


1) r open for reading only.
2) w open for writing (If file exists then it is overwritten)
3) a open for appending (If file does not exist then it creates new file)
4) r+ open for reading and writing, start at beginning
5) w+ open for reading and writing (overwrite file)
6) a+ open for reading and writing, at the end (append if file exists)
Same modes are also supported for binary files by just adding b, e.g. rb, wb, ab, r+b, w+b, a+b
15 Give definition of multi-dimensional array and give one example of multi-Dimensional
array.
In C programming, you can create array of an array known as multidimensional array. For example, ...
Here, x is a two-dimensional (2d) array. The array can hold 12 elements. You can think the array as table
with 3 row and each row has 4 column.
Syntax:
data_type array_name[size1][size2]....[sizeN];

data_type: Type of data to be stored in the array.


Here data_type is valid C/C++ data type
array_name: Name of the array
size1, size2,... ,sizeN: Sizes of the dimensions.
e.g. int three_d[10][20][30];

3/4 marks Questions.


1 Explain declaration and initialization of 2-D array with example.

Two dimensional arrays:


Two dimensional arrays are also called table or matrix.
Two dimensional arrays have two subscripts.
First subscript denotes the number of rows and second subscript denotes the number of columns.
Syntax : data_type array_name [row_size] [column_size];
Example : float marks [10][20];
Here a mark is declared as a matrix having 10 rows (0 to 9) and 20 columns (0 to 19). The first
element of the matrix is marks[0][0] and the last row last column is marks[9][19]
A two dimensional array marks[4][3] is shown below. The first element is given by
marks[0][0]contains 35.5 & second element is marks[0][1] and contains 40.5 and so on.

marks [0][0] marks [0][1] marks [0][2]


35.5 40.5 45.5
marks [1][0] 66.5 marks [1][1] marks [1][2]
55.5 60.5
marks [2][0] marks [2][1] marks [2][2]
85.5 78.5 65.3
marks [3][0] marks [3][1] marks [3][2]
25.6 35.2 76.2

Initialization of two dimensional array:


1. int table [2][3] = {1,2,3,4,5,6}; will initialize 1 st row 1st column element to 1, 1st row 2nd column
to 2, 1st row 3rd column to 3, 2row 3rd column to 6 and so on.
2. int table [2][3] = {{1,2,3},{4,5,6}}; here, 1 st group is for 1st row and 2nd group is for 2nd row. So
1st row 1st column element is 1, 2row1st column element is 4, 2nd row 3rd column element is 6 so
on.
3. int table [2][3] = {{1,2},{4}}
Initializes as above but missing elements will be initialized by 0.

2 Explain how an element will be inserted at position p into a single dimensional array
of size n.

#include <stdio.h>
#include<conio.h>

void main()
{
int array[50], position, c, n, value;

printf("Enter number of elements in the array\n");


scanf("%d", &n);

printf("Enter %d elements\n", n);

for (c = 0; c < n; c++)


{ scanf("%d", &array[c]); }

printf("Please enter the location where you want to insert an new element\n");
scanf("%d", &position);

printf("Please enter the value\n");


scanf("%d", &value);

for (c = n - 1; c >= position - 1; c--)


{
array[c+1] = array[c];
}

array[position-1] = value;
n++;

printf("Resultant array is\n");

for (c = 0; c <n; c++)


{
printf("%d\n", array[c]);
}

getch();
}
5 Write a program of addition for two 3x3 matrix.

//C program for matrix addition:


#include <stdio.h>

void main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];

printf("Enter the number of rows and columns of matrix\n");


scanf("%d%d", &m, &n);
printf("Enter the elements of first matrix\n");

for (c = 0; c < m; c++)


for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);

printf("Enter the elements of second matrix\n");

for (c = 0; c < m; c++)


for (d = 0 ; d < n; d++)
scanf("%d", &second[c][d]);

printf("Sum of entered matrices:-\n");

for (c = 0; c < m; c++) {


for (d = 0 ; d < n; d++) {
sum[c][d] = first[c][d] + second[c][d];
printf("%d\t", sum[c][d]);
}
printf("\n");
}

}
OUTPUT:
Enter the number of rows and columns of matrix 3 3
Enter the elements of first matrix
1
2
3
4
5
6
7
8
9
Enter the elements of first matrix 3 3
1
2
3
4
5
6
7
8
9
Sum of entered matrices:-
2 4 6
8 10 12
14 16 18
6 Write a C program to read N elements into a single dimensional array and sort it.

//C program to accept N numbers and arrange them in an ascending order


#include <stdio.h>
void main()
{
int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);

printf("Enter the numbers \n");


for (i = 0; i < n; ++i)
scanf("%d", &number[i]);

for (i = 0; i < n; ++i)


{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;

}
}
}

printf("The numbers arranged in ascending order are given below \n");


for (i = 0; i < n; ++i)
printf("%d\n", number[i]);

OUTPUT:
Enter the value of N
6
Enter the numbers
3
78
90
456
780
200
The numbers arranged in ascending order are given below
3
78
90
200
456
780
7 Explain how to read and print one dimensional string array with example.

#include <stdio.h>

void main()
{
int arr[10];
int i;
printf("\n\nRead and Print elements of an array:\n");
printf("-----------------------------------------\n");

printf("Input 10 elements in the array :\n");


for(i=0; i<10; i++)
{
printf("element - %d : ",i);
scanf("%d", &arr[i]);
}

printf("\nElements in array are: ");


for(i=0; i<10; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
}
OUTPUT:
Read and Print elements of an array:
-----------------------------------------
Input 10 elements in the array :
element - 0 : 1
element - 1 : 1
element - 2 : 2
element - 3 : 3
element - 4 : 4
element - 5 : 5
element - 6 : 6
element - 7 : 7
element - 8 : 8
element - 9 : 9

Elements in array are: 1 1 2 3 4 5 6 7 8 9


8 Write a C program to read 10 elements into a single dimensional array and
find minimum number in that array.

#include <stdio.h>
#include<conio.h>

void main()
{
int array[100], minimum, size, c, location = 1;

printf("Enter number of elements in array\n");


scanf("%d", &size);

printf("Enter %d integers\n", size);

for (c = 0; c < size; c++)


scanf("%d", &array[c]);

minimum = array[0];

for (c = 1; c < size; c++)


{
if (array[c] < minimum)
{
minimum = array[c];
location = c+1;
}
}

printf("Minimum element is present at location %d and it's value is %d.\n", location, minimum);
return 0;
}

9 Explain how to initialize one dimensional array with example.

Single Dimensional Array:


An array using only one subscript to represent the list of elements is called single dimensional
array.

Syntax : data_type array_name [size];


Example : int marks [5];

An individual array element can be used anywhere like a normal variable with a statement such as
g = marks [60]; More generally if i is declared to be an integer variable, then the statement
g=marks[i]; will take the value contained at ith position in an array and assigns it to g.
We can store value into array element by specifying the array element on the left hand side of the
equals sign like marks[60]=95; The value 95 is stored at 60 th position in an array.
The ability to represent a collection of related data items by a single array enables us to develop
Concise and efficient programs.
For example we can very easily sequence through the elements in the array by varying the value of
the variable that is used as a subscript into the array.
for(i=0; i<66; i++)
{
sum = sum + marks[i];
}
Above for loop will sequence through the first 66 elements of the marks array (elements 0 to 65)
and will add the values of each marks into sum. When for loop is finished, the variable sum will
then contain the total of first 66 values of the marks.

The declaration int values[5]; would reserve enough space for an array called values that could
hold up to 5 integers. Refer to the below given picture to conceptualize the reserved storage space.

// Program to find the average of n (n < 10) numbers using arrays


#include <stdio.h>
void main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter n: ");
scanf("%d", &n);
for(i=0; i<n; ++i)
{
printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum/n;

printf("Average = %d", average);

return 0;
}
Output

Enter n: 5
Enter number1: 45
Enter number2: 35
Enter number3: 38
Enter number4: 31
Enter number5: 49
Average = 39
10 Write different styles to declare and initialize pointers.

A pointer is initialized in the following way:


Pointervariable = &variable;
In above declaration &variable signifies the address of variable.
For example :

Char *chptr = &ch;


Or

Char *chptr;
Chptr =&ch;
Or
Char ch,*chptr=&ch;

11 Explain various string handling operation

C has several inbuilt functions to operate on string. These functions are known as string handling functions.
Example:

Function Meaning
Returns length of the string.
strlen(s1)
l = strlen(s1); it returns 5
Compares two strings.
It returns negative value if s1<s2, positive if s1>s2 and zero if s1=s2.
strcmp(s1,s2)
Output : -9
Copies 2nd string to 1st string.
strcpy(s1,s2) strcpy(s1,s2) copies the string s2 in to string s1 so s1 is now

Appends 2string at the end of 1string.


strcat(s1,s2); a copy of string s2 is appended at the end of string s1.
strcat(s1,s2)
Now s1

Returns a pointer to the first occurrence of a given character in the


string s1.
strchr(s1,c)
Output : ir
Returns a pointer to the first occurrence of a given string s2 in string
s1.
strstr(s1,s2)
Output : heir
Reverses given string.
strrev(s1)
Converts string s1 to lower case.
strlwr(s1)
strupr(s1) Converts string s1 to upper case.
strncpy(s1,s2,n) Copies first n character of string s2 to string s1
strncat(s1,s2,n) Appends first n character of string s2 at the end of string s1.
Compares first n character of string s1 and s2 and returns similar result
strncmp(s1,s2,n)
as
strrchr(s1,c) Returns the last occurrence of a given character in a string s1.
13 Explain merging operation of arrays and write C example.

/* C Program - Merge Two Arrays */

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int arr1[50], arr2[50], size1, size2, size, i, j, k, merge[100];
printf("Enter Array 1 Size : ");
scanf("%d",&size1);
printf("Enter Array 1 Elements : ");
for(i=0; i<size1; i++)
{
scanf("%d",&arr1[i]);
}
printf("Enter Array 2 Size : ");
scanf("%d",&size2);
printf("Enter Array 2 Elements : ");
for(i=0; i<size2; i++)
{
scanf("%d",&arr2[i]);
}
for(i=0; i<size1; i++)
{
merge[i]=arr1[i];
}
size=size1+size2;
for(i=0, k=size1; k<size && i<size2; i++, k++)
{
merge[k]=arr2[i];
}
printf("Now the new array after merging is :\n");
for(i=0; i<size; i++)
{
printf("%d ",merge[i]);
}
getch();
}

14 Write use of sorting in an array and write C example.

A Sorting Algorithm is used to rearrange a given array or list elements according to a comparison operator
on the elements. The comparison operator is used to decide the new order of element in the respective data
structure. For example: The below list of characters is sorted in increasing order of their ASCII values.
/*
* C program to accept N numbers and arrange them in an ascending order
*/

#include <stdio.h>
void main()
{

int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);

printf("Enter the numbers \n");


for (i = 0; i < n; ++i)
scanf("%d", &number[i]);

for (i = 0; i < n; ++i)


{

for (j = i + 1; j < n; ++j)


{

if (number[i] > number[j])


{

a = number[i];
number[i] = number[j];
number[j] = a;

printf("The numbers arranged in ascending order are given below \n");


for (i = 0; i < n; ++i)
printf("%d\n", number[i]);

}
15 Write a program to create a pointer to string and display the string in reverse using
pointer.

Creating a string
In the following example we are creating a string str using char character array of size 6.

char str[6] = "Hello";


The above string can be represented in memory as follows.
char Str[6]
Index 0 1 2 3 4 5
Value H e l l o \0
address 1000 1001 1002 1003 1004 1005

Creating a pointer for the string


The variable name of the string str holds the address of the first element of the array i.e., it points at the
starting memory address.

So, we can create a character pointer ptr and store the address of the string str variable in it. This way, ptr
will point at the string str.
In the following code we are assigning the address of the string str to the pointer ptr.

char *ptr = str;


We can represent the character pointer variable ptr as follows.
char Str[6]
Index 0 1 2 3 4 5
Value H e l l o \0
address 1000 1001 1002 1003 1004 1005

Variable ptr
Value 1000
address 8000

The pointer variable ptr is allocated memory address 8000 and it holds the address of the string variable
str i.e., 1000.
Accessing string via pointer
To access and print the elements of the string we can use a loop and check for the \0 null character.

In the following example we are using while loop to print the characters of the string variable str.
#include <stdio.h>

int main(void) {

// string variable
char str[6] = "Hello";

// pointer variable
char *ptr = str;

// print the string


while(*ptr != '\0') {
printf("%c", *ptr);

// move the ptr pointer to the next memory location


ptr++;
}

return 0;
}
Program to Reverse a String using Pointers
#include <stdio.h>
#include <string.h>

// Function to reverse the string


// using pointers
void reverseString(char* str)
{
int l, i;
char *begin_ptr, *end_ptr, ch;

// Get the length of the string


l = strlen(str);

// Set the begin_ptr and end_ptr


// initially to start of string
begin_ptr = str;
end_ptr = str;

// Move the end_ptr to the last character


for (i = 0; i < l - 1; i++)
end_ptr++;

// Swap the char from start and end


// index using begin_ptr and end_ptr
for (i = 0; i < l / 2; i++) {

// swap character
ch = *end_ptr;
*end_ptr = *begin_ptr;
*begin_ptr = ch;

// update pointers positions


begin_ptr++;
end_ptr--;
}
}

// Driver code
int main()
{

// Get the string


char str[100] = "GeeksForGeeks";
printf("Enter a string: %s\n", str);
// Reverse the string
reverseString(str);

// Print the result


printf("Reverse of the string: %s\n", str);

return 0;
}
Output:
Enter a string: GeeksForGeeks
Reverse of the string: skeeGroFskeeG
17 Write a program to find out sum of digits of a given number using recursion.

/*
* C Program to find Sum of Digits of a Number using Recursion
*/
#include <stdio.h>

int sum (int a);

int main()
{
int num, result;

printf("Enter the number: ");


scanf("%d", &num);
result = sum(num);
printf("Sum of digits in %d is %d\n", num, result);
return 0;
}

int sum (int num)


{
if (num != 0)
{
return (num % 10 + sum (num / 10));
}
else
{
return 0;
}
}
18 Write a function to find out sum of one dimensional numeric array of five Elements.

#include<stdio.h>
int main()
{
int array[] = {1,2,3,4,5,6,7};
int sum;
sum = sum_array_elements(array,6);
printf("\nSum of array elements is:%d",sum);
return 0;
}
int sum_array_elements( int arr[], int n ) {
if (n < 0) {
//base case:
return 0;
} else{
//Recursion: calling itself
return arr[n] + sum_array_elements(arr, n-1);
}
}
Output:

Sum of array elements is:28


19 List out different types (categories) of UDF (User Defined Function) and explain any
one category of function with example.

Functions can be classified in one of the following category based on whether arguments are present or
not, whether a value is returned or not.

1) Functions with no arguments and no return value \\ void printline(void)


2) Functions with no arguments and return a value \\ int printline(void)
3) Functions with arguments and no return value \\ void printline(int a)
4) Functions with arguments and one return value \\ int printline(int a)

1. Function with no argument and no return value:


When a function has no argument, it does not receive any data from calling function.
When it does not return a value, the calling function does not receive any data from the
called function.
In fact there is no data transfer between the calling function and called function.
Example:
#include<stdio.h>
void printline (void); // No argument No return value
void main()
{ clrscr();
printline();
printf("\n LJU \n");
}
void printline (void)
{ int i;
for(i=0;i<10;i++)
{
printf("-");
}
}
void main() No void Fun1()
{ Input {

Fun1()
No
} Output }

2. Function with no arguments and return a value:


When a function has no argument, it does not receive data from calling function.
When a function has return value, the calling function receives one data from the called
Function.
Example:
#include<stdio.h>
int get_number ( ); // No argument
void main()
{
int m;
m=get_number();
printf("%d",m);
}
int get_number( )
{
int number;
printf("enter number:");
scanf("%d",&number);
return number; // Return value
}
void main() No int Fun1()
{ Input {

A = Fun1()
Function return no;
} result }
3. Function with arguments and no return values:
When a function has argument, it receives data from calling function.
When it does not return a value, the calling function does not receive any data from the called
function.
Example:
#include<stdio.h>

void sum (int,int); // Argument


void main()
{
int no1,no2;
printf("enter no1,no2:");
scanf("%d%d",&no1,&no2);
sum(no1,no2);
}
void sum (int no1,int no2)
{
if(no1>no2)
printf("\n no1 is gretest");
else
printf("\n no2 is gretest");
} // No return value
void main() Value of void Fun1(int a)
{ argument {

Fun1(a)
No
} Return value }

4. Function with arguments and one return value:


When a function has argument, it receives data from calling function.
When a function has return value, the calling function receives any data from the called function.
Example:
#include<stdio.h>
int sum (int); // Argument
void main()
{ int no,x;
clrscr();
printf("enter no:");
scanf("%d",&no);
x=sum(no);
printf("sum=%d",x);
getch();
}
int sum(int no)
{
int add=0,i;
while(no>0)
{
i=no%10;
add=add+i;
no=no/10;
}
return add; // Return value
}

void main() Value of void Fun1(int a)


{ argument {
B= Fun1(a)
Function return( e );
} Result }
20 Explain array of pointers with example.

As we have an individual
elements of an array will store the address values. So, array of pointers is a collection of pointers of same
type known by single name.

Syntax :
data_type *name[size];

Example:
int *ptr[5]; \\Declares an array of integer pointer of size 5
int mat[5][3]; \\Declares a two dimensional array of 5 by 2
Now, the array of pointers ptr can be used to point to different rows of matrix as follow
for(i=0;i<5;i++)
{
ptr[i]=&mat[i][0]; \\ Can be re-written as ptr[i]=mat[i];
}
Ptr 0 1 2
ptr[0]
ptr[1]
ptr[2]
ptr[3]
ptr[4]

By using dynamic memory allocation, we do not require to declare two-dimensional array, it can be created
dynamically using array of pointers.
21 Explain Pointer to Pointer with example.

A pointer to pointer is a chain of pointers.

Pointer contains the address of a variable.


When we define a pointer to a pointer, the first pointer contains the address of the second
Pointer, which points to the location that contains the actual value as shown below.
Declaration of pointer:
Syntax:
data_type **pt_name ;
Example:
char c = 'd';
char *p;
char **ptr;
p = &c;
ptr = &p;
printf("\n Value of c = %c",c);
printf("\n Address of c = %d", &c);
printf("\n Value of *p = %c",*p);
printf("\n Address of *p = %d",&p);
printf("\n Value of **ptr = %c",**ptr);
printf("\n Address of **ptr = %d",&ptr);
Output:
Value of c = d
Address of c = 2293575
Value of c = d
Address of c = 2293568
Value of c = d
Address of c = 2293564
22 Compare(Difference) Macro and Function.

Macro Function
Macros are just a text substitution tool. In C when one function makes call to another
function it is done in several steps which takes time
such as saving of system space, stack loading etc.
This increases size of your program. This decreases size of your program.
Best efficiency and result is achieved from a macro Best efficiency and result is achieved from a
when they are short and frequently used. function when they are long and complex.
Macros are not executable. Functions are executable code.
23 Write a program to find out sum of digits of a given number using recursion.

/*
* C Program to find Sum of Digits of a Number using Recursion
*/
#include <stdio.h>

int sum (int a);

int main()
{
int num, result;

printf("Enter the number: ");


scanf("%d", &num);
result = sum(num);
printf("Sum of digits in %d is %d\n", num, result);
return 0;
}

int sum (int num)


{
if (num != 0)
{
return (num % 10 + sum (num / 10));
}
else
{
return 0;
}
}
24 Explain * and & operators in pointer.

Operator Operator Name Purpose


* Value at Operator Gives Value stored at Particular
address
& Address Operator Gives Address of Variable

In
operator.

.
.

#include<stdio.h>

int main()
{
int n = 20;
printf("\nThe address of n is %u",&n);
printf("\nThe Value of n is %d",n);
printf("\nThe Value of n is %d",*(&n));
}
Output:
The address of n is 1002
The Value of n is 20
The Value of n is 20

25 Explain recursion with example.

Recursive function is a function that calls itself.


If a function calls itself then it is known as recursion.
Recursion is thus the process of defining something in terms of itself.
Suppose we want to calculate the factorial of a given number then in terms of recursion we can
write it as n! = n * (n-1)!.
First we have to find (n-1)! and then multiply it by n. the (n-1)! is computed as
(n-1)! = (n-1) * (n-2)!. This process end when finally we need to calculate 1! which is 1.
Ex: 4! =4*3!
=4*3*2!
=4*3*2*1!
=4*3*2*1
Terminating condition must be there which can terminate the chain of process, otherwise itwill lead
to infinite number of process. Tracing of function fact() for n=4
Example: Find factorial of a given number using recursion.
#include<stdio.h>
int fact (int);
void main()
{
int f,n;
printf("enter number:");
scanf("%d",&n);
f=fact(n);
printf("\n factorial=%d",f);
}
int fact (int n)
{
int f=1;
if(n==1)
{
return 1;
}
else
{
f=n*fact(n-1);
return f;
}
}

26 Explain how to access String using Pointer.

Creating a pointer for the string


The variable name of the string str holds the address of the first element of the array i.e., it points at the
starting memory address.

So, we can create a character pointer ptr and store the address of the string str variable in it. This way, ptr
will point at the string str.

In the following code we are assigning the address of the string str to the pointer ptr.

char *ptr = str;


We can represent the character pointer variable ptr as follows.

The pointer variable ptr is allocated memory address 8000 and it holds the address of the string variable
str i.e., 1000.
Accessing string via pointer
To access and print the elements of the string we can use a loop and check for the \0 null character.

In the following example we are using while loop to print the characters of the string variable str.
#include <stdio.h>

int main(void) {

// string variable
char str[6] = "Hello";

// pointer variable
char *ptr = str;

// print the string


while(*ptr != '\0') {
printf("%c", *ptr);

// move the ptr pointer to the next memory location


ptr++;
}

return 0;
}
27 Write a program to find the length of string using pointer.

#include<stdio.h>
#include<conio.h>

void main()
{

char str[100],*p;
int length=0;

clrscr();

scanf(

p=str;

\
{
length ++;
p++;
}
printf
getch();
}

OUTPUT:
Enter any string: Hello
Length of given string is:5
28 Write a program to add two numbers using pointer and print that addition.

#include<stdio.h>
#include<conio.h>

void main()
{

int n[10],I,sum=0;
int *ptr;

clrscr();

for(i=0; i<10; i++)


{

ptr=n;

for(i=0; i<10; i++)


{
sum = sum + *ptr;
ptr++;
}

getch();
}

OUTPUT:
Entre 10 elements: 1 2 3 4 5 6 7 8 9 10
Sum of array elements is: 55
29 Explain return statement and write C example.

The return statement terminates the execution of a function and returns a value to the calling function. The
program control is transferred to the calling function after return statement.

In the above example, the value of variable result is returned to the variable sum in the main() function.
The return value could be any valid expression that returns a value:
Syntax of return statement

return (expression);

For example,

return a;
return (a+b);

The type of value returned from the function and the return type specified in function prototype and
function definition must match.
30 Differentiate Array and structure.
Syntax: Syntax:
Datatype arrayname[array size]; Struct structurename
Eg.int a[10]; {
Datatype member1;
Datatype member2;
.
.
Datatype member n;
}structure_variable;
31 Write a program to find maximum and minimum number from two number using
functions.
/*
* C program to find maximum and minimum between two numbers using functions
*/

#include <stdio.h>

/* Function declarations */
int max(int num1, int num2);
int min(int num1, int num2);

int main()
{
int num1, num2, maximum, minimum;

/* Input two numbers from user */


printf("Enter any two numbers: ");
scanf("%d%d", &num1, &num2);

maximum = max(num1, num2); // Call maximum function


minimum = min(num1, num2); // Call minimum function

printf("\nMaximum = %d\n", maximum);


printf("Minimum = %d", minimum);
return 0;
}

/**
* Find maximum between two numbers.
*/
int max(int num1, int num2)
{
return (num1 > num2 ) ? num1 : num2;
}

/**
* Find minimum between two numbers.
*/
int min(int num1, int num2)
{
return (num1 > num2 ) ? num2 : num1;
}

Output
Enter any two numbers: 10 20

Maximum = 20
Minimum = 10
32 Write syntax in C for structure named student with data field std_id, std_name,
std_percentage and declare a structure variables for three students.

#include <stdio.h>
#include<conio.h>
struct student
{
char std_name[50];
int std_id;
float std_percentage ;
} s[3];

int main()
{
int i;
clrscr();
printf("Enter information of students:\n");

// storing information
for(i=0; i<3; ++i)
{
printf("\nEnter roll number
%d,\n",s[i]. std_id );

printf("Enter name: ");


scanf("%s",s[i]. std_name );

printf("Enter marks: ");


scanf("%f",&s[i]. std_percentage );

printf("\n");
}

printf("Displaying Information:\n\n");
// displaying information
for(i=0; i<10; ++i)
{
printf("\nRoll number: %d\n",s[i]. std_id );
printf("Name: %d", s[i]. std_name);
printf("Marks: %.f",s[i]. std_percentage );
printf("\n");
}
getch();
}

Output

Enter information of students:

Enter roll number1


Enter name: Tom
Enter marks: 98

Enter roll number 2


Enter name: Jerry
Enter marks: 89

Enter roll number 3


Enter name: Mickey
Enter marks: 88

Displaying Information:

Roll number: 1
Name: Tom
Marks: 98

Roll number: 2
Name: Jerry
Marks: 89
Roll number: 3
Name: Mickey
Marks: 88
33 Write a function factorial which takes one number as input and returns its factorial
value.

#include <stdio.h>

int main()
{
int c, n, fact = 1;

printf("Enter a number to calculate its factorial\n");


scanf("%d", &n);

for (c = 1; c <= n; c++)


fact = fact * c;

printf("Factorial of %d = %d\n", n, fact);

return 0;
}

34 Explain enumerated data type with example.

An enumeration consists of integral constants. To define an enumeration, keyword enum is


used.

enum flag { const1, const2, ..., constN };


Here, name of the enumeration is flag.

And, const1, const2,...., constN are values of type flag.

By default, const1 is 0, const2 is 1 and so on. You can change default values of enum
elements during declaration (if necessary).
// Changing default values of enum
enum suit {
club = 0,
diamonds = 10,
hearts = 20,
spades = 3,
};

Example: Enumeration Type


#include <stdio.h>

enum week { sunday, monday, tuesday, wednesday, thursday, friday, saturday };

int main()
{
enum week today;
today = wednesday;
printf("Day %d",today+1);
return 0;
}
35 What is the purpose of typedef? How typedef is useful in Structure?
In C language, user can define their own data types of identifier that represents an existing
data types. The user defined data type identifier can later be used to declare variables.

The general syntax is:


typedef <data type> <identifier name> ;

Here type represents existing data type and identifier refers to the new type name given to
the data type.

For Example:
typedef int student;
typedef float per;

Here student symbolizes int and per symbolizes float. They can be later used to declare
variables as follows:

student s1,s2,s3;
per p1,p2,p3;

Therefore s1 and s2 and s3 are indirectly declared as integer data type and p1,p2 and p3 are
indirectly as float data type.
Using Typedef With Structures. It allows us to introduce synonyms for data types which
could have been declared some other way. It is used to give New name to the Structure.

36 What is Union? Write a program to Demonstrate the Concept and use of Union
Data Structure.

Union is user defined data type just like structure.


Each member in structure is assigned its own unique storage area where as in Union;
all the members share common storage area.
All members share the common area so only one member can be active at a time.
Unions are used when all the members are not assigned value at the same time.
Syntax:
union Union_name
{
Datatype member 1;
Datatype member 2;

Datatype member n;
};
Example:
union book
{
char title[100];
char author[50];
int pages;
float price;
};

/*
* C program to illustrate the concept of unions
*/
#include <stdio.h>
union number
{
int n1;
float n2;
};

void main()
{

union number x;

printf("Enter the value of n1: ");


scanf("%d", &x.n1);
printf("Value of n1 = %d", x.n1);
printf("\nEnter the value of n2: ");
scanf("%f", &x.n2);
printf("Value of n2 = %f\n", x.n2);

}
37 Define a Structure Data type called Player containing four member called
playername, teamname, score and average. Develop a program that would assign the
value to all the members and display the Player detail.

38 Explain array of structure with example.


Array of structure mean collection of structures.
Array storing different type of structure of variables.
As we have an array of basic data types, same way we can have an array variable of
structure.
#include <stdio.h>
#include <string.h>

struct student
{
int id;
char name[30];
float percentage;
};

int main()
{
int i;
struct student record[2];

// 1st student's record


record[0].id=1;
strcpy(record[0].name, "Raju");
record[0].percentage = 86.5;
// 2nd student's record
record[1].id=2;
strcpy(record[1].name, "Surendren");
record[1].percentage = 90.5;

// 3rd student's record


record[2].id=3;
strcpy(record[2].name, "Thiyagu");
record[2].percentage = 81.5;

for(i=0; i<3; i++)


{
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
printf(" Name is: %s \n", record[i].name);
printf(" Percentage is: %f\n\n",record[i].percentage);
}
return 0;
}
Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000

Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000

Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000

Example 2:

#include<stdio.h>
#include<string.h>
#define MAX 2

struct student
{
char name[20];
int roll_no;
float marks;
};

int main()
{
struct student arr_student[MAX];
int i;

for(i = 0; i < MAX; i++ )


{
printf("\nEnter details of student %d\n\n", i+1);

printf("Enter name: ");


scanf("%s", arr_student[i].name);

printf("Enter roll no: ");


scanf("%d", &arr_student[i].roll_no);

printf("Enter marks: ");


scanf("%f", &arr_student[i].marks);
}

printf("\n");

printf("Name\tRoll no\tMarks\n");

for(i = 0; i < MAX; i++ )


{
printf("%s\t%d\t%.2f\n",
arr_student[i].name, arr_student[i].roll_no, arr_student[i].marks);
}

// signal to operating system program ran fine


return 0;
}

Enter details of student 1

Enter name: Jim


Enter roll no: 1
Enter marks: 44

Enter details of student 2

Enter name: Tim


Enter roll no: 2
Enter marks: 76

Name Roll no Marks


Jim 1 44.00
Tim 2 76.00
39 Explain file function fseek(),feof(),fopen(),fclose() putc() and getc() or
Explain file handing functions with example.
C provides a set of functions to do operations on file. These functions are known as
file handling functions.
Each function is used for some particular purpose.

1) fopen() (Open file)


fopen is used to open a file for operation.
Two arguments should be supplied to fopen function,
File name or full path of file to be opened
File opening mode which indicates which type of operations are permitted on file.
If file is opened successfully, it returns pointer to file else NULL.

Examp
only.

2) fclose() (Close file)


Opened files must be closed when operations are over.
The function fclose() is used to close the file i.e. indicate that we are finished
processing this file.
To close a file, we have to supply file pointer to fclose() function.
If file is closed successfully then it returns 0 else EOF.
Example: fclose(fp);

3) fprintf() (Write formatted output to file)


The fprintf() function prints information in the file according to the specified format.
fprintf() works just like printf(), only difference is we have to pass file pointer to the
function.
It returns the number of characters outputted, or a negative number if an error occurs.
4) fscanf() (Read formatted data from file)

The function fscanf() reads data from the given file.


It works in a manner exactly like scanf(), only difference is we have to pass file
pointer to the function.
If reading is succeeded then it returns the number of variables that are actually
assigned values, or EOF if any error occurred.

5) fseek() (Reposition file position indicator)


Sets the position indicator associated with the file pointer to a new position defined
by adding offset to a reference position specified by origin.
You can use fseek() to move beyond a file, but not before the beginning.
fseek() clears the EOF flag associated with that file.
We have to supply three arguments, file pointer, how many characters, from which
location.
It returns zero upon success, non-zero on failure.

The origin value should have one of the following values


Name Explanation
SEEK_SET Seek from the start of the file
SEEK_CUR Seek from the current location
SEEK_END Seek from the end of the file

Example: fseek(fp,9,SEEK_SET); // Moves file position indicator to 9


position from begging.

6) ftell() (Get current position in file)


It returns the current value of the position indicator of the file.
For binary streams, the value returned corresponds to the number of bytes from the
beginning of the file.
Example: position = ftell (fp);

7) rewind() (Set position indicator to the beginning)


Sets the position indicator associated with file to the beginning of the file.
A call to rewind is equivalent to: fseek (fp, 0, SEEK_SET);
On file open for update (read+write), a call to rewind allows to switch between
reading and writing.
Example: rewind (fp);
8) getc() (Get character from file)
getc function returns the next character from file or EOF if the end of file is reached.
After reading a character, it advances position in file by one character.
getc is equivalent to getchar().
fgetc is identical to getc.
Example: ch = getc(fp);
9) putc() (Write character to file)
putc writes a character to the file and advances the position indicator.
After reading a character, it advances position in file by one character.
If there are no errors, the same character is returned; if error occurs then EOF is
returned.
putc is equivalent to putchar().
fgetc is identical to putc.
Example: putc(ch, fp);

10) getw() (Get integer from file)


getw function returns the next int from the file. If error occurs then EOF is returned.
Example: i = getw(fp);

11) putw() (Write integer to file)


putw function writes integer to file and advances indicator to next position.
It succeeded then returns same integer otherwise EOF is returned.
Example: putw(I, fp);

12) feof()
feof() function returns non-zero value only if end of file has reached otherwise it
returns 0.
Example : feof(fp)
40 What is Command line argument? Describe the arguments argc, argv[]

Command-line arguments are given after the name of a program in command line
operating systems like DOS or Linux.

Up to this point there is no argument in main() function.


main() can accept two arguments :

1) First argument is number of command-line arguments.


2) Second argument is a full list of command-line argument.

Syntax:
int main(int argc, char *argv[])
Here argc refers to the number of arguments passed and argv[] is a pointer array
which point to each argument which passed to main.
Following is a simple example which checks if there is any argument supplied from
the
command-line and take action accordingly:
Example:
#include <stdio.h>
int main( int argc, char *argv[] )
{
if( argc == 2 )
{
printf("The argument supplied is %s\n", argv[1]);
}
else if( argc > 2 )
{
printf("Too many arguments supplied.\n");
}
else
{
printf("One argument expected.\n");
}
}

Here argv[0] holds the name of the program itself and argv[1] is a pointer to the first
command line argument supplied, and *argv[n] is the last argument.
If no arguments are supplied, argc will be one and if you pass one argument then argc
is set at 2.
You pass all the command-line arguments separated by a space, but if argument itself
has a space then you can pass such arguments by putting them inside double quotes

Example:

$ ./a.out testing1 testing2


Too many arguments supplied.
Write a C program which performs addition, subtraction of two variables using user
define function.

#include<stdio.h>
#include<conio.h>

int sum(int num1, int num2);


int sub(int num1, int num2);

void main()
{

int num1, num2, res_1, res_2;

printf("\nEnter the two numbers : ");


scanf("%d %d", &num1, &num2);

//Call Function Sum With Two Parameters


res_1 = sum(num1, num2);
printf("\n Addition of two number is : %d ".res_1);

res_2 = sub(num1, num2);


printf("\n Subtraction of two number is : %d ".res_2);
}

int sum(int num1, int num2)


{
int num3;
num3 = num1 + num2;
return (num3);
}

int sub(int num1, int num2)


{
int num3;
num3 = num1 - num2;
return (num3);
}
Output :
Enter the two numbers : 15 12
Addition of two number is : 27
Subtraction of two number is: 3
Write a program to copy contents of one file into another.

/**
* C program to copy contents of one file to another.
*/

#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *sourceFile;
FILE *destFile;
char sourcePath[100];
char destPath[100];

char ch;

/* Input path of files to copy */


printf("Enter source file path: ");
scanf("%s", sourcePath);
printf("Enter destination file path: ");
scanf("%s", destPath);

/*
* Open source file in 'r' and
* destination file in 'w' mode
*/
sourceFile = fopen(sourcePath, "r");
destFile = fopen(destPath, "w");

/* fopen() return NULL if unable to open file in given mode. */


if (sourceFile == NULL || destFile == NULL)
{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read/write privilege.\n");

exit(EXIT_FAILURE);
}

/*
* Copy file contents character by character.
*/
ch = fgetc(sourceFile);
while (ch != EOF)
{
/* Write to destination file */
fputc(ch, destFile);

/* Read next character from source file */


ch = fgetc(sourceFile);
}

printf("\nFiles copied successfully.\n");

/* Finally close files to release resources */


fclose(sourceFile);
fclose(destFile);

return 0;
}
Write a program to merge the content of one file with another file.

**
* C program to merge contents of two files to third file.
*/

#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE *sourceFile1;
FILE *sourceFile2;
FILE *destFile;
char sourcePath1[100];
char sourcePath2[100];
char destPath[100];

char ch;

/* Input path of files to merge to third file */


printf("Enter first source file path: ");
scanf("%s", sourcePath1);
printf("Enter second source file path: ");
scanf("%s", sourcePath2);
printf("Enter destination file path: ");
scanf("%s", destPath);

/*
* Open source files in 'r' and
* destination file in 'w' mode
*/
sourceFile1 = fopen(sourcePath1, "r");
sourceFile2 = fopen(sourcePath2, "r");
destFile = fopen(destPath, "w");

/* fopen() return NULL if unable to open file in given mode. */


if (sourceFile1 == NULL || sourceFile2 == NULL || destFile == NULL)
{
/* Unable to open file hence exit */
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read/write privilege.\n");

exit(EXIT_FAILURE);
}

/* Copy contents of first file to destination */


while ((ch = fgetc(sourceFile1)) != EOF)
fputc(ch, destFile);

/* Copy contents of second file to destination */


while ((ch = fgetc(sourceFile2)) != EOF)
fputc(ch, destFile);

printf("\nFiles merged successfully to '%s'.\n", destPath);

/* Close files to release resources */


fclose(sourceFile1);
fclose(sourceFile2);
fclose(destFile);

return 0;
}
Create a structure of time having integer members year, month and days.
Read and display the array of structure.

Write a program to copy one file to another file using command line arguments.

/* File Copy using command line arguments */

#include<stdio.h>
int main(int argc,char *argv[])
{
FILE *fs,*ft;
int ch;
if(argc!=3)
{
printf("Invalide numbers of arguments.");
return 1;
}
fs=fopen(argv[1],"r");
if(fs==NULL)
{
printf("Can't find the source file.");
return 1;
}
ft=fopen(argv[2],"w");
if(ft==NULL)
{
printf("Can't open target file.");
fclose(fs);
return 1;
}

while(1)
{
ch=fgetc(fs);
if (feof(fs)) break;
fputc(ch,ft);
}

fclose(fs);
fclose(ft);
return 0;
}
Write a program to read data like rollno, name, marks and write it to the file using
fprintf() function.

#include<stdio.h>

void main()
{
FILE *fp;
int roll;
char name[25];
float marks;
char ch;

fp = fopen("file.txt","w"); //Statement 1

if(fp == NULL)
{
printf("\nCan't open file or file doesn't exist.");
exit(0);
}

do
{
printf("\nEnter Roll : ");
scanf("%d",&roll);

printf("\nEnter Name : ");


scanf("%s",name);

printf("\nEnter Marks : ");


scanf("%f",&marks);

fprintf(fp,"%d%s%f",roll,name,marks);

printf("\nDo you want to add another data (y/n) : ");


ch = getche();

}while(ch=='y' || ch=='Y');

printf("\nData written successfully...");


fclose(fp);
}

Output :

Enter Roll : 1
Enter Name : Kumar
Enter Marks : 78.53
Do you want to add another data (y/n) : y
Enter Roll : 2
Enter Name : Sumit
Enter Marks : 89.62
Do you want to add another data (y/n) : n
Data written successfully...

You might also like