0% found this document useful (0 votes)
7 views79 pages

EST 102 (Model Question Paper) Programming in C (Common To All Programs) - Abhinand TJ

The document outlines the first semester B.Tech examination for the course 'Programming in C' at APJ Abdul Kalam Technological University, detailing various questions and answers related to computer architecture, programming concepts, and C language syntax. It includes topics such as the role of processors and memory, differences between compiled and interpreted languages, and practical programming exercises. Additionally, it discusses the advantages of functions, variable scope and lifetime, and file handling in C.

Uploaded by

salim
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)
7 views79 pages

EST 102 (Model Question Paper) Programming in C (Common To All Programs) - Abhinand TJ

The document outlines the first semester B.Tech examination for the course 'Programming in C' at APJ Abdul Kalam Technological University, detailing various questions and answers related to computer architecture, programming concepts, and C language syntax. It includes topics such as the role of processors and memory, differences between compiled and interpreted languages, and practical programming exercises. Additionally, it discusses the advantages of functions, variable scope and lifetime, and file handling in C.

Uploaded by

salim
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/ 79

APJ ABDUL KALAM TECHNOLOGICAL UNIVERSITY FIRST SEMESTER B.

TECH DEGREE

EXAMINATION,

MONTH & YEAR

Course Code: EST 102

Max.Marks:100

Course Name: Programming in C (Common to all programs)

Max Marks:100 Duration: 3 Hours

(Part A)

Answer all questions, each carries 3 marks.

1. Write short note on processor and memory in a computer. (3 Marks)

Answer:- Processor, also known as a “Microprocessor“. It is a small electronic chip that is placed inside

the computers and other electronics components. Processors can manage all instructions such as

arithmetical, logical, input/output (I/O) and other basic instructions, which are created by hardware or

operating system. Its main role is to obtain input data from input devices, perform computations and then

display accurate results on the output devices. Nowadays, more advanced processors are available in

the market, which are capable of controlling trillions of instructions per second. Processors are used in

PCs as well as they can be used into other electronic devices such as smartphones, tablets, PDA etc.,

A processor is made of four basic elements:

● The arithmetic logic unit (ALU)

● The floating point unit (FPU),

● Registers, and

● The cache memories.


The ALU and FPU carry basic and advanced arithmetic and logic operations on numbers, and then

results are sent to the registers, which also store instructions. Caches are small and fast memories that

store copies of data for frequent use, and act similarly to a random access memory (RAM).

The CPU carries out its operations through the three main steps of the instruction cycle: fetch, decode,

and execute.

● Fetch: the CPU retrieves instructions, usually from RAM.

● Decode: a decoder converts the instruction into signals to the other components of the computer.

● Execute: the now decoded instructions are sent to each component so that the desired operation

can be performed.

Memory:- Memory is just like a human brain. It is used to store data and instructions. Computer

memory is the storage space in the computer, where data is to be processed and instructions

required for processing are stored.

Memory is primarily of three types −

● Cache Memory

● Primary Memory/Main Memory

● Secondary Memory

Cache Memory (volatile memory)

Cache memory is a very high speed semiconductor memory which can speed up the CPU. It acts as a

buffer between the CPU and the main memory. It is used to hold those parts of data and programs

which are most frequently used by the CPU. The parts of data and programs are transferred from the

disk to cache memory by the operating system, from where the CPU can access them.
Primary Memory (Main Memory) (volatile memory)

Primary memory holds only those data and instructions on which the computer is currently working. It

has a limited capacity and data is lost when power is switched off. It is generally made up of

semiconductor devices. These memories are not as fast as registers. The data and instruction required

to be processed resides in the main memory. It is divided into two subcategories RAM and ROM.

Secondary Memory

This type of memory is also known as external memory or non-volatile. It is slower than the main

memory. These are used for storing data/information permanently. CPU directly does not access these

memories, instead they are accessed via input-output routines. The contents of secondary memories

are first transferred to the main memory, and then the CPU can access it. For example, disk, CD-ROM,

DVD, etc.

2. What are the differences between compiled and interpreted languages? Give example for each.

(3 Marks)

Answer:

Sl. COMPILED LANGUAGE INTERPRETED LANGUAGE

No

1 A compiled language is a programming An interpreted language is a programming

language whose implementations are language whose implementations execute

typically compilers and not interpreters. instructions directly and freely, without previously
compiling a program into machine-language

instructions.

2 In this language, once the program is In this language, the instructions are not directly

compiled it is expressed in the instructions executed by the target machine.

of the target machine.

3 There are at least two steps to get from There is only one step to get from source code to

source code to execution. execution.

4 In this language, compiled programs run While in this language, interpreted programs can be

faster than interpreted programs. modified while the program is running.

5 In this language, compilation errors prevent In these languages, all the debugging occurs at

the code from compiling. run-time.

6 The code of compiled language can be A program written in an interpreted language is not

executed directly by the computer’s CPU. compiled, it is interpreted.

7 This language delivers better performance. This language delivers relatively slower

performance.

8 Example of compiled language – C, C++, Example of Interpreted language – JavaScript, Perl,

C#, CLEO, COBOL, etc. Python, BASIC, etc.

3. Write a C program to read a Natural Number through keyboard and to display the reverse
of the given number. For example, if “3214567” is given as input, the output to be shown is

