Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Modelpaper2 Solutions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Introduction to C programming Model paper 2 2022-23

Model Question Paper-2-I/II with effect from 2022-23 (CBCS Scheme)


First/Second Semester B.E. Degree Examination Introduction to C Programming
TIME: 03 Hours Max.Marks: 100
Note:
01. Answer any FIVE full questions, choosing at least ONE question from each MODULE.
02. Use C code snippet to illustrate a specific code design or a purpose.

Module -1

Q.01.a What is a computer? Write the characteristics of computer. L1 marks-6


Definition of computer: Computer is an electronic calculating device that performs mathematical and
logical operations automatically by accepting data as an input from the input devices, process the data
and finally produce an output to the output devices. It can process, store and retrieve large amount of
data very quickly.
Characteristics of computer:
Speed: A computer is very fast device. It can carry out instructions at very high speed. Computer
transmission speed is 1 x 10-9 seconds and 1 x 10-12 seconds, so computer speed is expressed by
nanoseconds and picoseconds respectively.
Accuracy: Accuracy of computer is consistently high when compared to human and the degree of
accuracy of particular computer depends on the instructions and the type of processor used. The
accurate result of computer is 99%.
Memory Storage: Data storage is an essential function of computer. A computer can have lot of storage
devices which can store tremendous amount of data.
Reliability: A computer can produce a stable and consistent result, while repetitive jobs are performed.
If humans can do repetitive jobs, he can commit mistakes. So, computer is reliable than human by its
consistent performance.
No feeling: Its performance is same for all the users i.e., it does not distinguish between users, under
any kind of environment. This is because it doesn’t have its own emotions, knowledge etc... that is
present in humans.
Power of remembering: Computer has the power of storing any amount of information or data. Any
information can be stored and recalled as long as it is required.
No I. Q: A computer does only what it is programmed to do. It cannot take its own decision in this
regard.
Versatility: Computer is capable of performing almost any task, if the task can be reduced to a finite
series of logical steps.
Diligence: Unlike humans, computers never get tired of a repetitive task. It can continuously work for
hours without creating errors and with accuracy.
Automation: Computers are automatable devices that can perform a task without any user intervention.
The user just needs to assign the task to computer, after which it automatically controls different
devices attached to it and executes the program instructions.
Economical: Today, computers are considered as short-term investments for achieving long-
term gains. Using computers also reduces manpower requirements and leads to elegant and
efficient way of performing various tasks. Hence, computers save time, energy and money.

1
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Q.01.b With the neat diagram, Explain the working of CRT monitor and LCD monitor. L2
marks-8.
Monitors
The monitor is a soft copy output device used to display video and graphics information generated by
the computer through the video card. Computer monitors are similar to television screens but they
displayed information at a much higher quality. The monitors come in three variants—cathode ray tube
(CRT), liquid crystal display (LCD), and plasma.
CRT Monitor:
 CRT monitors work by firing charged electrons at a phosphorus film. When electrons hit the
phosphor-coated screen, they glow, thereby enabling the user to see the output.
 CRT stands for Cathode Ray Tube, and is descriptive of the technology inside that chunky
monitor you might have on your desk.
 CRTs receive their picture through an analogue cable, and that signal is decoded by the display
controller, which handles the internal components of the monitor - think of it as the mini-CPU
for the monitor.
 CRTs have a distinctive funnel shape. At the very back of a monitor is an electron gun. The
electron gun fires electrons towards the front through a vacuum which exists in the tube of the
monitor. The gun can also be referred to as a cathode - hence the electrons fired foward are
called Cathode Rays.
 These rays correspond to to the red, green and blue channels of the display and video card.
At the neck of the funnel-shaped monitor is an anode, which is magnetised according to
instructions from the display controller. As electrons pass the anode, they are shunted or pulled
in one direction or the other depending on how magnetic the anode is at that time. This moves
the electrons towards the correct part of the screen.

The electrons pass through a mesh, and this mesh defines the individual pixels and resolution on the
screen. Electrons that pass through the mesh then hit the phosphor coating which is on the inside of the
glass screen. When the particles hit the phosphor, they immediately light up - causing the light to shine
through the front of the monitor, thus making up the picture on the screen. There are three differently
coloured phosphours for each pixel (known as phosphor triads), and depending on which phosphor the
electron hits, that's which colour the pixel will light up.

LCD: An LCD monitor is a thin, flat, electronic visual display that uses the light modulating properties of
liquid crystals, which do not emit light directly. LCD screens are used in a wide range of applications
2
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

ranging from computer monitors, televisions, instrument panels, video players, gaming devices, clocks,
watches, etc.

