You are on page 1of 26

MAHARAJA INSTITUTE OF TECHNOLOGY MYSORE

Belawadi, Srirangapatna, Mandya-571477


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
1st Semester
MODEL 2 QUESTION PAPER ANSWER
2022-23
Subject: Principles of Programming Using C Subject Code: BPOPS103
Section: ‘I’ and ‘L’ Faculty: Dr. Honnaraju B
MODULE-1
1. (a). Explain the structure of C program in detail. Write a sample program to
demonstrate the components in the structure of C program. 8 Marks
Answer:
Preprocessor Directives
Global Declarations

main( )
{
Local declaration
Statements;
}
Function1( )
{
Local declaration
Statements;
}
Function2( )
{
Local declaration
Statements;
}
………………….
………………….
FunctionN( )
{
Local declaration
Statements;
}
A C program is composed of pre-processor commands, a global declaration section, and
one or more functions.
The pre-processor directives contain special instructions that indicate how to prepare the
program for compilation. One of the most important and commonly used pre-processor
commands is include which tells the compiler that to execute the program, some
information is needed from the specified header file.
The statements in a C program are written in a logical sequence to perform a specific
task.
Execution of a C program begins at the main() function.
You can choose any name for the functions.
Every program must contain one function that has its name as main().

/* This is my first program in C */


#include<stdio.h>
void main()
{
printf("\n Welcome to the world of C ");
}
Solution:
Write the basic structure of the C program 3 Marks
Explain the basic structure of C program 5 Marks
Scheme [3 + 5 = 8 Marks]

(b). Demonstrate formatted output of integer in C with suitable example. 6 Marks


Answer:
The general form of formatted output statement (printf statement) is:
printf(“ Control string”, arg1, arg2, ………. argn);
Control string consists of three types of items:
1. Characters that will be printed on the screen as they appear.
2. Format specifications that define the output format for display of each item.
3. Escape sequence characters such as \n, \t, and \b.
The control string indicates how many arguments follow and what their types are. The
argument =s arg1, arg2, ………. Argn are the variables whose values are formatted and
printed according to the specification of the control string. The arguments should match
on number order and type with the format specifications.
A simple format specification has the following form:
% w.p type-specifier
• Example: Program to read your age and display the same on the screen.
#include<stdio.h>
void main()
{
int age;
printf(“enter your age: \n”);
scanf(“%d”, age);
printf(“your age is = %d years ”, age);
}
Solution:
Explain formatted output statement printf with example 6 Marks
Scheme [6 = 6 Marks]

(c). Discuss different types of error occur in program. 6 Marks


Answer:
While writing programs, very often we get errors in our program. These errors if not
removed will either give erroneous output or will not let the compiler to compile the
program. These errors are broadly classified under four groups as shown in Figure below.

.
Types of Errors
Run-time Errors As the name suggests, run-time errors occur when the program is
being run executed. Such errors occur when the program performs some illegal
operations like
• Dividing a number by zero
• Opening a file that already exists
• Lack of free memory space
• Finding square or logarithm of negative numbers
Run-time errors may terminate program execution, so the code must be written in such a
way that it handles all sorts of unexpected errors rather terminating it unexpectedly. This
ability to continue operation of a program despite of run-time errors is called robustness.
Compile-time Errors Again as the name implies, compile-errors occur at the time of
compilation of the program. Such errors can be further classified as follows:
 Syntax Errors Syntax error is generated when rules of C programming language
are violated. For example, if we write int a: then a syntax error will occur since the
correct statement should be int a;
 Semantic Errors Semantic errors are those errors which may comply with rules of
the programming language but are not meaningful to the compiler. For example, if
we write, a * b = c; it does not seem correct. Rather, if written like c = a * b would
have been more meaningful.
Logical Errors Logical errors are errors in the program code that result in unexpected
and undesirable output which is obviously not correct. Such errors are not detected by
the compiler, and programmers must check their code line by line or use a debugger to
locate and rectify the errors. Logical errors occur due to incorrect statements. For
example, if you meant to perform c = a + b; and by mistake you typed c = a * b; then
though this statement is syntactically correct, it is logically wrong.
Linker Errors These errors occur when the linker is not able to find the function
definition for a given prototype. For example, if you write clrscr(); but do not include
conio.h then a linker error will be shown. Similarly, even if you have defined a function
display_data() but while calling if you mistakenly write displaydata() then again a linker
error will be generated.
Solution:
Explain 4 major errors in C program 6 Marks
Scheme [6 = 6 Marks]