“7654123”. (3 Marks)

Answer: /*program to find the reverse of n digit number*/

#include<stdio.h>

//#include<conio.h>

main()

int a, b, s=0;

//clrscr();

printf("enter the number");

scanf("%d",&a);

while(a>0)

b=a%10;

s=(s*10)+b;

a=a/10;

printf("the reverse is %d",s);

return;

Output: enter the number123456789

the reverse is 987654321


4. Is it advisable to use goto statements in a C program? Justify your answer. (3 Marks)

Answer: A goto statement in C programming provides an unconditional jump from the 'goto' to a labeled

statement in the same function.

NOTE − Use of goto statements is highly discouraged in any programming language because it makes

it difficult to trace the control flow of a program, making the program hard to understand and hard to

modify. Any program that uses a goto can be rewritten to avoid them.

Syntax

The syntax for a goto statement in C is as follows −

goto label;

..

label: statement;

Here the label can be any plain text except C keyword and it can be set anywhere in the C program

above or below to goto statement.

Flow Diagram
Example:

/* accept the no and reverses it*/

#include<stdio.h>

int main()

int number, rev=0, digit, temp_num;

printf("enter a number\n");

scanf("%d", &number);

temp_num=number;

START: digit=number%10;

rev=rev*10+digit;

number=number/10;
if( number > 0)

goto START;

printf("Input number =%5d\n", temp_num);

printf("Reversed number=%5d\n", rev);

Output:

Enter the number

12345

Input number=12345

Reversed number=54321

5. Explain the different ways in which you can declare & initialize a single dimensional array.

(3 Marks)

Answer: Initializing one dimensional array Assigning some value to the variable that undergoes

processing.

•Syntax:- data_type array_name[size]={element1, element2,...elementn};

Where, data_type->basic data type

array_name-> name of an array

size-> maximum no of elements


Ex:- 1) int evennum[4]={2 , 4, 6, 12};

2 4 6 12

evennum[0] evennum[1] evennum[2] evennum[3]

2) float xyz[5]={1.2, 2.4, 3.6}

1.2 2.4 3.6 0 0

xyz[0] xyz[1] xyz[2] xyz[3] xyz[4]

1) int age[ ] = {16, 24, 30, 32, 40, 48};

2) float height[ ] = {150.0, 162.5, 170.0, 177.0};

In the first eg: the array age is initialized for its 6 elements. The size is 6. In the second eg: the

array height is initialized for its 4 elements. Here the size is 4.

6. Write a C program to read a sentence through keyboard and to display the count of white spaces

in the given sentence. (3 Marks)

Answer:

#include<stdio.h>

int main()

char a[60];

int i=0,count=0;
printf("Enter the string\n");

gets(a);

puts(a);

while(a[i]!='\0')

if(a[i]==' ')

count++;

i++;

printf("Number of blank spaces in a string is %d",count);

Output:

Enter the string

now a days people have got used to staying in home for long durations

now a days people have got used to staying in home for long durations

Number of blank spaces in a string is 13

7. What are the advantages of using functions in a program? (3 Marks)

Answer: These are the following advantages of C functions.


● Use of functions enhances the readability of a program. A big code is always difficult to read.

Breaking the code in smaller functions keeps the program organized, easy to understand and

makes it reusable.

● The C compiler follows top-to-down execution, so the control flow can be easily managed in case

of functions. The control will always come back to the main() function.

● It reduces the complexity of a program and gives it a modular structure.

● In case we need to test only a particular part of the program we will have to run the whole program

and figure out the errors which can be quite a complex process. Another advantage here is that

functions can be individually tested which is more convenient than the above mentioned process.

● A function can be used to create our own header file which can be used in any number of

programs i.e. the reusability.

8. With a simple example program, explain scope and lifetime of variables in C. (3 Marks)

Answer: Storage classes specify the scope, lifetime and binding of variables.

To fully define a variable, one needs to mention not only its ‘type’ but also its storage class.

A variable name identifies some physical location within computer memory, where a collection of bits are

allocated for storing values of variables.

Storage class tells us the following factors −

● Location of the variable storage (in memory or cpu register)

● The initial value of variable, if no value is initialized

● Scope of variable where it can be accessed


● Life of a variable

Lifetime

The lifetime of a variable defines the duration for which the computer allocates memory for it (the

duration between allocation and deallocation (freeing) of memory).

In C language, a variable can have automatic, static or dynamic lifetime.

● Automatic − The auto storage class is the default for variables declared inside a block. A

variable x that has automatic storage is deleted when the block in which x was declared exits.

● Static − A variable is created when the declaration is executed for the first time. It is destroyed

when the execution stops/terminates.

● Dynamic − The variables memory is allocated and deallocated through memory management

functions.

Storage Classes

There are four storage classes in C language −

Storage Storage Default initial value Lifetime Scope Keyword

Class Area

Automatic Memory Till control remains in block Till control remains in block Local Auto

Register CPU Garbage value Till control remains in block Local Register

register
Static Memory Zero Value in between function Local Static

calls

External Memory Garbage value Throughout program Global Extern

execution

Example for automatic storage class

Following is the C program for automatic storage class −

#include<stdio.h>

int main()

auto int i=1;

auto int i=2;

auto int i=3;