LCD panels are fairly simple to understand. The signal comes in and, as with a CRT, the signal from the
video controller is decoded and understood by a display controller on the monitor itself. The controller
has two things to control - the electrics of the pixels and the light source.

The actual image on a TFT is made up of a matrix of pixels. Unlike with CRTs, there's no complex
equation of dot pitch and image area to try and calculate - the native resolution of the monitor is simply
the number of pixels contained in the matrix. If it's a 17" monitor, chances are there are 1280 pixels in
the matrix horizontally, and 1024 vertically.

Fig: Working of LCD

Each pixel is made up of three sub-pixels, which have red, green and blue filters in front of them, just as
each pixel on a CRT has RGB phosphors. The subpixels are made up of a group of liquid crystal
molecules. These molecules are suspended between transparent electrodes and are mashed between
two polarising filters.

The two filters are exact opposites of each other. As the light from the light source behind the first filter
comes in, the filter effectively whites it out - which means that if it was to pass through the liquid
crystals with no interaction, the filter on the other side would polarise it back to black, leaving no colour
being emitted. In fact, alternate current - leaving the crystals 'dead in the water' - is how black is created
on a panel.

However, if the electrodes apply current to the liquid crystals they twist and change the way that the
light is passed through, altering its polarisation and this then results in the correct colour coming out of
the second polarising filter and being displayed to the user.

3
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Q.01.c Write a structure of a C program with an example. L1 marks-6

Structure of a C Program

fig: Structure of C Program

Preprocessor directives: They contain special instructions which indicate how the program is prepared
for compilation. Common preprocessor command is 'include' that tells the compiler to execute a
program where some information is required from the specified header file.
Global declaration: It is a variable/function which is declared after the preprocessor directives and
before the main() function.

Example:
#include <stdio.h>
#include <conio.h>
int add (int a, int b);
void main()
{
...…...........
}

 A C program contains more than one function where the functions are defined together as a group and all the
statements are executed together. The statements are written logically and in a sequence for performing
certain tasks.
 The main() function is one of the most important parts of the program. It is a compulsory part of every C
program.
 All the functions in the program which include the main() function are divided into two parts –
 Declaration section: describes the data that will be used in the function.
 Statement section: contains the code that will manipulate the data for specified tasks.
4
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

 A C program can have a number of functions depending on the number of tasks. Any number of statements
can be included in the function.

OR
Q.02 a Define the following terms with an example

i. Algorithm
ii. Flowcharts
iii. Pseudo code L1 marks-6

i. Algorithm
An algorithm is a step-by-step, well-defined procedure to solve a given problem. An algorithm provides a
blueprint to writing a program to solve a particular problem. Once a blue print of a solution is created,
we can implement it in high-level programming language like c, c++, java, python etc.
Characteristics of Algorithm
Every step of an algorithm (pseudocode) should perform a single task.
Ambiguity should not be included at any stage of an algorithm i.e., pseudocode.
An algorithm should involve a finite number of steps to arrive at a solution.
Every algorithm should lead to a unique solution of the problem.
An algorithm should have the capability to handle some unexpected situations, wish may arise during
the solution of a problem.

ii. Pseudocode
The word "pseudo” means “not real” so pseudocode means not a real code.
It is another way of representing an algorithm.
It is generally used to represents the structural flow of a program and it is not associated with a specific
language.
It is not a programming language, it is just a learning and reasoning tool, which is used by programmer
and developers to underline how to write the actual code.
It is a detailed description of instruction that a computer must follow in a particular order.
It cannot be executed directly by the computer.

iii. Flowchart
A flowchart is a graphical or symbolic representation of an algorithm. Each step in the process is
represented by a different symbol and contain a short description of that step. These symbols are
connected with arrows to show the flow of control from one step to another step.

5
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Example for pseudocde:

Program pseudocode
main() Begin
{ Number s1, s2, sum
Int num1, num2, sum; Output (“input number 1:”)
Printf(“enter two integers: “); Input s1
Scanf(“%d%d”, &num1, &num2); Output (“input number 2:”)
Sum=num1+num2; Input s2
Printf(“%d + %d=%d”, num1, num2, sum); Sum=s1+s2 Output sum end
return 0;
}

Q.02 b What are variables how they are declared and initialized with an example L1 marks-8
Variables
 A meaningful name given to a data storage location in the computer memory is known as a Variable.
 When a variable is used it actually refers to a address of the memory where the data is stored.
 A variable name can comprise of letters, digits and underscore characters.
 The first character has to be an alphabet.
 There should be no commas or blank spaces between the variable names.
 Variable declaration
 All the variables that we wish to to use in the program need to be declared.