OR
2. (a). Explain the various rules for forming identifiers names. Give examples for
valid and invalid identifiers for the same. 8 Marks
Answer:
● Identifiers are names given to program elements such as variables, arrays and
functions. Identifiers may consist of sequence of letters, numerals, or underscores.
Rules for forming identifier name
● it cannot include any special characters or punctuation marks (like #, $, ^, ?, .,
etc) except the underscore"_".
● There cannot be two successive underscores
● Keywords cannot be used as identifiers
● The names are case sensitive. So, example, “FIRST” is different from “first” and
“First”.
● It must begin with an alphabet or an underscore.
● It can be of any reasonable length. Though it should not contain more than 31
characters.

Example:
Valid variable invalid variable
num2 $num1
_apple +add
a_2 199_space
#12
Solution:
Rule for forming identifier 5 Marks
Classify valid and invalid variable 3 Marks
Scheme [5 + 3 = 8 Marks]

(b). Mention various output devices and explain hardcopy devices. 6 Marks
Answer:
Any device that outputs/gives information from a computer is called an output device.
Output devices are electromechanical devices which accept digital data from the
computer and converts them into human understandable language.

Classification of output devices

HARD COPY OUTPUT DEVICES


Hard copy output devices produces a physical form of output. For example, the content of
a file printed on a paper is a form of hard copy output.
PRINTERS
Printer is a device that outputs text and graphics information obtained from the
computer and prints it on to a paper. Printers are available in the market in a variety of
size, speed, sophistication, and cost. The qualities of printer which are of interest to
users include:
Color: Colored printouts are needed for presentations or maps and other pages where
color is part of the information. They are more expensive.
Memory: Most printers have a small amount of memory that can be expanded by the
user. Having more memory makes enhances the speed of printing
Resolution: The resolution of a printer means the sharpness of text and images on
paper. It is usually expressed in dots per inch (dpi). Even the least inexpensive printer
provides sufficient resolution for most purposes at 600 dpi.
Speed: Speed means number of pages that are printed in one minute. While high speed
printers are a little expensive, the inexpensive printers on the other hand can print only
about 3 to 6 sheets per minute. Color printing is even slower.
Impact Printer. They create characters by striking an inked ribbon against the paper.
Ex., dot-matrix printers, daisywheel printers, and most types of line printer.
Non-Impact Printer: Non-impact printers are much quieter than impact printers as their
printing heads do not strike the paper. They offer better print quality, faster printing and
the ability to create prints that contain sophisticated graphics.
Solution:
Mention various output devices 2 Marks
Explain hardcopy output devices 4 Marks
Scheme [2 + 4 = 6 Marks]

(c). Discuss the variants of microcomputer that are widely used today 6 Marks
Answer:
Microcomputers, commonly known as PCs, are very small and cheap. The first
microcomputer was designed by IBM in 1981 and was named IBM-PC.
Later on, many computer hardware companies copied this design and termed their
microcomputers as PC-compatible, which refers to any PC that is based on the original
IBM PC design.
Another type of popular PC is designed by Apple. PCs designed by IBM and other PC-
compatible computers have a different architecture from that of Apple computers.

Laptop: Laptops are small microcomputer that can easily fit inside a briefly.
Desktop PCs: A desktop PC is the most popular model of PCs. The system unit of the
desktop PC can be placed flat on a desk or table.
Workstation: Workstation are single-user computer that have the same features of PCs,
but their processing speed matches that of a minicomputer or mainframe computer.
Network Computer: Network computer have less processing power, memory, and
storage than a desktop computer. These computers are specifically designed to be used
as terminals in a networked environment.
Handheld Computers: The mid-1990s witnessed a range of small personal computing
devices that are commonly known as handheld computers, or mobile computers. (Smart
phones and Tablet PCs)
Solution:
Explain various microcomputers 6 Marks
Scheme [6 = 6 Marks]
MODULE-2

3. (a). Demonstrate the functioning of Bitwise operator in C. 6 Marks


Answer:
Bitwise Operators:
● Bitwise operators perform operations at bit level. These operators include: bitwise
AND, bitwise OR, bitwise XOR and shift operators.
● The bitwise AND operator (&) is a small version of the boolean AND (&&) as it
performs operation on bits instead of bytes, chars, integers, etc.
● The bitwise OR operator (|) is a small version of the boolean OR (||) as it
performs operation on bits instead of bytes, chars, integers, etc.
● The bitwise NOT (~), or complement, is a unary operation that performs logical
negation on each bit of the operand. By performing negation of each bit, it
actually produces the ones' complement of the given binary value.
● The bitwise XOR operator (^) performs operation on individual bits of the
operands. The result of XOR operation is shown in the table.
Bitwise Shift Operators:
In bitwise shift operations, the digits are moved, or shifted, to the left or right.
The CPU registers have a fixed number of available bits for storing numerals, so when
we perform shift operations; some bits will be "shifted out" of the register at one end,
while the same number of bits are "shifted in" from the other end.
In a left arithmetic shift, zeros are shifted in on the right.
For example;
unsigned int x = 11000101;
Then
x << 2 = 00010100
If a right arithmetic shift is performed on an unsigned integer then zeros are shifted
on the left.
unsigned int x = 11000101;
Then
x >> 2 = 00110001
Solution:
Demonstrate the function of bitwise operator 6 Marks
Scheme [6 = 6 Marks]