printf ("%d\n",i);

printf("%d\n", i);

printf("%d\n", i);
}

Output: 321

Example for external storage class

Following is the C program for external storage class −

#include<stdio.h>

extern int i =1; /* this ‘i’ is available throughout program */

int main()

int i = 3; /* this ‘i' available only in main */

printf ("%d\n",i);

fun ();

fun ()

printf ("%d", i);

Output:
3

9. Write a function in C which takes the address of a single dimensional array (containing finite

sequence of numbers) and the number of numbers stored in the array as arguments and stores

the numbers in the same array in reverse order. Use pointers to access the elements of the array.

(3 Marks)

Answer:

/* C program to reverse an array using pointers */

#include <stdio.h>

void printArr(int *arr, int size); /* Function declaration */

int main()

int arr[100];

int size;

int *left = arr; // Pointer to arr[0]

int *right;

// Input size of array

printf("Enter size of array: ");

scanf("%d", &size);
right = &arr[size - 1]; // Pointer to arr[size - 1]

printf("Enter elements in array: "); /** Input elements in array */

while(left <= right)

scanf("%d", left++);

printf("\nArray before reverse: ");

printArr(arr, size);

left = arr; // Make sure that left points to arr[0]

while(left < right) // Loop to reverse array

/* * Swaping element from left of array to right of array. */

*left ^= *right;

*right ^= *left;

*left ^= *right;

// Increment left array pointer and decrement right array pointer

left++;

right--;

printf("\nArray after reverse: ");


printArr(arr, size);

return 0;

/* Function to print array using pointer. */

void printArr(int * arr, int size)

int * arrEnd = (arr + size - 1); // Pointer to arr[size - 1]

while(arr <= arrEnd) /* Loop till last array element */

printf("%d ", *arr);

arr++; // Move pointer to next array element.

Output:

Enter size of array: 4

Enter elements in array: 22 15 10 45

Array before reverse: 22, 15, 10, 45,


Array after reverse: 45, 10, 15, 22,

10. With an example, explain the different modes of opening a file. (3 Marks)

Answer:- Opening a file

The fopen() function is used to create a file or open an existing file:

fp = fopen(const char filename,const char mode);

There are many modes for opening a file:

r - open a file in read mode

w - opens or create a text file in write mode

a - opens a file in append mode

r+ - opens a file in both read and write mode

a+ - opens a file in both read and write mode

w+ - opens a file in both read and write mode

Here’s an example of reading data from a file and writing to it:

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

main()

FILE *fp;

char ch;

fp = fopen("hello.txt", "w");

printf("Enter data");