Syntax:
data-type variable-name;

In the above syntax a data-type is declared along with a variable name. Meaningful names should be
given to the variables.
Example: A simple variable declaration.
int emp_id;
float salary;
Variables can be declared anywhere in the program according to their needs. Multiple variables can also
be declared in one statement but the data-type has to be the same.

6
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Example: Multiple variable declaration


float salary, bonus;
Example: A simple variable definition/Initialization.
int emp_id=21;
float salary=2000;
Generally variables are declared in three places as follows:
1. Local variable is declared inside the function.
2. Formal parameters are declared in the definition of the function parameters.
3. Global variables are declared outside all the functions.

Q.02 c Write a C program to demonstrate the use of printf and scanf statements to read and
print values of variables of different data types. L1 marks-6

#include
int main( )
{
int a, b, c;
float d, e, f;
char g;
bool j;
printf(“enter the integer value of a and b\n”);
scanf(“%d %d\n”, a&,&b);
c=a+b;
printf(“%d\n”, c);
printf(“enter the float value of d and e\n”);
scanf(“%f %f\n”, d&,&e);
f=d+e; printf(“%f\n”, f);
printf(“enter a character value of g\n”);
scanf(“%c \n”, &g);
printf(“%c equivalent integer value in ascii character is %d\n”, c, c);
printf(“enter the value of j \n”);
scanf(“%d”, &j);
z=(bool)j;
printf(“ %d\n”, &z);
return 0;
}
Module 2

Q. 03. a Explain the syntax and working of switch case statement. Write a C program to
determine whether an entered character is Vowel or not. L2 marks-10

This case statement is a multi-way decision statement which is a simpler version of the if-else block
which evaluates only one variable. All the expressions should have a result of an integer value or the
character value.

7
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Syntax:
switch (expression)
{
case expression 1: statement 1;
statement 2;
............
statement n;
break;

case expression 2: statement 1;


statement 2;
..........
statement n;
break;

default: statement 1;
statement 2;
...........
statement n;
}
Fig: Flowchart of swith case

Example 1: Write a program to check if the character Example 2: Write a program to implement switch case
entered is a vowel or not. statement.
#include <stdio.h> #include <stdio.h>
void main( ) void main( )
{ {
char ch; int n;
printf("Enter any character:"); printf("Enter any number:");
scanf("%c", &ch); scanf("%d", &n);
switch(ch) switch(n)
{ {
case 'A': case 1: printf(“the value is %d”,n);
case 'a': break;
case 'E': case 2: printf(“%d”,n);
case 'e': break;
case 'I': default:
case 'i': printf("%d is not a case”,n);
case 'O': break;
case 'o': }
case 'U': }
case 'u':
printf("%c is a vowel",ch); Output:
break; Enter any character: 1
default: the value is 1
printf("%c is not a vowel", ch);
}
}
Output:
Enter any character: c
c is not a vowel.

8
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Q.03. b Develop a C program to find the largest of three numbers using ternary operator. L3
marks-6

//C program to find the largest of three numbers Output:


using ternary operator Enter first number: 5
#include<stdio.h> Enter second number: 2
#include<conio.h> Enter third number: 9
void main()
{
int a, b, c, larg;
printf("Enter first number: ");
scanf("%d", &a);
printf("Enter second number: ");
scanf("%d", &b);
printf("Enter third number: ");
scanf("%d", &c);
larg = (a>b)?((a>c)?a:c):((b>c)?b:c);
printf("Largest number is: %d", larg);
getch();
}

Q.03 c Develop a program to convert an integer into the corresponding floating point number
using Type casting. L3 marks-4
Converting one datatype into another is known as type casting or, type-conversion. For example, if you
want to store a 'floating point' value into a simple integer then you can type cast 'float' to 'int'. You can
convert the values from one type to another explicitly using the cast operator as follows –

(type_name) expression

Consider the following example where the cast operator causes the division of two int point number
whose evaluated value is 2 stored in variable c. But, because of the cast operation it is converted into
float value and stores the value 2.5 in variable result.

#include <stdio.h>

main() {

int a = 2, b = 5, c;
float result;

c= b / a;
result=(float)c
printf("Value of mean : %f\n",c );
}

9
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

When the above code is compiled and executed, it produces the following result −

Output: Value of mean : 2.5

Type conversions can be implicit which is performed by the compiler automatically, or it can be specified
explicitly through the use of the cast operator. It is considered good programming practice to use the
cast operator whenever type conversions are necessary.

OR
Q.04 a Demonstrate the working of break and continue statement with suitable example. L2 marks-4
switch case

2.1. continue statement 2. break statement


This is one of the easiest and the most basic keyword in In all the C loops we have a way to break out of a loop at
C, which gives programmers control over loops. any point in time, immediately, regardless of the
The continue exactly as the name suggests. Since we use conditions set for the loop. This is done using
this in loops, it will skip over the remaining body of the the break keyword. In simple words,
current loop, and continue to the next iteration. We can the break statement is a loop control statement which is
use this inside any loops like for, while, or do- used to terminate the loop immediately.
while loops. Basically break statements are used in the situations
In Simple words, when we are not sure about the actual number of
1. The continue statement is used to skip the remaining iterations for the loop or we want to terminate
portion of a for/while loop. the loop based on some condition.
2. we continue onto the next iteration, and move to the Syntax :
loop condition check. break;
3. This is quite useful for programmers to be flexible with Note : The break statement is almost always used
their approach in control loops. with if...else statement inside the loop.
Syntax : How break statement works?
continue;
Note : The continue statement is almost always used
with the if...else statement.
How continue statement works?

Example : break statement

10
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

// program to use break statement inside for loop


Working of Continue statement in C #include <stdio.h>
Example : continue statement int main()
// loop to print numbers 1 to 10 except 4 {
#include <stdio.h> for (int i = 1; i <= 10; i++)
int main() {
{ // break condition
for (int i = 1; i <= 10; i++) if (i == 5)
{ {
// if i is equal to 4 , continue to next iteration break;
without printing 4. }
if (i == 4) printf("%d ", i);
{ }
continue; return 0;
} }
else Output
{ 1234
// otherwise print the value of i. In the above example, a for loop is used to print the
printf("%d ", i); value of ‘i’ in each iteration. In which a if statement is
} used with break statement in it. The condition
} of if statement is i == 5 i.e. when ‘i’ is equal to 5
return 0; and break statement is executed to terminate the loop.
} Hence, the output doesn't include values greater than or
Output equal to 5. In C programming, break is also used with
1 2 3 5 6 7 8 9 10 the switch statement.
In the above program, we have used the for loop to print
the value of i in each iteration. Here, notice the code,
if (i == 4)
{ continue; }
this means,
When i is equal to 4, the continue statement skips the
current iteration and starts the next iteration
Then, i becomes 5, and the condition is evaluated again.
Hence, 5 and 6 are printed in the next two iterations.
Loop prints the value of i until it became 11 and
condition becomes fales. Then, the loop terminates.