(b). Write a C program to find roots of quadratic equation. 8 Marks


Answer:
/* C Program to compute quadratic equation */
#include <stdio.h>
#include <math.h>
void main()
{
float a,b,c,x1,x2,d,r,i;
printf("\n Enter the Coefficients of Roots\n");
scanf("%f %f %f",&a,&b,&c);
d=(b*b)--(4*a*c);
if(d>0)
{
b+sqrt(d))/(2*a);
b sqrt(d))/(2*a);
printf("\n Roots are Real and Distinct \n");
printf("x1=%f \n x2=%f\n",x1,x2);
}
else if(d == 0)
{
x1= b/(2*a);
printf("\n Roots are Real and Equal \n");
printf("\n x1=%f \n x2=%f\n",x1,x2);
}
else /* if roots are real and imaginary*/
{
b/(2*a);
i=sqrt(fabs(d))/(2*a);
printf("\n Roots are Real and Imaginary \n");
printf("\n x1=%f+i%f \n x2=%f i%f\n",r,i,r,i);
}
}
Solution:
Develop C Program to compute quadratic equation 8 Marks
Scheme [8 = 8 Marks]

(c). Distinguish between the break and continue statement. 6 Marks


Answer:
Break Statement:
● The break statement is used to terminate the execution of the nearest enclosing
loop in which it appears.
● When compiler encounters a break statement, the control passes to the statement
that follows the loop in which the break statement appears.
● Its syntax is quite simple, just type keyword break followed with a semi-colon.
break;
In switch statement if the break statement is missing then every case from the matched
case label to the end of the switch, including the default, is executed.

Continue Statement:
● The continue statement can only appear in the body of a loop.
● When the compiler encounters a continue statement then the rest of the
statements in the loop are skipped and the control is unconditionally transferred
to the loop-continuation portion of the nearest enclosing loop.
● Its syntax is quite simple, just type keyword continue followed with a semi-colon.
continue;
● If placed within a for loop, the continue statement causes a branch to the code
that updates the loop variable.
● For example,

Solution:
Explain difference 6 Marks
Scheme [6 = 6 Marks]
OR
4. (a). Illustrate Nested loops in C with suitable example. 6 Marks
Answer:
C allows its users to have nested loops, i.e., loops that can be placed inside other loops.
Although this feature will work with any loop such as while, do-while, and for, it is most
commonly used with the for loop, because this is easiest to control.
A for loop can be used to control the number of times that a particular set of statements
will be executed. Another outer loop could be used to control the number of times that a
whole loop is repeated.
Syntax
The syntax for a nested for loop statement in C is as follows: −
for ( initialization; condition; increment )
{
for ( initialization; condition; increment )
{
statement(s);
}
statement(s);
}
Programs to print triangles using *, numbers and characters

*
* *
* **
* ***
* ****

#include <stdio.h>
void main()
{
int i, j, rows;
printf("Enter number of rows: ");
scanf("%d",&rows);
for(i=1; i<=rows; ++i)
{
for(j=1; j<=i; ++j)
{
printf("* ");
}
printf("\n");
}
}
Solution:
Explain nested loop with syntax 3 Marks
Write example Program to illustrate nested loop 3 Marks
Scheme [3 + 3 = 6 Marks]

(b). Write a C program to print whether a given number is palindrome or not.


Answer: 7 Marks
/* Program to reverse and check palindrome */
#include<stdio.h>
void main()
{
int num, temp, rev=0,digit;
printf("Enter the Integer number\n");
scanf("%d",&num);
temp =num;
while(num!=0)
{
digit = num % 10;
num = num / 10;
rev = rev * 10 + digit;
}
printf("Reverse of a given number=%d\n",rev);
if(temp == rev)
printf("Given number %d is palindrome\n", temp);
else
printf("Given number %d is not palindrome\n", temp);
}
Solution:
Write a C program to check palindrome 7 Marks
Scheme [7 = 7 Marks]

(c) Explain switch statement with syntax. Write a C program to simulate calculator.
Answer: 7 Marks
● A switch case statement is a multi-way decision statement that is simplified
version of an if-else block that evaluates only one variable.
The general form of the switch statement is as shown below:
switch (variable)
{
case value1:
Statement block-1;
break;
case value2:
Statement block-2;
break;
case value-3:
Statement block-3;
break;
……………………
……………………
case value N:
Statement block-N;
break;

default:
Statement default-block;
break;
}
Statement-x;