while( (ch = getchar()) != EOF) {

putc(ch,fp);

fclose(fp);

fp = fopen("hello.txt", "r");

while( (ch = getc(fp)! = EOF)

printf("%c",ch);

fclose(fp);

Part B

Answer any one Question from each module. Each question carries 14 Marks
11. (a) Draw a flow chart to find the position of an element in a given sequence, using linear

searching technique. With an example explain how the flowchart finds the position of a

given element. (10 Marks)

Answer:

/* C program to input N numbers and store them in an array.

* Do a linear search for a given key and report success or failure. */

#include <stdio.h>

void main()

int num;

int i, keynum, found = 0;

printf("Enter the number of elements ");

scanf("%d", &num);

int array[num];

printf("Enter the elements one by one \n");

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

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

printf("Enter the element to be searched ");

scanf("%d", &keynum);

/* Linear search begins */

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

if (keynum == array[i] )

found = 1;

break;

if (found == 1)

printf("Element is present in the array at position %d",i+1);

else

printf("Element is not present in the array\n");

Output:

Enter the number of elements 7

Enter the elements one by one


21 56 41 20 85 64 73

Enter the element to be searched 20

Element is present in the array at position 4

Flow Chart
(b) Write a pseudo code representing the flowchart for linear searching. (4 Marks)
Answer:

Step 1: Initialize an integer array of size 20 declare num, keyele, i, found

Step 2: Read the size (num) of the mentioned array

Step 3: Initialize for loop with index variable i=0 and final value of size of array with step increment

Step 4: Read the entered elements one by one

Step 5: Read the key element

Step 6: In function to search for the key element using if condition (keyele==arr[i])

Step 7: if array element is present , found=1

Step 8: if found =1, print the array element is found with the index number or position number.

Step 9: if key element is not found print the element is not found

Step 10: End

12. (a) With the help of a flow chart, explain the bubble sort operation. Illustrate with an example. (10

Marks)

Answer: /*program to bubble sort the given array of numbers*/

#include<stdio.h>

#include<conio.h>

main()

int a[15], i, j, t, n;

//clrscr();

printf("enter the limit \n");

scanf("%d",&n);
printf("enter the numbers \n");

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

scanf("%d",&a[i]);

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

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

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

t=a[i];

a[i]=a[j];

a[j]=t;

printf("the sorted numbers are \n");

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

printf("\t%d",a[i]);

getch();

Output:

enter the limit

enter the numbers

12 3 0 25 7

the sorted numbers are

0 3 7 12 25
Flow Chart:

12. (b) Write an algorithm representing the flowchart for bubble sort. (4 Marks)

Answer:

Step 1: Declare array, limit, index variable and temporary variable

Step 2: Read the limit


Step 3: Read the numbers into the array

Step 4: initialise nested for loops

Step 5: check if the first variable greater than second variable

Step 6: interchange using dummy variable t

Step 7: Print the sorted numbers

Step 8: Stop

13. (a) Write a C program to read an English Alphabet through keyboard and display whether

the given Alphabet is in upper case or lower case. (6 Marks)

Answer:

#include<stdio.h>

int main()

char ch;

printf("\nEnter The Character : ");

scanf("%c", &ch);

if (ch >= 65 && ch <= 90)

printf("Character is Upper Case Letters");

else

printf("Character is Not Upper Case Letters");

return (0);

Output: Enter The Character : a


Character is Not Upper Case Letters

13. (b) Explain how one can use the builtin function in C, scanf to read values of different data

types. Also explain using examples how one can use the builtin function in C, printf for text formatting.

(8 Marks)

Answer: A function in which a prototype already predefined in the library is called a built in function.

There is no need to write a program for calling library functions or built in functions.

The name of the library function cannot be changed as its prototype is already predefined in the compiler.

Library functions are used in each and every program irrespective of complexity.

The library functions like scanf and printf are already present in the header file #include<stdio.h>

. To use these functions we need to include the header file in our program. For example,

If you want to use the printf() function, which is a formatted output statement, the header file <stdio.h>

should be included.

The printf statements used in different data types used are as given below.

Example:

#include <stdio.h>

int main()

// Displays the string inside quotations

printf("C Programming");
return 0;

Output

C Programming

Example 2: Integer Output

#include <stdio.h>

int main()

int testInteger = 5;

printf("Number = %d", testInteger);

return 0;

Output

Number = 5

We use %d format specifier to print int types. Here, the %d inside the quotations will be replaced by the

value of testInteger.

float and double Output


#include <stdio.h>

int main()

float number1 = 13.5;

double number2 = 12.4;

printf("number1 = %f\n", number1);

printf("number2 = %lf", number2);

return 0;

Output

number1 = 13.500000

number2 = 12.400000

To print float, we use %f format specifier. Similarly, we use %lf to print double values.

Example 4: Print Characters

#include <stdio.h>

int main()

char chr = 'a';


printf("character = %c", chr);

return 0;

Output

character = a

To print char, we use %c format specifier.

If we try to use printf() without including the stdio.h header file, we will get an error.

scanf()

In C programming, scanf() is one of the commonly used function to take input from the user. The scanf()

function reads formatted input from the standard input such as keyboards.

For the formatted input statement scanf() statement also we need to use the #include<stdio.h> header

file.

Example: Integer Input/Output

#include <stdio.h>

int main()

int testInteger;

printf("Enter an integer: ");


scanf("%d", &testInteger);

printf("Number = %d",testInteger);

return 0;

Output

Enter an integer: 4

Number = 4

In this case also if we use scanf statement without the #include<stdio.h> header file, we get an error.

Here, we have used %d format specifier inside the scanf() function to take int input from the user. When

the user enters an integer, it is stored in the testInteger variable.

We have used &testInteger inside scanf(). It is because &testInteger gets the address of testInteger, and

the value entered by the user is stored in that address

Float and Double Input/Output

#include <stdio.h>

int main()

float num1;

double num2;

printf("Enter a number: ");


scanf("%f", &num1);

printf("Enter another number: ");

scanf("%lf", &num2);

printf("num1 = %f\n", num1);

printf("num2 = %lf", num2);

return 0;

Output

Enter a number: 12.523

Enter another number: 10.2

num1 = 12.523000

num2 = 10.200000

We use %f and %lf format specifiers for float and double respectively.

C Character I/O

#include <stdio.h>

int main()

char chr;

printf("Enter a character: ");


scanf("%c",&chr);

printf("You entered %c.", chr);

return 0;

Output

Enter a character: g

You entered g

When a character is entered by the user in the above program, the character itself is not stored. Instead,

an integer value (ASCII value) is stored.

And when we display that value using %c text format, the entered character is displayed. If we use %d to

display the character, it's ASCII value is printed.

The printf() lies in its formatting string. That text can be packed with plain text, escape sequences, and

conversion characters, which insert values into the text output.

14. a) With suitable examples, explain various operators in C. (10 Marks)

Answer: C operators can be classified into following types:

● Arithmetic operators

● Relational operators

● Logical operators

● Bitwise operators
● Assignment operators

● Conditional operators

● Special operators

Arithmetic operators

C supports all the basic arithmetic operators. The following table shows all the basic arithmetic operators.

Operator Description

+ adds two operands

- subtract second operands from first

* multiply two operand

/ divide numerator by denominator

% remainder of division

++ Increment operator - increases integer value by one

-- Decrement operator - decreases integer value by one

Relational operators:

The following table shows all relation operators supported by C.

Operator Description
== Check if two operand are equal

!= Check if two operands are not equal.

> Check if operand on the left is greater than operand on the right

< Check operand on the left is smaller than right operand

>= check left operand is greater than or equal to right operand

<= Check if operand on left is smaller than or equal to right operand

Logical operators

C language supports the following 3 logical operators. Suppose a = 1 and b = 0,

Operator Description Example

&& Logical AND (a && b) is false

|| Logical OR (a || b) is true

! Logical NOT (!a) is false

Bitwise operators

Bitwise operators perform manipulations of data at bit level. These operators also perform shifting of bits

from right to left. Bitwise operators are not applied to float or double.
Operator Description

& Bitwise AND

| Bitwise OR

^ Bitwise exclusive OR

<< left shift

>> right shift

Assignment Operators

Assignment operators supported by C language are as follows.

Operator Description Example

= assigns values from right side operands to left side a=b

operand

+= adds right operand to the left operand and assign the a+=b is same as

result to left a=a+b

-= subtracts right operand from the left operand and a-=b is same as

assign the result to left operand a=a-b


*= mutiply left operand with the right operand and assign a*=b is same as

the result to left operand a=a*b

/= divides left operand with the right operand and assign a/=b is same as

the result to left operand a=a/b

%= calculate modulus using two operands and assign the a%=b is same

result to left operand as a=a%b

Conditional operator

The conditional operators in C language are known by two more names

1. Ternary Operator

2. ? : Operator

It is actually the if condition that we use in C language decision making, but using the conditional

operator, we turn the if condition statement into a short and simple operator.

The syntax of a conditional operator is :

expression 1 ? expression 2: expression 3

Explanation:

● The question mark "?" in the syntax represents the if part.


● The first expression (expression 1) generally returns either true or false, based on which it is

decided whether (expression 2) will be executed or (expression 3)

● If (expression 1) returns true then the expression on the left side of " : " i.e (expression 2) is

executed.

● If (expression 1) returns false then the expression on the right side of " : " i.e (expression 3) is

executed.

Special operator

Operator Description Example

sizeof Returns the size of an variable sizeof(x) return size of the variable x

& Returns the address of a &x ; return address of the variable x

variable

* Pointer to a variable *x ; will be pointer to a variable x

14. (b) Explain how characters are stored and processed in C. (4 Marks)

Answer: Computers work in binary . As a result, all characters, whether they are letters, punctuation or

digits, are stored as binary numbers. All of the characters that a computer can use are called as the

ASCII character set. The ASCII character set is a set of numbers from 0 .. 255, where each number in

the set represents a unique character. For example, the number 48 is used to represent the digit '0', 65

represents the character 'A', and 97 represents the character 'a'.


Formatting characters are also represented in the ASCII character set. The blank space character is

ASCII 32, the tab character is ASCII 9 , and the carriage return is represented by 13. When we look at a

text file, every symbol seen and every non-visible formatting technique is represented by an ASCII

character. In what follows the assumption is made that data is being read from the keyboard.

Every keystroke made is recorded in an area of memory called the keyboard buffer. This is where data

is held until needed by a program. When an input command such as getchar or scanf appears in a C

program, the program will first check the keyboard buffer to see if any data is present. If data is present,

the program will extract the data out of the keyboard buffer. In this way the input command is satisfied.

If there is no data in the buffer, the program will pause and wait for the user to type something.

15. (a) Write a function in C which takes a 2-Dimensional array storing a matrix of numbers and

the order of the matrix (number of rows and columns) as arguments and displays the sum

of the elements stored in each row. (6 Marks)

Answer:

/* C Program to find Sum of rows in a Matrix */

#include<stdio.h>

void addRows(int arr[10][10], int rows, int columns)

int i, j;
for(i = 0; i < rows; i++)

int Sum = 0;

for(j = 0; j < columns; j++)

Sum = Sum + arr[i][j];

printf("The Sum of Elements of Row %d in Matrix = %d \n",i+1, Sum );

int main()

int i, j, rows, columns, a[10][10];

printf("Please Enter Number of rows and columns : ");

scanf("%d %d", &rows, &columns);

printf("Please Enter the Row and Column Elements of Matrix \n");

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


{

for(j = 0; j < columns; j++)

scanf("%d", &a[i][j]);

addRows(a, rows, columns);

return 0;

Output:

Please Enter Number of rows and columns : 2 2

Please Enter the Row and Column Elements of Matrix

11 22

33 44

The Sum of Elements of Rows 1 in Matrix = 33

The Sum of Elements of Rows 2 in Matrix = 77


15. (b) Write a C program to check whether a given matrix is a diagonal matrix. (8 Marks)

Answer: A matrix having non-zero elements only in the diagonal running from the upper left to the lower

right is called a diagonal matrix.

#include<stdio.h>

int main()

int row_size,col_size;

//Get size of matrix

printf("Enter the row Size Of the Matrix:");

scanf("%d",&row_size);

printf("Enter the columns Size Of the Matrix:");

scanf("%d",&col_size);

int matrix[row_size][col_size];

//Taking input of the matrix

int i,j;
printf("Enter the Matrix Element:\n");

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

for(j=0;j<col_size;j++)

scanf("%d",&matrix[i][j]);

//check elements except diagonal are 0 or not

int point=0;

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

for(j=0;j<col_size;j++)

if(i!=j && matrix[i][j]!=0)

{
point=1;

break;

if(point==1)

printf("Given Matrix is not a diagonal Matrix.");

else

printf("Given Matrix is a diagonal Matrix.");

Output:

Enter the row Size Of the Matrix:3

Enter the columns Size Of the Matrix:3

Enter the Matrix Element:

100

020
003

Given Matrix is a diagonal Matrix.

16. (a) Without using any builtin string processing function like strlen, strcat etc., write a

program to concatenate two strings. (8 Marks)

Answer:

#include <stdio.h>

int main()

char first_string[20], second_string[20];

int i,j;

printf("Enter the first string");

scanf("%s",first_string);

printf("\nEnter the second string");

scanf("%s",second_string);

for(i=0;first_string[i]!='\0';i++);
for(int j=0;second_string[j]!='\0';j++)

first_string[i]=second_string[j];

i++;

first_string[i]='\0';

printf("After concatenation, the string would look like: %s", first_string);

return 0;

Output:

Enter the first string

Kerala

Enter the second string

_University

After concatenation, the string would look like: Kerala_University


16. (b) Write a C program to perform bubble sort. (6 Marks)

Answer:

/*program to bubble sort the given array of numbers*/

#include<stdio.h>

#include<conio.h>

int main()

int a[15], i, j, t, n;

printf("enter the limit \n");

scanf("%d",&n);

printf("enter the numbers \n");

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

scanf("%d",&a[i]);

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

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

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

{
t=a[i];

a[i]=a[j];

a[j]=t;

printf("the sorted numbers are \n");

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

printf("\t%d",a[i]);

getch();

Output:

enter the limit

enter the numbers

22 1 9 0 3

the sorted numbers are

0 1 3 9 22
17. a) (a) Write a function namely myFact in C to find the factorial of a given number. Also, write

another function in C namely nCr which accepts two positive integer parameters n and r and

returns the value of the mathematical function C(n,r) = ( n! / ( r! x (n - r)!) ). The function nCr is

expected to make use of the factorial function myFact. (10 Marks)

Answer:

#include <stdio.h>

int myFact(int);

int nCr(int);

void main()

int n,r,ncr,N;

printf("enter the value of integer for finding factorial\n");

scanf("%d",&N);

int fact=myFact(N);

printf("the factorial of the number %d\t is %d\t\n",N,fact);

printf("Enter a number n \n");


scanf("%d",&n);

printf("Enter a number r \n");

scanf("%d",&r);

ncr=nCr(n)/(nCr(r)*nCr(n-r));

printf("Value of %dC%d = %d\n",n,r,ncr);

int nCr(int n)

int i,f=1;

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

f=f*i;

return f;

int myFact(int N)

{
int j,fact=1;

for(j=1;j<=N;j++)

fact=fact*j;

return fact;

Output:

enter the value of integer for finding factorial

the factorial of the number 4 is 24

Enter a number n

10

Enter a number r

Value of 10C5 = 252


17. (b) What is recursion? Give an example. (4 Marks)

Answer: Recursion:- function calling itself

Recursion is the technique that defines a function in terms of itself.

A function, which performs a particular task is repeatedly called itself.

There should be an exclusive stopping statement (terminating condition).

Otherwise the function will not be terminated (it becomes circular)

Eg:- finding the factorial of a given number (say 4)

4*fact(3) , 3*fact(2), 2*fact(1), 1*fact(0),

Fact(0)=1*1, 2*1=2, 3*2=6, 4=4*6=24

/*program accepts a number from the keyboard and computes its factorial by recursive function*/

#include<stdio.h>

int main()

int num, fact;

printf("Enter the number \n");

scanf("%d", &num);

fact=rec_funct(num);

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

}
/*recursive function for factorial*/

int rec_funct(N)

int N;

int fct;

if(N==0) /*stopping condition*/

return(1);

else

fct=N*rec_funct(N-1); /*recursive call*/

return (fct);

Output:-

Enter the number

Factorial of 5=120

18. (a) With a suitable example, explain the differences between a structure and a union in C (6 Marks)

Answer:-

Parameter Structure Union

keyword struct keyword is used to define the union keyword is used to define the

structure union
size When variables or members are When a variable is associated with a

associated with a structure, the compiler union, the compiler allocates the memory

allocates the memory for each member. considering the size of the largest

The size of a structure is equal to or memory. So, the size of the union is the

greater than the sum of sizes of its size of the largest member.

members.

memory Each member within a structure is Memory allocated is shared by individual

assigned unique storage area of location members of union

Value altering Altering the value of a member will not Altering the value of any of the member

affect other members of the structure will alter other member values

Accessing Individual members can be accessed at Only one member can be accessed at a

members a time time

Initialization of Several members of a structure can be Only the first member of a union can be

members initialized at once initialized


example struct student
union number
{
{
int reg_no;

char name[20]; int n1;

char branch[20]; float n2;

int semester; };

float total_marks;

};

18. b) Declare a structure namely Student to store the details (roll number, name, mark_for_C)

of a student. Then, write a program in C to find the average mark obtained by the students

in a class for the subject Programming in C (using the field mark_for_C). Use array of

structures to store the required data (8 Marks)

Answer:

/* program accepts the roll no, name and marks obtained in one test of students of a class and displays

the roll number, name, marks of C and average*/

#include<stdio.h>

void main()

{
struct stud_rec

int Rollno;

char Name[20];

int mark_for_C;

float avg;

};

int i,n,total=0;

struct stud_rec s[100]; /*array of structures*/

printf("enter the number of students\n");

scanf("%d",&n);

printf("type in information of %d students\n",n);

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

printf("enter the Rollno: Name: and marks_for_C of student %d\n=", i+1);

scanf("%d%s%d",&s[i].Rollno,s[i].Name,&s[i].mark_for_C);

printf("Rollno Name Marks for C entered are \n");

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

printf("%d %s %d \n", s[i].Rollno, s[i].Name, s[i].mark_for_C);

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

total+=s[i].mark_for_C;
s[i].avg=total/n;

printf("the average marks of C for the class of %d students is %f",n, s[i].avg);

Output:

enter the number of students

type in information of 5 students

enter the Rollno: Name: and marks_for_C of student 1=

5 Babu 25

enter the Rollno: Name: and marks_for_C of student 2=

3 Ramu 21

enter the Rollno: Name: and marks_for_C of student 3=

4 Binu 20

enter the Rollno: Name: and marks_for_C of student 4=

1 Adil 19

enter the Rollno: Name: and marks_for_C of student 5=


2 Somu 17

Rollno Name Marks for C entered are

5 Babu 25

3 Ramu 21

4 Binu 20

1 Adil 19

2 Somu 17

the average marks of C for the class of 5 students is 20.000000

19. (a) With a suitable example, explain the concept of pass by reference. (6 Marks)

Answer:- Pass by reference:

•Actual values are not passed, instead their addresses are passed.

•There is no copying of values since their memory locations are referenced.

•If any modification is made to the values in the called function, then original values get changed within

the calling function.

•Mechanism by which pointers can be passed as arguments to the functions.

•Thus the data items of the calling program can be accessed by the called program(function)
•No value is copied when pointers are passed as arguments, as in call by value method.

•Unlike call by value method, If the values are changed in the functions, this will modify the original

contents of the actual parameters.

•When the pointers are passed as arguments, then the following two points must be considered.

1) in the calling program, the function is invoked with the function name and addresses of actual

parameters enclosed within the parentheses.

• i.e, function_name(&var1, &var2, ….& varn);

2) In the called program, parameter list, each and every formal parameters (pointers) must be preceded