Q.04 b Explain relation operator and logical operator. L2 marks-6


Relational Operators
The following table shows all the relational operators supported by C. Assume variable A holds 10 and
variable B holds 20 then −
Operator Description Example

== Checks if the values of two operands are equal or not. If yes, then the condition becomes true. (A ==
B) is not
true.
!= Checks if the values of two operands are equal or not. If the values are not equal, then the (A != B)
condition becomes true. is true.

11
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

> Checks if the value of left operand is greater than the value of right operand. If yes, then the (A > B)
condition becomes true. is not
true.
< Checks if the value of left operand is less than the value of right operand. If yes, then the (A < B)
condition becomes true. is true.

>= Checks if the value of left operand is greater than or equal to the value of right operand. If yes, (A >=
then the condition becomes true. B) is not
true.
<= Checks if the value of left operand is less than or equal to the value of right operand. If yes, (A <=
then the condition becomes true. B) is
true.

Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A holds 1 and
variable B holds 0, then –

Operator Description Example


&& Called Logical AND operator. If both the operands are non-zero, then the condition (A && B)
becomes true. is false.
|| Called Logical OR Operator. If any of the two operands is non-zero, then the condition (A || B) is
becomes true. true.
! Called Logical NOT Operator. It is used to reverse the logical state of its operand. If a !(A &&
condition is true, then Logical NOT operator will make it false. B) is true.