Here, statement blocks refer to statement lists contain zero or more statements. These
statements in the block are not enclosed within opening and closing braces.
Switch statements are mostly used in two situations:
1. When there is only one variable to evaluate in the expression.
2. When many conditions are being tested for.
The switch case statement compares the value of the variable given in the switch
statement with value of each case statement that follows. When the value of the switch
and the case statement matches, the statement block of that particular case is executed.
Default is also a case that is executed when no match is found between the values of
switch and case statements and thus there are no statements to be executed.
default is also a case that is executed when the value of the variable does not match
with any of the values of the case statement. That is, the default case is executed when
no match is found between the values of switch and case statements and there are no
statements to be executed.
The break statement must be used at the end of each case because if it is not used, then
the case that matched and all the following cases will be executed.

Example: Simulation of calculator


void main( )
{
int a,b ,opt;
printf("enter any 2 values");
scanf("%d%d",&a,&b);
printf("1.addition\n2.subraction\n3.multiplication\4.division\n6.modular\n");
printf("\n Enter your option");
scanf("%d",&opt);
switch(opt)
{
case 1:
printf("addition of %d & %d is %d",a,b,a+b);
break;
case 2:
printf("sub of %d & %d is %d",a,b,a-b");
break;
case 3:
printf("multiple of %d & %d is %d",a,b,a*b);
break;
case 4:
printf("div of %d & %d is %d",a,b,a/b);
break;
case 5:
printf("modular of %d & %d is %d",a,b,a/b);
break;
default:
printf ("\n invalid option");
}
}
Solution:
Explain switch statement with syntax 3 Marks
Write a C program to simulate calculator 4 Marks
Scheme [3 + 4 = 7 Marks]
MODULE-3
5.(a). Write a C program to implement Bubble sort technique (ascending order).
Answer: 8 Marks
/* Program to arrange the elements */
#include<stdio.h>
void main()
{
int a[10],i,j,n,temp;
printf("Enter the array size\n");
scanf("%d",&n);
printf("Enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Entered array elements are as follows\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
for(i=1;i<=n-1;i++)
{
for(j=0;j<=n-i-1;j++)
{
if(a[j] >= a[j+1])
{
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf("Sorted array elements are as follows\n");
for(i=0;i<n;i++)
{
printf("%d\n",a[i]);
}
}
Solution:
Write C Program to arrange numbers using bubble sort 8 Marks
Scheme [8 = 8 Marks]

(b). Illustrate the concept of recursive function with example. 6 Marks


Answer:
● A recursive function is a function that calls itself to solve a smaller version of its
task until a final call is made which does not require a call to itself.
● Every recursive solution has two major cases, they are base case, in which the
problem is simple enough to be solved directly without making any further calls to the
same function recursive case, in which first the problem at hand is divided into simpler
sub parts. Second the function calls itself but with sub parts of the problem obtained
in the first step. Third, the result is obtained by combining the solutions of simpler
sub-parts.
● Therefore, recursion is defining large and complex problems in terms of a smaller
and more easily solvable problem. In recursive function, complicated problem is
defined in terms of simpler problems and the simplest problem is given explicitly.
Ex:
void main()
{
printf(“MIT Mysore\n”);
main();
}
Above program execute for infinite number of times.

Program:
Base case is when n=1, because if n = 1, the result is known to be 1
Recursive case of the factorial function will call itself but with a smaller value of n, this
case can be given as : factorial(n) = n X factorial (n-1)

/* Program to Find the Factorial of a Number */


#include<stdio.h>
int Fact(int n)
{ if(n==1)
retrun 1;
return (n * Fact(n-1));
}
void main()
{ int num, fact;
printf(“Enter the value for num\n”);
scanf(“%d”, &num);
fact = Fact(num);
printf(“\n Factorial of %d = %d”, num, Fact(num));
}

Solution:
Explain the concept of recursion 3 Marks
Write example program 3 Marks
Scheme [3 + 3 = 6 Marks]

(c). Discuss various scope of variables. 6 Marks


Answer:
In C, all constants and variables have a defined scope.
By scope we mean the accessibility and visibility of the variables at different points in the
program.
A variable or a constant in C has four types of scope: block, function, file and program
scope.

Variable Scope

Function Program
Block scope File scope
scope scope
Block Scope:
A statement block is a group of statements enclosed within an opening and closing curly
brackets ({ }). If a variable is declared within a statement block then, as soon as the
control exits that block, the variable will cease to exist. Such a variable also known as a
local variable is said to have a block scope.
Blocks of statements may be placed one after the other in a program; such blocks that
are placed at the same level are known as parallel blocks.
Function Scope:
Function Scope indicates that a variable is active and visible from the beginning to the
end of a function.
● Function scope is applicable only with goto label names. That is the programmer
cannot have the same label name inside a function.
Using goto statement is not recommended as it is not considered to be a good
programming practice.
Program Scope:
● If you want that functions should be able to access some variables which are not
passed to them as arguments, then declare those variables outside any function
blocks. Such variables are commonly known as global variables. Hence, global
variables are those variables that can be accessed from any point in the program.
File Scope:
● When a global variable is accessible until the end of the file, the variable is said
to have file scope.
● To allow a variable to have file scope, declare that variable with the static keyword
before specifying its data type, like this:
static int x = 10;
● A global static variable can be used any-where from the file in which it is declared
but it is not accessible by any other files.
● Such variables are useful when the programmer writes his own header files.
Solution:
Explain four scope variable 6 Marks
Scheme [6 = 6 Marks]

OR
6.(a). Differentiate between call by value and call by reference. Using suitable
example.
Answer: 8 Marks
Call by Value
● In the Call by Value method, the called function creates new variables to store
the value of the arguments passed to it. Therefore, the called function uses a copy
of the actual arguments to perform its intended task.
● If the called function is supposed to modify the value of the parameters
passed to it, then the change will be reflected only in the called function. In the
calling function no change will be made to the value of the variables.
#include<stdio.h>
void add( int n);
void main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(num);
printf("\n The value of num after calling the function = %d", num);
}
void add(int n)
{
n = n + 10;
printf("\n The value of num in the called function = %d", n);
}
The output of this program is:
The value of num before calling the function = 2
The value of num in the called function = 20
The value of num after calling the function = 2

Call By Reference:
● When the calling function passes arguments to the called function using call by
value method, the only way to return the modified value of the argument to the caller is
explicitly using the return statement. The better option when a function can modify the
value of the argument is to pass arguments using call by reference technique.
● In call by reference, we declare the function parameters as references rather than
normal variables. When this is done any changes made by the function to the arguments
it received are visible by the calling program.
● To indicate that an argument is passed using call by reference, an ampersand sign (&)
is placed after the type in the parameter list. This way, changes made to that
parameter in the called function body will then be reflected in its value in the calling
program.

#include<stdio.h>
void add( int &n);
void main()
{
int num = 2;
printf("\n The value of num before calling the function = %d", num);
add(num);
printf("\n The value of num after calling the function = %d", num);
}
void add( int &n)
{
n = n + 10;
printf("\n The value of num in the called function = %d", n);
}

The output of this program is:


The value of num before calling the function = 2
The value of num in the called function = 20
The value of num after calling the function = 20
Solution:
Explain the difference b/w call-by value and reference 8 Marks
Scheme [8 = 8 Marks]

(b). Write a C program to transpose a M x N matrix. 6 Marks


Answer:
#include<stdio.h>
void main()
{
int arr[5][5],m,n;
int i, j;
printf("Enter the size of the matrix \n");
scanf("%d%d",&m,&n);
printf("Enter the matrix elements \n");
for(i=0;i<m;i++)
{
for(j=0;j<n;j++)
scanf("%d", &arr[i][j]);
}
printf("Matrix elements as follows \n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t", arr[i][j]);
}
printf("Transpose of matrix \n");
for(i=0;i<m;i++)
{
printf("\n");
for(j=0;j<n;j++)
printf("%d\t", arr[j][i]);
}
}
Solution:
Write a C program to transpose a matrix. 8 Marks
Scheme [8 = 8 Marks]

(c). Discuss the various storage classes. 6 Marks


Answer:
STORAGE CLASS
FEATURE
Auto Extern Register Static
Local: Accessible
within the
function or block
Accessible
Accessible within Accessible within in which it is
within all
the function or the function or declared
Accessibility program files
block in which it is block in which it Global:
that are a part
declared is declared Accessible within
of the program
the program in
which it is
declared
Storage Main Memory Main Memory CPU Register Main Memory
Exists when the
Exists when the function or block
function or block in in which it is Local: Retains
which it is declared declared is value between
Exists
is entered. Ceases entered. Ceases to function calls or
throughout the
Existence to exist when the execution of the exist when the block entries
control returns control returns Global: Preserves
program
from the function or from the function value in program
the block in which or the block in files
it was declared which it was
declared
Default
Garbage Zero Garbage Zero
value
Solution:
Explain 4 storage classes. 4 Marks
Scheme [4 = 4 Marks]
MODULE-4
7. (a). Mention various operations that can be performed on string using built-in
functions. Explain any two functions. 6 Marks
Answer:
C supports a large number of string handling functions.
• There are numerous functions defined in <string.h> header file. Below table shows the
some of the function for handling string.
strcat Function
Syntax:
char *strcat(char * str1, char *str2);
The strcat function appends the string pointed by str2 to the end of the string pointed to
by str1. The terminating null character of str1 is overwritten. The process stops when the
terminating null character of str2 is copied.
• Example: Program to illustrate the use of strcat().
#include <stdio.h>
#include <string.h>
void main()
{
char str1[10], str2[10];
printf("Enter First String:");
gets(str1);
printf("\n Enter Second String:");
gets(str2);
strcat(str1,str2); //concatenates str1 and str2 and
printf("\n Concatenated String is ");
puts(str1); //resultant string is stored in str1
}

strcpy Function
Syntax:
char *strncat(char * str1, char *str2);
This function copies the string pointed to by str2 to str1 including the null character of
str2. It returns the argument str1. Here str1 should be big enough to store the content of
str2.
#include<string.h>
#include<stdio.h>
void main()
{
char str1[20],str2[20];
printf("Enter string: ");
gets(str2);
strcpy(str1, str2); //Content of string src is copied to string dest
printf("Copied string: ");
puts(str1);
}
Output:
Enter string: mitmysore
Copied string: mitmysore
Solution:
List different string handling functions 2 Marks
Explain any 2 string handling functions 6 Marks
Scheme [2 + 6 = 8 Marks]

(b). Develop a program using pointer to compute the sum, mean and standard
deviation of all element stored in array of N real number 8 Marks
Answer:
/* Program to find sum, mean, and Standard Deviation using pointer */
#include<stdio.h>
#include<math.h>
void main()
{
float a[10],*ptr,mean,std,sum=0,sumstd=0;
int n,i;
printf("Enter the no of elements n =");
scanf("%d",&n);
printf(" Enter the array elements\n");
for(i=0;i<n;i++)
{
scanf("%f",&a[i]);
}
ptr=a;
for(i=0;i<n;i++)
{
sum=sum+ *ptr;
ptr++;
}
mean=sum/n;
ptr=a;
for(i=0;i<n;i++)
{
sumstd=sumstd+ pow((*ptr-mean),2);
ptr++;
}
std=sqrt(sumstd/n);
printf("Sum=%.3f\t",sum);
printf("Mean=%.3f\t",mean);
printf("Standard Deviation=%.3f\n",std);
}
Solution:
Develop a C program to compute Standard Deviation 8 = 8 Marks
Scheme [8 = 8 Marks]

(c). Explain how strings are represented in main memory. 4 Marks


Answer:
● A string is a null-terminated character array. This means that after the last
character, a null character („\0‟) is stored to signify the end of the character array.
● The general form of declaring a string is
char str[size];
● For example if we write,
char str[] = “HELLO”;
We are declaring a character array with 5 characters namely, H, E, L, L and O.
Besides, a null character („\0‟) is stored at the end of the string. So, the internal
representation of the string becomes- HELLO‟\0‟. Note that to store a string of length 5,
we need 5 + 1 locations (1 extra for the null character).
The name of the character array (or the string) is a pointer to the beginning of the
string.
char str[] = “HELLO”;
str[0] 1000 H Beginning of the string
str[1] 1001 E
str[2] 1002 L
str[3] 1003 L
str[4] 1004 O
str[5] 1005 \0 End of the String

char str[] = “HELLO”;


The forgiven statement declares a constant string as we have assigned value to it while
declaring the string. However, the general form of declaring a string is
char str[size];
When we declaring the sting in this way, we can store size -1 characters in the array
because the last character would be null character.
Solution:
Explain the internal representation of string 4 Marks
Scheme [4 = 4 Marks]
OR
8. (a). Write a program to compare two strings without using built-in function.
Answer: 8 Marks
/* Program to perform string comparison operation */
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void main()
{
int i=0;
int len1=0;
int len2=0;
char str1[50],str2[50];
int flag = 0;
printf("Enter the String 1\n");
gets(str1);
printf("Enter the String 2\n");
gets(str2);
len1 = strlen(str1);
len2 = strlen(str2);
if(len1 != len2)
{
printf("Strings are Not Equal\n");
exit(1);
}
while(str1[i]!='\0')
{
if(str1[i] != str2[i])
{
flag = 1;
break;
}
i++;
}
if(flag == 0)
printf("Strings are Equal\n");
else
printf("Strings are Not Equal\n");
}
Solution:
Develop a C program to compare 2 Strings 8 marks
Scheme [8 = 8 Marks]

(b). What is pointer? Discuss pointer arithmetic with suitable C code. 6 Marks
Answer:
● Actually pointers are nothing but memory addresses.
● A pointer is a variable that contains the memory location of another variable.
Another definition of pointer is: “Pointer is a variable which holds the address of
another variable of same type.”
● The general syntax of declaring pointer variable is
data_type *ptr_name;
Like other variables, pointer variables can also be used in expressions.
For example, if ptr1 and ptr2 are pointers, then the following statements are valid.
For ex,
int num1=2, num2= 3, sum=0, mul=0, div=1;
int *ptr1, *ptr2;
ptr1 = &num1, ptr2 = &num2;

sum = *ptr1 + *ptr2;


mul = sum * *ptr1;
*ptr2 +=1;
div = 9 + *ptr1/*ptr2 - 30;
● We can add integers to or subtract integers from pointers as well as to subtract one
pointer from the other.
● We can compare pointers by using relational operators in the expressions. For
example p1 > p2 , p1==p2 and p1!=p2 are all valid in C.

When using pointers, unary increment (++) and decrement (--) operators have greater
precedence than the dereference operator (*). Therefore, the expression
*ptr++ is equivalent to *(ptr++). So the expression will increase the value of ptr so that it
now points to the next element.
In order to increment the value of the variable whose address is stored in ptr, write
(*ptr)++
Example Programs:
#include <stdio.h>
const int MAX = 3;
void main ()
{
int var[] = {10, 100, 200};
int i, *ptr;
/* let us have array address in pointer */
ptr = var;
for ( i = 0; i < MAX; i++)
{
printf("Address of var[%d] = %x\n", i, ptr );
printf("Value of var[%d] = %d\n", i, *ptr );
/* move to the next location */
ptr++;
}
}
Solution:
Define Pointer 2 Marks
Explain pointer expression with example 4 Marks
Scheme [2 + 4 = 6 Marks]

(c). Explain gets()and puts() function with example. 6 Marks


Answer:
● The string can be read by writing
gets(str);
gets() takes the starting address of the string which will hold the input. The string
inputted using gets() is automatically terminated with a null character.

The string can be displayed by writing


puts(str);
puts() is a simple function that overcomes the drawbacks of the printf() function. The
puts() function writes a line of output on the screen. It terminates the line with a newline
character(\n).

/* Program to concatenates two string */


#include <stdio.h>
#include <string.h>
void main()
{
char str1[10], str2[10];
printf("Enter First String:");
gets(str1);
printf("\n Enter Second String:");
gets(str2);
strcat(str1,str2); //concatenates str1 and str2
printf("\n Concatenated String is ");
puts(str1); //resultant string is stored in str1
}
Solution:
Explain gets() and puts() with example 3 + 3 = 6 Marks
Scheme [6 = 6 Marks]
MODULE-5
9 (a). Explain various modes in which file can be opened for processing. 7 Marks
Answer:
● A file must be first opened before data can be read from it or written to it. In order
to open a file and associate it with a stream, the fopen() function is used.
● The prototype of fopen() can be given as:
FILE *fopen(const char *file_name, const char *mode);
● Using the above prototype, the file whose pathname is the string pointed to by
file_name is opened in the mode specified using the mode.
● If successful, fopen() returns a pointer-to-structure and if it fails, it returns NULL.
Below table shows the different modes of file.

Solution:
Explain different file opening modes 7 Marks
Scheme [7 = 7 Marks]

(b). Implement structure to read, write and compute average marks of the students.
List the students scoring above and below the average marks for a class of n
students. 8 Marks
Answer:
/* Program to Maintain Student information */
#include<stdio.h>
#include<string.h>
struct student
{
int roll_num, marks;
char name[20];
};
void main()
{
int i, n;
struct student s[10];
int total = 0;
float avg =0.0;
printf("Enter the students n = ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf(" Enter the %d student details\n",i+1);
printf(" Enter the roll number:");
scanf("%d",&s[i].roll_num);
printf(" Enter the student name without spaces:");
scanf("%s",s[i].name);
printf(" Enter the marks:");
scanf("%d",&s[i].marks);

}
printf("\n The student details are \n");
printf("------------------------------------------------\n");
printf(" Roll Num\tName\t\tMarks\n");
printf("------------------------------------------------\n");
for(i=0;i<n;i++)
{
printf("\t%d\t%s\t\t%d\n",s[i].roll_num,s[i].name,s[i].marks);
}
printf("------------------------------------------------\n");
for(i=0;i<n; i++)
{
total = total + s[i].marks;
}
avg = total/n;
printf("Average marks of the class is = %f\n",avg);
printf("\n List of students who have above the average marks\n");
printf("------------------------------------------------\n");
printf(" Roll Num\tName\t\tMarks\n");
printf("------------------------------------------------\n");
for(i=0;i<n;i++)
{
if(s[i].marks >= avg)
{
printf("\t%d\t%s\t\t%d\n",s[i].roll_num,s[i].name,s[i].marks);
}
}
printf("\n List of students who have below the average marks\n");
printf("------------------------------------------------\n");
printf(" Roll Num\tName\t\tMarks\n");
printf("------------------------------------------------\n");
for(i=0;i<n;i++)
{
if(s[i].marks < avg)
{
printf("\t%d\t%s\t\t%d\n",s[i].roll_num,s[i].name,s[i].marks);
}
}
}
Solution:
Develop a C program to display student information 8 Marks
Scheme [8 = 8 Marks]

(c). What are enumeration variable? How are they declared? 5 Marks
Answer:
● The enumerated data type is a user defined type based on the standard integer type.
● An enumeration consists of a set of named integer constants. That is, in an
enumerated type, each integer value is assigned an identifier. This identifier (also known
as an enumeration constant) can be used as symbolic names to make the program more
readable.
● To define enumerated data types, enum keyword is used.
● Enumerations create new data types to contain values that are not limited to the
values fundamental data types may take. The syntax of creating an enumerated data
type can be given as below.
enum enumeration_name { identifier1, identifier2, …..., identifiern };
● Consider the example given below which creates a new type of variable called COLORS
to store colors constants.
● enum COLORS {RED, BLUE, BLACK, GREEN, YELLOW, PURPLE, WHITE};
In case you do not assign any value to a constant, the default value for the first one in
the list - RED (in our case), has the value of 0. The rest of the undefined constants have a
value 1 more than its previous one. So in our example,
● RED = 0, BLUE = 1, BLACK = 2, GREEN = 3, YELLOW = 4, PURPLE = 5, WHITE =6
● If you want to explicitly assign values to these integer constants then you should
specifically mention those values as shown below.
● enum COLORS {RED = 2, BLUE, BLACK = 5, GREEN = 7, YELLOW, PURPLE ,
WHITE = 15};
● As a result of the above statement, now
● RED = 2, BLUE = 3, BLACK = 5, GREEN = 7, YELLOW = 8, PURPLE = 9, WHITE = 15
Solution:
Explain enumeration 5 Marks
Scheme [5 = 5 Marks]
OR
10. (a). Write a short note on functions used to
Read data from a file
Write data to a file.
Answer: 8 Marks
● A file must be first opened before data can be read from it or written to it. In order
to open a file and associate it with a stream, the fopen() function is used.
● The prototype of fopen() can be given as:
FILE *fopen(const char *file_name, const char *mode);
● Using the above prototype, the file whose pathname is the string pointed to by
file_name is opened in the mode specified using the mode.
● If successful, fopen() returns a pointer-to-structure and if it fails, it returns NULL.
● When opening a file in read purpose, file must be open in read mode. (r)
● When opening a file in write purpose, file must be open in write mode. (w)

/* Program to Copy Content from one file to another */


#include <stdio.h>
#include <stdlib.h>
void main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
/* Open one file for reading */
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
printf("Enter the filename to open for writing \n");
scanf("%s", filename);
/* Open another file for writing */
fptr2 = fopen(filename, "w");
if (fptr2 == NULL)
{
printf("Cannot open file %s \n", filename);
exit(0);
}
/* Read contents from file */
c = fgetc(fptr1);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("\nContents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
}
Solution:
Explain read and write file operations with example 8 Marks
Scheme [8 = 8 Marks]

(b). Differentiate structures and unions with syntax and example. 6 Marks
Answer:

● . A structure type is defined by using the given syntax.


struct struct-name
{
data_type var-name;
data_type var-name;
...
};
struct student
{ int r_no;
char name[20];
char course[20];
float fees;
};

The syntax for declaring a union is same as that of declaring a structure.


union union-name
{ data_type var-name;
data_type var-name;
...
};
Solution:
Difference b/w structure and union with syntax 6 Marks
Scheme [6 = 6 Marks]

(c). How to detect END-OF-FILE. 6 Marks


Answer:
In C, there are two ways to detect the end-of-file
While reading the file in text mode, character by character, the programmer can compare
the character that has been read with the EOF, which is a symbolic constant defined in
stdio.h with a value -1.
while(1)
{
c = fgetc(fp); // here c is an int variable
if (c==EOF)
break;
printf("%c", c);
}
The other way is to use the standard library function feof() which is defined in stdio.h.
The feof() is used to distinguish between two cases
 When a stream operation has reached the end of a file
 When the EOF ("end of file") error code has been returned as a generic error
indicator even when the end of the file has not been reached
The prototype of feof() can be given as:
int feof(FILE *fp);
Feof() returns zero (false) when the end of file has not been reached and a one (true) if the
end-of-file has been reached.
while( !feof(fp)
{
fgets(str, 80, fp);
printf("\n %s", str);
}
Solution:
Explain how to detect EOF in C 6 Marks
Scheme [6 = 6 Marks]

You might also like