by an indirection operator(*).

/* illustrates the call by reference method to interchange the contents of two integer variables*/

#include<stdio.h>

int main()

int num1, num2;

int inter_change(int *n1, int *n2); /*function prototype*/

printf("enter two numbers \n");

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


printf(" num1=%d and num2=%d (before calling function) \n", num1, num2);

inter_change(&num1, &num2); /*function reference*/

printf("num1=%d and num2=%d (after function is called ) \n", num1, num2);

/*function to interchange the values of two variables using pointers*/

int inter_change(int *n1, int *n2)

int temp;

temp= *n1;

*n1 = *n2;

*n2= temp;

Output:

Enter two numbers

56

88

num1=56 and num2=88 (before calling function)


num1=88 and num2=56 (after function is called)

19. (b) With a suitable example, explain how pointers can help in changing the content of a

single dimensionally array passed as an argument to a function in C. (8 Marks)

Answer:

/*program passes the third element of an array and interchanges with the 4th element and finally prints

the resultant array*/

#include<stdio.h>

int main()

int x[10];

int i, n;

int swap34(int *ptr1, int *ptr2 ); /*function declaration*/

printf("how many elements\n");

scanf("%d", &n);

printf("enter elements one by one\n");

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


scanf("%d", x+i);

swap34(x+2, x+3); /*Interchanging 3rd element by 4th */