Q.04 c Compare the working of for while and do while along with their Syntax. L2 marks-10
SR. while loop do-while loop
NO
1. While the loop is an entry control loop because The do-while loop is an exit control loop because in this, first of
firstly, the condition is checked, then the loop's all, the body of the loop is executed then the condition is
body is executed. checked true or false.
2. The statement of while loop may not be executed at The statement of the do-while loop must be executed at least
all. once.
3. The while loop terminates when the condition As long as the condition is true, the compiler keeps executing
becomes false. the loop in the do-while loop.
4. In a while loop, the test condition variable must be In a do-while loop, the variable of test condition Initialized in
initialized first to check the test condition in the the loop also.
loop.
5. In a while loop, at the end of the condition, there is In this, at the end of the condition, there is a semicolon.
no semicolon. Syntax:
Syntax: while (condition);
while (condition)
6. While loop is not used for creating menu-driven It is mostly used for creating menu-driven programs because at
programs. least one time; the loop is executed whether the condition is
true or false.
7. In a while loop, the number of executions depends In a do-while loop, irrespective of the condition mentioned, a
on the condition defined in the while block. minimum of 1 execution occurs.
8. Syntax of while loop: Syntax of do-while loop:
while (condition) do
{ {
12
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Block of statements; statements;


} }
Statement-x; while (condition);
Statement-x;
9. Program of while loop: Program of do-while loop:
#include #include
#include #include
Void main() Void main()
{ {
int i; int i;
clrscr(); clrscr();
i = 1; i = 1;
while(i<=10) do
{ {
printf("hello"); printf("hello");
i = i + 1; i = i + 1;
} }
getch(); while(i<=10);
} getch();
}

Module-3

Q.05.a What is recursion? Develop a C program to print Fibonacci series using recursion.
marks-8
 A function which calls itself is #include<stdio.h>
int fibonacci(int);
called a Recursive function. int main()
 It also means that some statement in {
int n, i=0,res;
that function's body calls to same
printf(“Enter the number of
function. terms\n”);
 While using the recursive functions, scanf(“%d”,&n);
printf(“fibonacci series \n“);
it is important to be careful to define
for(i=0;i<n;i++)
the exit condition from the function {
or then it may result into an infinite res=fibonacci(i);
printf(“%d\t”,res);
loop. }
 So exit condition of a recursion is return 0;
called as base condition. }
int fibonacci(int n)
 A function call which calls itself is {
called as recursive function. The if(n==0)
return 0;
process is recursion.
else if(n==1)
 The recursive functions are very return 1;
13
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

useful for solving mathematical else


return (fibonacci(n-1)
problems. +fibonacci(n-2));
 They are used for calculating }
factorial of a number, Fibonacci
series etc.

Q.05.b How 1D integer array is represented in memory. With the help of suitable example
demonstrate the initializing the element. L1 marks-6

An array is a collection of similar data elements. They generally have the same data types. Instead of
declaring variables individually, arrays help to declare them all together. All the elements of an array are
accessed with the help of an index. They have continuous memory location.

In the above figure you can see the elements and the index that are allotted to them. We can have as
many elements as we want in an array.

Definition and Declaration of Arrays


An array is defined in the same way as variables i.e.. It is series or collection of memory location which
stores the value of same data type. The only difference is that of the size-specifier which tells us the size
of the array.
Syntax:
data-type array-name [array-size];

Example: int arr[10]; // Array declaration


Where,
data-type - all the array elements should have the same data-type. Any valid data-type of C can be
taken.
array-name - is the name of the array.
array-size - it specifies the size of the array. It tells how many elements are present in the array.
The square brackets will tell us that we are dealing with an array in that particular program. They will
use a continuous memory. The size of an array is optional. If the size is specified it should be matched
with the definition. An array declaration cannot have the initial values.

Initialization of Arrays

When we declare an array, we are just allocating space for elements; no values are stored in the array.
There are three ways to store values in an array—first, to initialize the array element at the time of

14
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

declaration; second, and to input value for every individual element at the run time; third to assign
values to the individual elements. This is shown in figure below.

The elements in an array can be initialized when they are declared.


Syntax:
data-type array-name[array-size] = {list of values};
The elements of the array are not initialized by default. It contains garbage value, so before the array is
used it must be initialized or should read some meaningful data in it.
Examples:

15
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Q.05.c Develop a C program to print binary search. L3 marks-6

16
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

OR
Q. 06.a Distinguish between Call by Value and Call by Reference using suitable example. L2
marks-10
When a function is called, the calling function has to pass some values to the called functions.
There are two ways by which we can pass the parameters to the functions:
Call by Value
Call by Reference

1. Call by Value 2. Call by Reference


