APIC Q ALL
APIC Q ALL
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 size determines the number of characters in the string_name. Some examples are:
Example: char city[10];
char name[30];
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;
prinf("Format specifers",value1,value2,..);
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.
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.
Example:
void main()
Output: 10 10 5000
A 10 5000
P 5000 5048
Advantages :
fseek() is used to move file pointer associated with a given file to a specific 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.
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-
After this type definition, the identifier BYTE can be used as an abbreviation for the type int, for example.
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.
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,
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:
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;
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.
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("Please enter the location where you want to insert an new element\n");
scanf("%d", &position);
array[position-1] = value;
n++;
getch();
}
5 Write a program of addition for two 3x3 matrix.
void main()
{
int m, n, c, d, first[10][10], second[10][10], sum[10][10];
}
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.
}
}
}
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");
#include <stdio.h>
#include<conio.h>
void main()
{
int array[100], minimum, size, c, location = 1;
minimum = array[0];
printf("Minimum element is present at location %d and it's value is %d.\n", location, minimum);
return 0;
}
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.
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.
Char *chptr;
Chptr =&ch;
Or
Char ch,*chptr=&ch;
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
#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();
}
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);
a = number[i];
number[i] = number[j];
number[j] = a;
}
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.
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.
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;
return 0;
}
Program to Reverse a String using Pointers
#include <stdio.h>
#include <string.h>
// swap character
ch = *end_ptr;
*end_ptr = *begin_ptr;
*begin_ptr = ch;
// Driver code
int main()
{
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 main()
{
int num, result;
#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:
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.
Fun1()
No
} Output }
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>
Fun1(a)
No
} Return value }
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.
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 main()
{
int num, result;
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
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.
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;
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();
ptr=n;
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;
/**
* 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("\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
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;
return 0;
}
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,
};
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.
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.
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;
}
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.
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record[2];
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;
printf("\n");
printf("Name\tRoll no\tMarks\n");
Examp
only.
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.
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:
#include<stdio.h>
#include<conio.h>
void main()
{
/**
* 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;
/*
* Open source file in 'r' and
* destination file in 'w' mode
*/
sourceFile = fopen(sourcePath, "r");
destFile = fopen(destPath, "w");
exit(EXIT_FAILURE);
}
/*
* Copy file contents character by character.
*/
ch = fgetc(sourceFile);
while (ch != EOF)
{
/* Write to destination file */
fputc(ch, 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;
/*
* Open source files in 'r' and
* destination file in 'w' mode
*/
sourceFile1 = fopen(sourcePath1, "r");
sourceFile2 = fopen(sourcePath2, "r");
destFile = fopen(destPath, "w");
exit(EXIT_FAILURE);
}
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.
#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);
fprintf(fp,"%d%s%f",roll,name,marks);
}while(ch=='y' || ch=='Y');
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...