printf("Resultant array is \n");

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

printf(" element [%d] = %d \t", i+1, x[i]);

/*function to interchange elements*/

int swap34(int *ptr1, int *ptr2 )

int temp;

temp = *ptr1;

*ptr1=*ptr2;

*ptr2=temp;

Output:

how many elements


4

enter elements one by one

22 555 66 77

Resultant array is

element [1] = 22 element [2] = 555 element [3] = 77 element [4] = 66

20. (a) Differentiate between sequential files and random access files? (4 Marks)

Answer:

Sequential files Random access files

Sequential Access to a data file means that Random Access to a file means that the computer

the computer system reads or writes system can read or write information anywhere in the

information to the file sequentially, starting data file. This type of operation is also called “Direct

from the beginning of the file and proceeding Access” because the computer system knows where

step by step. the data is stored (using Indexing) and hence goes

“directly” and reads the data.


Sequential access has advantages when Random access file has the advantage that you can

you access information in the same order all search through it and find the data you need more

the time. Also is faster than random access. easily (using indexing for example). Random Access

Memory (RAM) in computers works like that.

Tape Storage devices (used for offline Modern computer hard disks are using Random Access

backups) use Sequential Access.

Sequential drive stores files and data in a A random access drive puts them all over the place

specific order

20. (b) Using the prototypes explain the functionality provided by the following functions. (10 Marks)