Here the values of the variables are passed by the calling function to Here, the addresses of the variables are passed by the calling
the called function. If any value of the parameter in the called function to the called function. The address which is used inside
function has to be modified the change will be reflected only in the the function is used to access the actual argument used in the call.
called function. This happens as all the changes are made on the We use ampersand ‘ &’ to pass the address of the variables in
copy of the variables and not on the actual ones. the function call.
Example: Call by Value Ex: Fun1(&a, &b);
#include <stdio.h> To indicate that an argument is passed using call by reference, we
int sum (int n); use asterisk “*” which is placed after the data type in the
void main() parameter list of function header.
{ Ex: fun1(int *n )
int a = 5; {
printf("\n The value of 'a' before the calling function is =%d", a); ….//function body
a = sum(a); //assigning the resultant value returned from the }
function definition to a. For accepting address of the variables we use argument pointers
printf("\n The value of 'a' after calling the function is = %d", a); “*” in the function header.
} If there are any changes made in the parameters in function
int sum (int n) definition, they affect the passed argument as well.
{
n = n + 20; Example: Call by Reference
printf("\n Value of 'n' in the called function is = %d", n); #include <stdio.h>
return n; int sum (int *n);
} void main()
Output: {
The value of 'a' before the calling function is = 5 int a = 5;
Value of 'n' in the called function is = 25 printf("\n The value of 'a' before the calling function is = %d", a);
The value of 'a' after calling the function is = 25 sum(&a);
printf("\n The value of 'a' after calling the function is = %d", a);
}
int sum (int *n)
{
*n = *n + 20;
printf("\n value of 'n' in the called function is = %d", n);
}

Output:
The value of 'a' before the calling function is = 5
value of 'n' in the called function is = -1079041764
The value of 'a' after calling the function is = 25

Q. 06.c Define storage class explain the different storage classes supported by c L2 marks-4
Storage Classes in C Programming
A storage class defines the scope (visibility), default value, location and the lifetime of a variable within a program.
The type that is modified will be preceded.

17
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

General syntax:
<storage_class_specifier> <data_type> <variable_name>
There are four different types of storage classes:
 automatic
 register
 external
 static
1 Auto Storage Class 2 Register Storage Class
This is the default storage class for all the local It is used for defining the local variables which are
variables. stored in the CPU register instead of RAM.
Syntax: The variable has a maximum size which is equal to
auto int x; the register size.
Scope: The auto storage class can be used only Syntax:
within the function scope and block scope i.e. local register int x;
variables. The register storage class should be used for the
Location: RAM variables which require quick access.
Default: Garbage value. If 'register' is defined, it does not mean that the
Lifetime: within the block and function block. variable should be stored in the register. It means
that it can be stored in the register depending on the
hardware and implementing issues.
Scope: The register storage class can be used only
within the function scope and block scope i.e. local
variables.
Location: CPU registers.
Default: Garbage value.
Lifetime: within the block and function block.

3 Static Storage Class 4 Extern Storage Class


It is the default storage class for the global This storage class is used for referencing of the
variables. global variables which is visible to all the program
The memory for the static variables is allocated files.
when the program begins running and gets free If there are multiple files in the same program and
when the program terminates. you want to use a particular function or variable in
Syntax: that file apart from the ones that are declared then
static int x = 10; you can use the extern keyword.
It has an existence throughout the program and Syntax:
instead of getting created and destroyed each time, extern int x;
it comes in and out of the scope. They can be declared anywhere outside the
Scope: The static storage class can be used within function. But, in general they are defined and
the function scope, program scope and block scope. declared at the beginning of the source code.
Location: RAM. The external variables have global scope.
Default: Zero or NULL Scope: The extern storage class can be used only in
Lifetime: Throughout the program or till the end of program scope i.e. Global variables.
program. Location: RAM
Default: Zero
Lifetime: Throughout the program or till the end of
program

Module-4

18
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Q. 07.a How 2D array is represented in memory. Explain with suitable example. L2 marks-8
At times we need to store the data in form of tables or matrices. For this, we can use the two
dimensional arrays. This array is specified by using two subscripts where one subscript is denoted as the
row and the other as the column. It is also viewed as an array of arrays.

Above figure shows how the rows and columns are addressed in a two- dimensional array. The first
subscript denotes the row and the second subscript denotes the column. i) Declaration of a two-
dimensional array
The declaration of the array will tell the compiler as to which array is being used for the program.
Syntax:
data_type array_name [row_size] [column_size] ;

The declaration of the rows and columns is compulsory for a two-dimensional array.
We cannot replace the row size with the column size and the column size to row size. The proper
sequence has to be maintained.
ii) Initialization of two-dimensional array
A two-dimensional array is initialized in the same way as the one-dimensional array.

Example: Initialization of 2D array


int score [3] [2] ={50, 60, 70, 95, 3, 36};

The initialization of the array is done row-by-row.

The above can also be written in the following manner:


int score [3] [2] ={{50, 60} , {70,95} ,{3,36}};

The elements will be seen in the following format once they are initialized.

score[0][0] = 50 score [0][1] = 60


score[1][0] = 70 score [1][1] = 95
score[2][0] = 3 score [2][1] = 36

The above example has been divided into three rows and two columns.