i. fseek()

ii. ftell()

iii. fread()

iv. fwrite()

v. rewind()

Answer:

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

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

pointer: pointer to a FILE object that identifies the stream.

offset: number of bytes to offset from position

position: position from where offset is added.

Returns zero if successful, or else it returns a non-zero value

position defines the point with respect to which the file pointer needs to be moved. It has three values:

SEEK_END : It denotes the end of the file.

SEEK_SET : It denotes the starting of the file.

SEEK_CUR : It denotes file pointer’s current position.


// C Program to demonstrate the use of fseek()

#include <stdio.h>

int main()

FILE *fp;

fp = fopen("test.txt", "r");

// Moving pointer to end

fseek(fp, 0, SEEK_END);

// Printing position of pointer

printf("%ld", ftell(fp));

return 0;

Output:

ii. ftell(): ftell() in C is used to find out the position of file pointer in the file with respect to starting of the

file. Syntax of ftell() is:

long ftell(FILE *pointer)


Consider below C program. The file taken in the example contains the following data :

“Someone over there is calling you. We are going for work. Take care of yourself.” (without the quotes)

When the fscanf statement is executed word “Someone” is stored in string and the pointer is moved

beyond “Someone”. Therefore ftell(fp) returns 7.

// C program to demonstrate use of ftell()