19
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Q. 07.b Develop a C program to sort the given set of N numbers using bubble sort L3 marks-6

Output:
Enter the value of n 5
Enter the number one by one
25146
The Sorted items are: 1 2 4 5 6

Q. 07.c What are strings? Mention the reading strings and writing strings along with their
Syntax. L2 marks-6
Strings are known as a one dimensional array of characters. A group of characters is called as a character
array. The difference between any type of array and the strings is that a character array ends with a '\0'
character.
Syntax:
char str_name = “string_name”;
Reading Strings
If we declare a string by writing
char str[100];
Then str can be read by using three ways:
 Using scanf( ) function
 Using gets( ) function
 Using getchar( ), getch( ) or getche( ) functions,
Example 1: scanf() to read a string
#include <stdio.h>
int main()

20
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
return 0;
}
Output
Enter name: Dennis Ritchie
Your name is Dennis.
Example 2: using gets( )
They help in transferring the strings between the computer and the standard input-output devices. Only single
arguments are accepted. The arguments must be such that it represents a string. It may include white space
characters. If gets is used enter key has to be pressed for ending the string. The gets is used to offer simple
alternatives of scanf( ) for reading strings.

Example:
#include <stdio.h>
void main()
{
char line[30];
gets (line);
puts (line);
}
2. Writing Strings
Then str can be written by using three ways:
 Using printf( ) function
 Using puts( ) function
 Using putchar( ) functions.
Example 1: printf() to read a string
#include <stdio.h>
int main()
{
char name[20];
printf("Enter name: ");
scanf("%s", name);
printf("Your name is %s.", name);
printf("Your name is %5.3s.", name); // 8.3 means 8 fields 3 characters from right side
printf("Your name is %-5.3s.", name); //-8.3 means 8 fields 3 characters from left side

return 0;
}
Output
Enter name: Dennis Ritchie
Your name is Dennis.
Your name is Den
Your name is Den
Example 2: Using puts( ) function
Arguments must be such that it represents a string. It may include white space characters. puts( ) is used to offer
simple alternatives of printf( ) for writing strings.

Example:
#include <stdio.h>
void main()
21
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

{
char line[30];
gets (line);
puts (line);
}

OR

Q. 08.a Develop a C program to implement matrix multiplication and validate the rules of
multiplication marks-8
Multiplication of matrix }printf("%d\t",mul[i][j]);
#include<stdio.h> }
main() printf("\n");
{ }
int a[10][10],b[10][10],mul[10][10],r,c,i,j,k; }
printf("enter the number of row and col=");
scanf("%d%d",&r,&c);
printf("enter the first matrix element=\n"); Output:
for(i=0;i<r;i++) enter the number of row and col= 2 2
{ enter the first matrix element=
for(j=0;j<c;j++) 1
{ 1
scanf("%d",&a[i][j]); 2
} 2
}
enter the second matrix element=
printf("enter the second matrix element=\n");
2
for(i=0;i<r;i++)
{ 2
for(j=0;j<c;j++) 2
{ 2
scanf("%d",&b[i][j]); multiplication of the matrix=
} 4 4
} 8 8
printf("multiplication of the matrix=\n");
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
mul[i][j]=0;
for(k=0;k<c;k++)
{
mul[i][j]+=a[i][k]*b[k][j];

22
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Q. 08.b With a neat diagram, Explain three dimensional array write a C program to read and
display 2x2x2 array L2 marks-6

for(i=0;i<2;i++)
include <stdio.h>
{
void main() printf("\n\n");
for(j=0;j<2;j++
{
)
int arr[3][3][3],i,j,k; {
printf("\n");
printf("\n Enter the elements for
for(k=0;k<2;k++)
thearray:"); printf("\t array[%d][%d][%d]=%d",i,j,k,
arr[i][j][k]);
for(i=0;i<2;i++)
{ }
for(j=0;j<2;j++) }
}
{ Output:
Enter the elements for the
for(k=0;k<2;k++)
array: 10,20,30,40,50,60,70,80
{ array [0][0][0] = 10
printf("\n array [%d][%d][%d] = array [0][0][1] = 20
array [0][1][0] = 30
",i,j,k); array [0][1][1] = 40
array [1][0][0] = 50
scanf("%d",&arr[i][j][k]);
array [1][0][1] = 60
} array [1][1][0] = 70
array [1][1][1] = 80
}
} The matrix is:
printf("\n The matrix is:");
array[0][0][0]=10 array[0][0][1]=20
array[0][1][0]=30 array[0][1][1]=40
array[1][0][0]=50 array[1][0][1]=60
array[1][1][0]=70 array[1][1][1]=80

23
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Q. 08.c Develop a C program to print the following pattern. L3 marks-6

Module-5

Q. 09.a What is a pointer? Discuss pointer arithmetic with suitable code. L1 marks-6
A variable which contains the memory location of another variable is known as a pointer. It represents
the location of the data item. It is preceded by a '*' (asterik) before the variable.

Syntax:

data_type *ptr_name;
24
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

A pointer variable can store only the address of a variable.


Pointer Arithmetic
1. Increment-Decrement

Syntax:
int *pt;
pt++
pt--
pt++ will increment the pointer to the next location of the same type.
pt-- will decrement the pointer to the previous element of the same type.

2. Assignment
The pointers must be of the same type.
Syntax:
int *p1, *p2;
If we write *p1 = *p2 both the pointers will point to the same location.

3. Addition of an integer

Syntax:
int i, *p;

If we write p+i the pointer will point to the ith object after its initial position.
4. Subtraction of an integer
Syntax:
int i, *p;
If we write p-i the pointer will point to the ith object after its initial position.

5. Comparison of pointers
The pointers should be pointing to the elements of the same array.
Syntax:
int *p1, *p2;

If p1<p2 then 1 would be returned, if p1 points to an element which is close to the array beginning.

Q. 09.b Using suitable code, Discuss the working of the following string functions. L2 marks-8
i. strcat
ii. strlen
iii. strstr
iv..strcmp

25
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

i. #include <stdio.h> iii. #include <string.h>


#include <string.h> #include <string.h>
void main () int main()
{ {
char s1[12] = "good"; // Take any two strings
char s2[12]=” morning”; char s1[] = "A program";
char s2[] = "program";
/* string concatenation */
char* p;
strcat( s1, s2);
printf("strcat( s1, s2): %s\n", s1 ); // Find first occurrence of s2 in s1
} p = strstr(s1, s2);
Output: // Prints the result
strcpy( s3, s1) : goodmorning if (p)
{
printf("String found\n");
printf("First occurrence of string '%s' in '%s' is '%s'",
s2, s1, p);
}
else
printf("String not found\n");
return 0;
}
Output: String found
First occurrence of string 'program' in 'A program' is
'program’.

ii. #include <stdio.h> iv. #include <stdio.h>


#include <string.h> #include <string.h>
void main () int main()
{ {
char s1[12] = "good"; char str1[] = "Hello";
int l ; char str2[] = "hello";
/* string length */ int result = strcmp(str1, str2);
l = strlen(s1); if (result == 0)
printf("strlen(s1) : %d\n", l ); {
} printf("Strings are equal");
Output: }
strlen(s1) : 11 else
{
printf("Strings are not equal");
}

}
Output: Strings are not equal

26
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Q. 09.c Develop a C program to concatenate two strings without using built-in function. L3
marks-6
Concatenation: To concatenate two strings in C, we can create a
new character array to hold the result and copy the characters
from both strings into it. Here's an example:

#include <stdio.h>
int main()
{
char p[20] = "Hello";
char q[20] = "world";
int c, d ;
c = 0;
while (p[c] != '\0')
{
c++;
}
d = 0;
while (q[d] != '\0')
{
p[c] = q[d];
d++;
c++;
}
p[c] = '\0';
printf("Concatenated string: %s \n", p);
}

Output:
Concatenated string: Helloworld

OR

Q. 10.a Develop a program using pointers to compute the Sum, Mean and Standard deviation
of all elements stored in an array of N real numbers. L3 marks-7

27
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Q. 10.b Define structure? How structure is declared and initialize. L2 marks-6

Structure is a collection of data items of different data types. It is a user defined data type which stores
related information together. It is also known as a collection of variables under a single name.
General format of a structure is as follows:
struct struct_name
{
member 1;
member 2;
.
.
member n;
};
The semicolon should be used after the closing brace brackets.
struct is the required keyword.
struct_name is the name given to the structure.

Declare:
struct struct_name
{
28
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

member 1;
member 2;
.
.
member n;
} var1, var2, …..varn;

Example:

struct student
{
char name[20];
int roll_no;
float marks, avg;
}s1, s2, s3;

Example : Initialization of a structure

struct student
{
char name[20];
int roll_no;
float fees;
}s1={“Raj”, 5, 50000};

OR

struct student s1 = {“Raj”, 5, 50000};

29
SSB,KIT,TIPTUR-572201
Introduction to C programming Model paper 2 2022-23

Q. 10.c Develop a C program to implement a structures read, write and compute average
marks and the students scoring above and below the average marks for a class of N students
L3 marks-7

30
SSB,KIT,TIPTUR-572201

You might also like