#include<stdio.h>

int main()

/* Opening file in read mode */

FILE *fp = fopen("test.txt","r");

/* Reading first string */

char string[20];

fscanf(fp,"%s",string);

/* Printing position of file pointer */

printf("%ld", ftell(fp));

return 0;

}
Output:

iii. fread():The fread() function is the complementary of fwrite() function. fread() function is commonly

used to read binary data. It accepts the same arguments as fwrite() function does. The syntax of fread()

function is as follows:

Syntax: size_t fread(void *ptr, size_t size, size_t n, FILE *fp);

The ptr is the starting address of the memory block where data will be stored after reading from the file.

The function reads n items from the file where each item occupies the number of bytes specified in the

second argument. On success, it reads n items from the file and returns n. On error or end of the file, it

returns a number less than n.

Let's take some examples:

Example 1: Reading a float value from the file

int val;

fread(&val, sizeof(int), 1, fp);

This reads a float value from the file and stores it in the variable val.

Example 2: Reading an array from the file


int arr[10];

fread(arr, sizeof(arr), 1, fp);

This reads an array of 10 integers from the file and stores it in the variable arr.

Example 3: Reading the first 5 elements of an array

int arr[10];

fread(arr, sizeof(int), 5, fp);

This reads 5 integers from the file and stores it in the variable arr.

int arr[10];

fread(arr, sizeof(int), 5, fp);

This reads 5 integers from the file and stores it in the variable arr.

Example : The following program demonstrates how we can use fread() function.

#include<stdio.h>

#include<stdlib.h>

struct employee

{
char name[50];

char designation[50];

int age;

float salary;

} employee;

int main()

FILE *fp;

fp = fopen("employee.txt", "rb");

if(fp == NULL)

printf("Error opening file\n");

exit(1);

printf("Testing fread() function: \n\n");

while( fread(&emp, sizeof(emp), 1, fp) == 1 )

{
printf("Name: %s \n", emp.name);

printf("Designation: %s \n", emp.designation);

printf("Age: %d \n", emp.age);

printf("Salary: %.2f \n\n", emp.salary);

fclose(fp);

return 0;

Output:

iv) fwrite(): The fwrite() function writes the data specified by the void pointer ptr to the file.

Syntax: size_t fwrite(const void *ptr, size_t size, size_t n, FILE *fp);

ptr: it points to the block of memory which contains the data items to be written.

size: It specifies the number of bytes of each item to be written.

n: It is the number of items to be written.


fp: It is a pointer to the file where data items will be written.

On success, it returns the count of the number of items successfully written to the file. On error, it returns

a number less than n. Notice that two arguments (size and n) and return value of fwrite() are of type

size_t which on the most system is unsigned int.

To better understand fwrite() function consider the following examples:

Example 1: Writing a variable

float *f = 100.13;

fwrite(&p, sizeof(f), 1, fp);

This writes the value of variable f to the file.

Example 2: Writing an array

int arr[3] = {101, 203, 303};

fwrite(arr, sizeof(arr), 1, fp);

This writes the entire array into the file.

The following program demonstrates how to use fwrite() function.


#include<stdio.h>

#include<stdlib.h>

struct employee

char name[50];

char designation[50];

int age;

float salary;

} employee;

int main()

int n, i, chars;

FILE *fp;

fp = fopen("employee.txt", "wb");
if(fp == NULL)

printf("Error opening file\n");

exit(1);

printf("Testing fwrite() function: \n\n");

printf("Enter the number of records you want to enter: ");

scanf("%d", &n);

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

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

fflush(stdin);
printf("Name: ");

gets(employee.name);

printf("Designation: ");

gets(employee.designation);

printf("Age: ");

scanf("%d", &employee.age);

printf("Salary: ");

scanf("%f", &employee.salary);

chars = fwrite(&employee, sizeof(employee), 1, fp);

printf("Number of items written to the file: %d\n", chars);

}
fclose(fp);

return 0;

v) rewind(): The C library function void rewind(FILE *stream) sets the file position to the beginning of

the file of the given stream.

Syntax: void rewind(FILE *fp);

The rewind() function takes the file pointer as argument.

Example of rewind() function

#include<stdio.h>

#include<conio.h>

void main(){

FILE *fp;

char c;

//clrscr();

fp=fopen("file.txt","r");

while((c=fgetc(fp))!=EOF){

printf("%c",c);
}

rewind(fp);//moves the file pointer at beginning of the file

while((c=fgetc(fp))!=EOF){

printf("%c",c);

fclose(fp);

getch();

Output:

You might also like