You are on page 1of 38

MODEL QUESTION PAPER

COLLEGE OF ENGINEERING , ARANMULA


SIXTH SEMESTER B.TECH DEGREE EXAMINATION, MARCH 2018
Course Code: CS100
Course Name: COMPUTER PROGRAMMING
Max. Marks: 100 Duration: 3 Hours

PART A
Answer all questions
1 Give the use of break and continue with an example? (3)
2 What are the basic input and output functions used in C? (2)
3 What is difference between while and do-while loops? (3)
4 What is keyword? State two keywords of C? (2)
5 Explain nested for loop statement with suitable example? (2)
6 What is function prototype? Give one example of function prototype? (3)
7 Explain union with an example and state the uses of union? (3)
8 Give the meaning of declaration :int *ptr; (2)
9 Differentiate between call by value and call by reference. (3)
10 Explain about Actual and Formal parameters? (2)
11 What is recursion? Differentiate between recursion with iteration. (3)
12 What is the difference between text and binary file? (3)
13 State any four string handling functions? (2)
14 What is typecasting in C? (2)
15 Explain about command line arguments? (2)
16 What is the use of fseek( ) function in files. Write its syntax? (2)

.
PART B
S I N
OTE
Answer any 4 full questions, each carries 8 marks.
17

18 T U N
a) Write a C program to test whether a given number is Armstrong or not?
b) What is Preprocessors ? define some Preprocessors in c?
K
a) Explain about different storage classes with examples. Discuss their uses and
(5)
(3)
(3)
scope.
b) Write a recursive function for finding the factorial value of a given number. (5)
19 a) Write the procedure for swapping two strings using pointers. (5)
b) How can a pointer be used to access individual elements of an array? (3)
Explain with an example.
20 a) Write the procedure for swapping two strings using pointers. Write a program (6)
to print the following series on the screen
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
b) Write short note on relational operators in c? (2)
21 Write a function to multiply two matrices of order ‘mxn’ and ‘nxl’ and write (8)
the main program to input array values and output resultant matrix ?
PART C
Answer any two full questions, each carries 14 marks..
22 a) Write a C program to compare two strings without using any standard library (6)
function.
b) Write a C program to read name and marks of n number of students from user (8)
and store them in a file. If the file previously exits, add the information of n
students.

Downloaded from Ktunotes.in


23 a) Write a C program to search an element from a list of integers using linear (11)
search method?
b) What is an address operator? (3)
24 a) C Program to Implement Selection Sort Recursively? (10)
b) Explain if, else-if and switch statements with suitable examples. (4)

S . I N
T U N OTE
K

Downloaded from Ktunotes.in


Answer Key
PART A
1.

Break Continue

A break can appear in both switch and A continue can appear only in loop (for,
loop (for, while, do) statements. while, do) statements.

A break causes the switch or loop A continue doesn't terminate the loop, it
statements to terminate the moment it causes the loop to go to the next
is executed. Loop or switch ends iteration. All iterations of the loop are
abruptly when break is encountered. executed even if continue is
encountered. The continue statement is
used to skip statements in the loop that
appear after the continue

The break statement can be used in both The continue statement can appear only
switch and loop statements. in loops. You will get an error if this
appears in switch statement.

When a break statement is encountered, When

E S .a
I N continue statement
it terminates the block and gets the encountered, it gets the control to the
is

control out of the switch or loop.

KTU NOT
next iteration of the loop.

A break causes the innermost enclosing A continue inside a loop nested within a
loop or switch to be exited immediately. switch causes the next loop iteration.

Eg,Pgm for Continue


#include <stdio.h>

int main()
{
int a[10] = {-1, 2, -3, 4, -5, 6, -7, 8, -9, 10};
int i, sum = 0;
for (i = 0; i < 10; i++)
{
if (a[i] < 0) /* skip negative elements */
continue;
sum += a[i]; /* sum positive elements */
}
printf("Sum of positive elements: %d\n", sum);
}

OUTPUT

Downloaded from Ktunotes.in


======
Sum of positive elements: 30

Eg.pgm for break


int main()
{
int i;
double number, sum = 0.0;

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


{
printf("Enter a n%d: ",i);
scanf("%lf",&number);

// If user enters negative number, loop is terminated


if(number < 0.0)
{
break;
}

sum += number; // sum = sum + number;


}

printf("Sum = %.2lf",sum);
E S . I N
}
return 0;
KTU NOT
Output

Enter a n1: 2.4


Enter a n2: 4.5
Enter a n3: 3.4
Enter a n4: -3
Sum = 10.30

2. scanf() and printf() functions


functions printf() and scanf(), which are used to display output on screen and to take
input from user respectively.In general terms, the scanf function is written as:

scanf(control string, arg1, arg2,.........,argN)

where control string refers to a string containing certain required formatting information, and
arg1,arg2,….,argN are arguments that represent the individual data items.

getchar() & putchar() functions


The getchar() function reads a character from the terminal and returns it as an integer. This
function reads only single character at a time. You can use this method in a loop in case you want

Downloaded from Ktunotes.in


to read more than one character. The putchar() function displays the character passed to it on the
screen and returns the same character. This function too displays only a single character at a
time. In case you want to display more than one characters, use putchar() method in a loop.

gets() & puts() functions

The gets() function reads a line from stdin(standard input) into the buffer pointed to by str
pointer, until either a terminating newline or EOF (end of file) occurs. The puts() function writes
the string str and a trailing newline to stdout.

3.

Basis for comparison while do-while

General Form while ( condition) { do{


statements; //body of loop .
} statements; // body of
loop.
.

E S . I N } while( Condition );

NOT
Controlling Condition In 'while' loop the In 'do-while' loop the

KTU
controlling condition controlling condition
appears at the start of the appears at the end of the
loop. loop.

Iterations The iterations do not occur The iteration occurs at


if, the condition at the first least once even if the
iteration, appears false. condition is false at the
first iteration.

Example pgm while(wdlen<2){ do {


printf("Word length... printf("Word length...
"); ");
scanf("%d", &wdlen); scanf("%d", &wdlen);
} } while(wdlen<2);

4.Keywords are predefined, reserved words used in programming that have special meanings to
the compiler. Keywords are part of the syntax and they cannot be used as an identifier.
Keywords in C Language
auto double int struct

Downloaded from Ktunotes.in


break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned

5.
Nested for loop

A for loop inside another for loop is called nested for loop.
Syntax of Nested for loop

for (initialization; condition; increment/decrement)


{
statement(s);
for (initialization; condition; increment/decrement)
{
statement(s);
... ... ...
}

}
... ... ...

E S . I N
#include<stdio.h>
KTU NOT
C program to print all the composite numbers from 2 to a certain number entered by user.

#include<math.h>
int main()
{
int i,j,n;
printf("Enter a number:");
scanf("%d",&n);
for(i=2;i<=n;i++)
{
for(j=2;j<=(int)pow(i,0.5);j++)
{
if(i%j==0)
{
printf("%d is composite\n",i);
break;
}
}
}
return 0;
}

Downloaded from Ktunotes.in


Output

Enter a number:15
4 is composite
6 is composite
8 is composite
9 is composite
10 is composite
12 is composite
14 is composite
15 is composite

6.
In C++ all functions must be declared before they are used. This is accomplished usingfunction
prototype. Prototypes enable complier to provide stronger type checking. When prototype is
used, the compiler can find and report any illegal type conversions betweenthe type of arguments
used to call a function and the type definition of its parameters. Itcan also find the difference
between the no of arguments used to call a function and thenumber of parameters in the function.
Thus function prototypes help us trap bugs beforethey occur. In addition, they help verify that
your program is working correctly by notallowing functions to be called with mismatched
arguments.

E S . I N
NOT
A general function prototype looks like following:return_type func_name(type
param_name1, type param_name2, …,type param_nameN);The type indicates data type.

KTU
Parameter names are optional in prototype
Following program illustrates the value of function parameters

void sqr_it(int *i); //prototype of function


sqr_itint main()
{
int num;num = 10;
sqr_it(num); //type mismatchreturn 0;
}
void sqr_it(int *i)
{
*i = *i * *i;
}
Since sqr_it() has pointer to integer as its parameter, the program throws an error whenwe pass
an integer to it.

7.
C Union is also like structure, i.e. collection of different data types which are grouped together.
Each element in a union is called member.

Union and structure in C are same in concepts, except allocating memory for their members.

Downloaded from Ktunotes.in


Structure allocates storage space for all its members separately.
Whereas, Union allocates one common storage space for all its members

We can access only one member of union at a time. We can’t access all member values at the
same time in union. But, structure can access all member values at the same time. This is
because, Union allocates one common storage space for all its members. Where as Structure
allocates storage space for all its members separately.
Many union variables can be created in a program and memory will be allocated for each
union variable separately.
Syntax:
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example:
union student
{
int mark;
char name[10];
float average;
};
E S . I N
NOT
#include <stdio.h>

KTU
#include <string.h>

union student
{
char name[20];
char subject[20];
float percentage;
};

int main()
{
union student record1;
union student record2;

// assigning values to record1 union variable


strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;

printf("Union record1 values example\n");


printf(" Name : %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);

Downloaded from Ktunotes.in


printf(" Percentage : %f \n\n", record1.percentage);

// assigning values to record2 union variable


printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name : %s \n", record2.name);

strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);

record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
}

Output:
Union record1 values example
Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000
E S . I N
KTU NOT
8.A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location. Like any variable or constant, you must declare a pointer before using it to
store any variable address. The general form of a pointer variable declaration is −

type *var-name;
Here, type is the pointer's base type; it must be a valid C data type and var-name is the name of
the pointer variable.the asterisk is being used to designate a variable as a pointer.
So 'ptr' is apointer of type integer
9.

call by value call by reference

In call by value, a copy of actual In call by reference, the location


arguments is passed to formal (address) of actual arguments is passed
arguments of the called function and any to formal arguments of the called
change made to the formal arguments in function. This means by accessing the
the called function have no effect on the addresses of actual arguments we can
values of actual arguments in the calling alter them within from the called
function. function.

In call by value, actual arguments will In call by reference, alteration to actual

Downloaded from Ktunotes.in


remain safe, they cannot be modified arguments is possible within from called
accidentally. function; therefore the code must handle
arguments carefully else you get
unexpected results.

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

void swapByValue(int, int); /* Prototype void swapByReference(int*, int*); /*


*/ Prototype */

int main() /* Main function */ int main() /* Main function */


{ {
int n1 = 10, n2 = 20; int n1 = 10, n2 = 20;

/* actual arguments will be as it is */

E S . I N
/* actual arguments will be altered */

NOT
swapByValue(n1, n2); swapByReference(&n1, &n2);

} KTU
printf("n1: %d, n2: %d\n", n1, n2);
}
printf("n1: %d, n2: %d\n", n1, n2);

void swapByValue(int a, int b) void swapByReference(int *a, int *b)


{ {
int t; int t;
t = a; a = b; b = t; t = *a; *a = *b; *b = t;
} }

OUTPUT OUTPUT
====== ======
n1: 10, n2: 20 n1: 20, n2: 10

10

Downloaded from Ktunotes.in


formal parameter — the identifier used in a method to stand for the value that is passed into
the method by a caller.

actual parameter — the actual value that is passed into the method by a caller.

11.
A recursive procedure or routine is one that has the ability to call itself. A recursive expression is
a function, algorithm, or sequence of instructions (typically, an IF, THEN, ELSE sequence) that
loops back to the beginning of itself until it detects that some condition has been satisfied.

Basis For Comparison Recursion Iteration

Basic The statement in a body of Allows the set of


function calls the function instructions to be
itself. repeatedly executed.

Format In recursive function, only Iteration includes


termination condition initialization, condition,
(base case) is specified. execution of statement
within loop and update

E S . I N (increments and

NOT
decrements) the control
variable.

Termination KTU A conditional statement is


included in the body of the
The iteration statement is
repeatedly executed until
function to force the a certain condition is
function to return without reached.
recursion call being
executed.

Condition If the function does not If the control condition in


converge to some the iteration statement
condition called (base never become false, it
case), it leads to infinite leads to infinite iteration.
recursion.

Infinite Repetition Infinite recursion can crash Infinite loop uses CPU
the system. cycles repeatedly.

Applied Recursion is always Iteration is applied to


applied to functions. iteration statements or
"loops".

Downloaded from Ktunotes.in


Stack The stack is used to store Does not uses stack.
the set of new local
variables and parameters
each time the function is
called.

Overhead Recursion possesses the No overhead of repeated


overhead of repeated function call.
function calls.

Speed Slow in execution. Fast in execution.

Size of Code Recursion reduces the size Iteration makes the code
of the code. longer

12.

text file-

1. extension is .txt

. I
2. data is in the form of alphabets and numerals

E S N
KTU
4. human readable files.
NOT
3. accessing time is more as compared to binary files.

5. consume more space in memory than binary files.

binary file-

1. extension is .doc

2. data is in the form of 0 and 1.

3. accessing time is less as compared to text files.

4. human unreadable files.

5. consume less space in memory than text files.

13.

a)strlen()
strlen() function returns the length of the string. strlen() function returns integer
value.

Downloaded from Ktunotes.in


Example:
char *str = "Learn C Online";
int strLength;
strLength = strlen(str); //strLength contains the length of the string i.e. 14

char *str = "Learn C Online";


int strLength;
strLength = strlen(str); //strLength contains the length of the string i.e. 14
b) strcpy()
strcpy() function is used to copy one string to another. The Destination_String
should be a variable and Source_String can either be a string constant or a variable.
Syntax:
strcpy(Destination_String,Source_String);
Example:
char *Destination_String;
char *Source_String = "Learn C Online";
strcpy(Destination_String,Source_String);
printf("%s", Destination_String);

char *Destination_String;
char *Source_String = "Learn C Online";
strcpy(Destination_String,Source_String);
printf("%s", Destination_String);

Output:
E S . I N
NOT
Learn C Online

KTU
c) strncpy()
strncpy() is used to copy only the left most n characters from source to
destination. The Destination_String should be a variable and Source_String can
either be a string constant or a variable.
Syntax:
strncpy(Destination_String, Source_String,no_of_characters);
d) strcat()
strcat() is used to concatenate two strings.
The Destination_String should be a variable and Source_String can either be a
string constant or a variable.
Syntax:
strcat(Destination_String, Source_String);
Example:
char *Destination_String ="Learn ";
char *Source_String = "C Online";
strcat(Destination_String, Source_String);
puts( Destination_String);

char *Destination_String ="Learn ";


char *Source_String = "C Online";
strcat(Destination_String, Source_String);
puts( Destination_String);

Output:

Downloaded from Ktunotes.in


Learn C Online
d) strncat()
strncat() is used to concatenate only the leftmost n characters from source with
the destination string.
The Destination_String should be a variable and Source_String can either be a
string constant or a variable.
Syntax:
strncat(Destination_String, Source_String,no_of_characters);
Example:
char *Destination_String="Visit ";
char *Source_String = "Learn C Online is a great site";
strncat(Destination_String, Source_String,14);
puts( Destination_String);

char *Destination_String="Visit ";


char *Source_String = "Learn C Online is a great site";
strncat(Destination_String, Source_String,14);
puts( Destination_String);

Output:
Visit Learn C Online
e) strcmp()
strcmp() function is use two compare two strings. strcmp() function does a case

. I N
sensitive comparison between two strings. The Destination_String and

E S
Source_String can either be a string constant or a variable.
Syntax:

KTU
int strcmp(string1, string2);
NOT
This function returns integer value after comparison.
Value returned is 0 if two strings are equal.
If the first string is alphabetically greater than the second string then, it returns a
positive value.
If the first string is alphabetically less than the second string then, it returns a
negative value
Example:
char *string1 = "Learn C Online";
char *string2 = "Learn C Online";
int ret;
ret=strcmp(string1, string2);
printf("%d",ret);

char *string1 = "Learn C Online";


char *string2 = "Learn C Online";
int ret;
ret=strcmp(string1, string2);
printf("%d",ret);

Output:
0
f)strncmp()

Downloaded from Ktunotes.in


strncmp() is used to compare only left most ‘n’ characters from the strings.
Syntax:
int strncmp(string1, string2,no_of_chars);
This function returns integer value after comparison.
Value returned is 0 if left most ‘n’ characters of two strings are equal.
If the left most ‘n’ characters of first string is alphabetically greater than the left
most ‘n’ characters of second string then, it returns a positive value.
If the left most ‘n’ characters of first string is alphabetically less than the left
most ‘n’ characters of second string then, it returns a negative value
Example:
char *string1 = "Learn C Online is a great site";
char *string2 = "Learn C Online";
int ret;
ret=strncmp(string1, string2,7);
printf("%d",ret);

char *string1 = "Learn C Online is a great site";


char *string2 = "Learn C Online";
int ret;
ret=strncmp(string1, string2,7);
printf("%d",ret);

Output:
0
g) strcmpi()
E S . I N
NOT
strcmpi() function is use two compare two strings. strcmp() function does a case

KTU
insensitive comparison between two strings. The Destination_String and
Source_String can either be a string constant or a variable.
Syntax:
int strcmpi(string1, string2);
This function returns integer value after comparison.
Example:
char *string1 = “Learn C Online”;
char *string2 = “LEARN C ONLINE”;
int ret;
ret=strcmpi(string1, string2);
printf("%d",ret);

char *string1 = “Learn C Online”;


char *string2 = “LEARN C ONLINE”;
int ret;
ret=strcmpi(string1, string2);
printf("%d",ret);

Output:
0
h) strncmpi()
strncmpi() is used to compare only left most ‘n’ characters from the strings.
strncmpi() function does a case insensitive comparison.

Downloaded from Ktunotes.in


Syntax:
int strncmpi(string1, string2,no_of_chars);
This function returns integer value after comparison.
Example:
char *string1 = "Learn C Online is a great site";
char *string2 = "LEARN C ONLINE";
int ret;
ret=strncmpi(string1, string2,7);
printf("%d",ret);

char *string1 = "Learn C Online is a great site";


char *string2 = "LEARN C ONLINE";
int ret;
ret=strncmpi(string1, string2,7);
printf("%d",ret);

Output:
0

14.
Type casting is a way to convert a variable from one data type to another data type.
For example, if you want to store a 'long' value into a simple integer then you can
type cast 'long' to 'int'. You can convert the values from one type to another

. I N
explicitly using the cast operator as follows −

E S
NOT
(type_name) expression

KTU
Consider the following example where the cast operator causes the division of one
integer variable by another to be performed as a floating-point operation −
#include <stdio.h>

main() {

int sum = 17, count = 5;


double mean;

mean = (double) sum / count;


printf("Value of mean : %f\n", mean );
}
When the above code is compiled and executed, it produces the following result −

Value of mean : 3.400000


15.
The most important function of C is main() function. It is mostly defined with a
return type of int and without parameters :

int main() { /* ... */ }

Downloaded from Ktunotes.in


Command-line arguments are given after the name of the program in command-line
shell of Operating Systems.
To pass command line arguments, we typically define main() with two arguments :
first argument is the number of command line arguments and second is list of
command-line arguments.

int main(int argc, char *argv[]) { /* ... */ }

or

int main(int argc, char **argv[]) { /* ... */ }

argc (ARGument Count) is int and stores number of command-line arguments


passed by the user including the name of the program. So if we pass a value to a
program, value of argc would be 2 (one for argument and one for program name)
The value of argc should be non negative.
argv(ARGument Vector) is array of character pointers listing all the arguments.
If argc is greater than zero,the array elements from argv[0] to argv[argc-1] will
contain pointers to strings.
Argv[0] is the name of the program , After that till argv[argc-1] every element is
command -line arguments.

For better understanding run this code on your linux machine.


// Name of program mainreturn.cpp
E S . I N
NOT
#include <iostream>
using namespace std;

KTU
int main(int argc, char** argv)
{
cout << "You have entered " << argc
<< " arguments:" << "\n";

for (int i = 0; i < argc; ++i)


cout << argv[i] << "\n";

return 0;
}

Input:

$ g++ mainreturn.cpp -o main


$ ./main geeks for geeks

Output:

You have entered 4 arguments:


./main
geeks
for

Downloaded from Ktunotes.in


geeks

Properties of Command Line Arguments:

• They are passed to main() function.


• They are parameters/arguments supplied to the program when it is
invoked.
• They are used to control program from outside instead of hard coding
those values inside the code.
• argv[argc] is a NULL pointer.
• argv[0] holds the name of the program.
• argv[1] points to the first command line argument and argv[n] points last
argument.

16.
Description

The C library function int fseek(FILE *stream, long int offset, int whence) sets the file
position of the stream to the given offset.
Declaration

Following is the declaration for fseek() function.

S . I N
int fseek(FILE *stream, long int offset, int whence)

E
Parameters

KTU NOT
stream − This is the pointer to a FILE object that identifies the stream.

offset − This is the number of bytes to offset from whence.

whence − This is the position from where offset is added. It is specified by one of
the following constants −
1. SEEK_SET-Beginning of file
2. SEEK_CUR-Current position of the file pointer
3. SEEK_END-End of file

PART B

17.a)
#include <stdio.h>
#include <math.h>
void main()
{
int number, sum = 0, rem = 0, cube = 0, temp;

Downloaded from Ktunotes.in


printf ("enter a number");
scanf("%d", &number);
temp = number;
while (number != 0)
{
rem = number % 10;
cube = pow(rem, 3);
sum = sum + cube;
number = number / 10;
}
if (sum == temp)
printf ("The given no is armstrong no");
else
printf ("The given no is not a armstrong no");
}

E S . I N
Output:

KTU NOT
enter a number370
The given no is armstrong no

enter a number1500
The given no is not a armstrong no
b)
The C Preprocessor is not a part of the compiler, but is a separate step in the
compilation process. In simple terms, a C Preprocessor is just a text substitution tool
and it instructs the compiler to do required pre-processing before the actual
compilation.
All preprocessor commands begin with a hash symbol (#).
The following section lists down all the important preprocessor directives −
1 .#define-Substitutes a preprocessor macro.
2 .#include-Inserts a particular header from another file.

Downloaded from Ktunotes.in


3 .#undef-Undefines a preprocessor macro.
4 .#ifdef-Returns true if this macro is defined.
5 .#ifndef-Returns true if this macro is not defined.
6 .#if-Tests if a compile time condition is true.
7 .#else-The alternative for #if.
8 .#elif,#else and #if in one statement.
9 .#endif-Ends preprocessor conditional.
10 .#error-Prints error message on stderr.
11 .#pragma-Issues special commands to the compiler, using a standardized
method.
Preprocessors Examples
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the C to replace instances of MAX_ARRAY_LENGTH with 20. Use
#define for constants to increase readability.
#include <stdio.h>

E S . I N
NOT
#include "myheader.h"

KTU
These directives tell the Compiler to get stdio.h from System Libraries and add the
text to the current source file. The next line tells CPP to get myheader.h from the
local directory and add the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42
It tells the Compiler to undefine existing FILE_SIZE and define it as 42.
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
It tells the Compiler to define MESSAGE only if MESSAGE isn't already defined.
#ifdef DEBUG
/* Your debugging statements here */
#endif
It tells the Compiler to process the statements enclosed if DEBUG is defined. This is
useful if you pass the -DDEBUG flag to the gcc compiler at the time of compilation.
This will define DEBUG, so you can turn debugging on and off on the fly during
compilation.

Downloaded from Ktunotes.in


18.a)
A storage class defines the scope (visibility) and life-time of variables and/or
functions within a C Program. They precede the type that they modify. We have four
different storage classes in a C program −
auto
register
static
extern
The auto Storage Class
The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}

S . N
The example above defines two variables with in the same storage class. 'auto' can
I
only be used within functions, i.e., local variables.
E
The register Storage Class

KTU NOT
The register storage class is used to define local variables that should be stored in a
register instead of RAM. This means that the variable has a maximum size equal to
the register size (usually one word) and can't have the unary '&' operator applied to
it (as it does not have a memory location).
{
register int miles;
}
The register should only be used for variables that require quick access such as
counters. It should also be noted that defining 'register' does not mean that the
variable will be stored in a register. It means that it MIGHT be stored in a register
depending on hardware and implementation restrictions.
The static Storage Class
The static storage class instructs the compiler to keep a local variable in existence
during the life-time of the program instead of creating and destroying it each time it
comes into and goes out of scope. Therefore, making local variables static allows
them to maintain their values between function calls.

Downloaded from Ktunotes.in


The static modifier may also be applied to global variables. When this is
done, it causes that variable's scope to be restricted to the file in which it is
declared.

In C programming, when static is used on a global variable, it causes only one copy
of that member to be shared by all the objects of its class.
#include <stdio.h>
/* function declaration */
void func(void);
static int count = 5; /* global variable */
main() {
while(count--) {
func();
}
return 0;
}
/* function definition */
E S . I N
void func( void ) {

KTU NOT
static int i = 5; /* local static variable */
i++;
printf("i is %d and count is %d\n", i, count);
}
When the above code is compiled and executed, it produces the following result −

i is 6 and count is 4
i is 7 and count is 3
i is 8 and count is 2
i is 9 and count is 1
i is 10 and count is 0
The extern Storage Class
The extern storage class is used to give a reference of a global variable that is
visible to ALL the program files. When you use 'extern', the variable cannot be

Downloaded from Ktunotes.in


initialized however, it points the variable name at a storage location that has been
previously defined.

When you have multiple files and you define a global variable or function, which will
also be used in other files, then extern will be used in another file to provide the
reference of defined variable or function. Just for understanding, extern is used to
declare a global variable or function in another file.
The extern modifier is most commonly used when there are two or more files
sharing the same global variables or functions as explained below.
First File: main.c
#include <stdio.h>
int count ;
extern void write_extern();
main() {
count = 5;
write_extern();
}
Second File: support.c
E S . I N
#include <stdio.h>
extern int count;
KTU NOT
void write_extern(void) {
printf("count is %d\n", count);
}
Here, extern is being used to declare count in the second file, where as it has its
definition in the first file, main.c.
b)
#include <stdio.h>
long int multiplyNumbers(int n);

int main()
{
int n;
printf("Enter a positive integer: ");

Downloaded from Ktunotes.in


scanf("%d", &n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n)
{
if (n >= 1)
return n*multiplyNumbers(n-1);
else
return 1;
}
Output

Enter a positive integer: 6


Factorial of 6 = 720

E S . I N
19.a)

KTU NOT
Let us see the correct ways for swapping strings:
Method 1(Swap Pointers)
If you are using character pointer for strings (not arrays) then change str1 and str2
to point each other’s data. i.e., swap pointers. In a function, if we want to change a
pointer (and obviously we want changes to be reflected outside the function) then
we need to pass a pointer to the pointer.
#include<stdio.h>
/* Swaps strings by swapping pointers */
void swap1(char **str1_ptr, char **str2_ptr)
{
char *temp = *str1_ptr;
*str1_ptr = *str2_ptr;
*str2_ptr = temp;
}
int main()

Downloaded from Ktunotes.in


{
char *str1 = "geeks";
char *str2 = "forgeeks";
swap1(&str1, &str2);
printf("str1 is %s, str2 is %s", str1, str2);
getchar();
return 0;
}
This method cannot be applied if strings are stored using character arrays.
Method 2(Swap Data)
If you are using character arrays to store strings then preferred way is to swap the
data of both arrays.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
/* Swaps strings by swapping data*/

E S . I N
NOT
void swap2(char *str1, char *str2)
{
KTU
char *temp = (char *)malloc((strlen(str1) + 1) * sizeof(char));
strcpy(temp, str1);
strcpy(str1, str2);
strcpy(str2, temp);
free(temp);
}
int main()
{
char str1[10] = "geeks";
char str2[10] = "forgeeks";
swap2(str1, str2);
printf("str1 is %s, str2 is %s", str1, str2);
getchar();

Downloaded from Ktunotes.in


return 0;
}
This method cannot be applied for strings stored in read only block of memory.

b) A variable declared as an array of some type acts as a pointer to that type.


When used by itself, it points to the first element of the array.
A pointer can be indexed like an array name.
#include <stdio.h>
int main()
{
int data[5], i;
printf("Enter elements: ");
for(i = 0; i < 5; ++i)
scanf("%d", data + i);
printf("You entered: \n");
for(i = 0; i < 5; ++i)

E S . I N
NOT
printf("%d\n", *(data + i));

}
return 0;
KTU
Output
Enter elements: 1
2
3
5
4
You entered:
1
2
3
5
4

Downloaded from Ktunotes.in


20.a)
include<stdio.h>
int main(){
int i, j, n;
printf("Enter the number of lines required: ");
scanf("%d", &n);
for(i=1;i<=n;i++){
for(j=1;j<=i;j++){
printf("%d\t", j);
}
printf("\n");
}
return 0;
}
Sample Input
E S . I N
Enter the number of lines required: 5
Sample Output
KTU NOT
1
12
123
1234
12345
b)
A header file is a file with extension .h which contains C function declarations and
macro definitions to be shared between several source files. There are two types of
header files: the files that the programmer writes and the files that comes with your
compiler.
Relational operators are used for comparison of two values. Let’s see them one by
one:
• ‘==’ operator checks whether the two given operands are equal or not. If
so, it returns true. Otherwise it returns false. For example, 5==5 will return
true.

Downloaded from Ktunotes.in


• ‘!=’ operator checks whether the two given operands are equal or not. If
not, it returns true. Otherwise it returns false. It is the exact boolean
complement of the ‘==’ operator. For example, 5!=5 will return false.
• ‘>’ operator checks whether the first operand is greater than the second
operand. If so, it returns true. Otherwise it returns false. For example, 6>5
will return true.
• ‘<‘ operator checks whether the first operand is lesser than the second
operand. If so, it returns true. Otherwise it returns false. For example, 6<5
will return false.
• ‘>=’ operator checks whether the first operand is greater than or equal
to the second operand. If so, it returns true. Otherwise it returns false. For
example, 5>=5 will return true.
• ‘<=’ operator checks whether the first operand is lesser than or equal to
the second operand. If so, it returns true. Otherwise it returns false. For
example, 5<=5 will also return true.
21.
#include <stdio.h>
int main()
{

E S . I N
NOT
int m, n, p, q, c, d, k, sum = 0;

KTU
int first[10][10], second[10][10], multiply[10][10];
printf("Enter number of rows and columns of first matrix\n");
scanf("%d%d", &m, &n);
printf("Enter elements of first matrix\n");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
scanf("%d", &first[c][d]);
printf("Enter number of rows and columns of second matrix\n");
scanf("%d%d", &n, &l);
printf("Enter elements of second matrix\n");
for (c = 0; c < n; c++)
for (d = 0; d < l; d++)
scanf("%d", &second[c][d]);
for (c = 0; c < m; c++) {
for (d = 0; d < l; d++) {

Downloaded from Ktunotes.in


for (k = 0; k < n; k++) {
sum = sum + first[c][k]*second[k][d];
}
multiply[c][d] = sum;
sum = 0;
}
}
printf("Product of the matrices:\n");

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


for (d = 0; d < l; d++)
printf("%d\t", multiply[c][d]);
printf("\n");
}
}
return 0;
E S . I N
}
22.a)
KTU NOT
#include<stdio.h>
int main() {
char str1[30], str2[30];
int i;
printf("\nEnter two strings :");
gets(str1);
gets(str2);
i = 0;
while (str1[i] == str2[i] && str1[i] != '\0')
i++;
if (str1[i] > str2[i])
printf("str1 > str2");
else if (str1[i] < str2[i])

Downloaded from Ktunotes.in


printf("str1 < str2");
else
printf("str1 = str2");
return (0);
}
b)
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
printf("Enter number of students: ");
scanf("%d", &num);
FILE *fptr;
fptr = (fopen("C:\\student.txt", "a"));
if(fptr == NULL)
E S . I N
{

KTU
printf("Error!");
NOT
exit(1);
}
for(i = 0; i < num; ++i)
{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);
printf("Enter marks: ");
scanf("%d", &marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);
}
fclose(fptr);
return 0;
}

Downloaded from Ktunotes.in


23.a)

#include <stdio.h>

int main()
{
int array[100], search, c, n;

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


scanf("%d",&n);

printf("Enter %d integer(s)\n", n);

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


scanf("%d", &array[c]);
E S . I N
KTU NOT
printf("Enter the number to search\n");
scanf("%d", &search);

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


{
if (array[c] == search) /* if required element found */
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d is not present in array.\n", search);

Downloaded from Ktunotes.in


return 0;
}
b)
An address-of operator is a mechanism within C++ that returns the memory
address of a variable. These addresses returned by the address-of operator are
known as pointers, because they "point" to the variable in memory.
The address-of operator is a unary operator represented by an ampersand (&). It is
also known as an address operator.
Address operators commonly serve two purposes:
1. To conduct parameter passing by reference, such as by name
2. To establish pointer values. Address-of operators point to the location in the
memory because the value of the pointer is the memory address/location
where the data item resides in memory.
24.a)
void selection(int [], int, int, int, int);
int main()
{
int list[30], size, temp, i, j;
E S . I N
KTU
scanf("%d", &size);
NOT
printf("Enter the size of the list: ");

printf("Enter the elements in list:\n");


for (i = 0; i < size; i++)
{
scanf("%d", &list[i]);
}
selection(list, 0, 0, size, 1);
printf("The sorted list in ascending order is\n");
for (i = 0; i < size; i++)
{
printf("%d ", list[i]);
}
return 0;
}

Downloaded from Ktunotes.in


void selection(int list[], int i, int j, int size, int flag)
{
int temp;
if (i < size - 1)
{
if (flag)
{
j = i + 1;
}
if (j < size)
{
if (list[i] > list[j])
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
E S . I N
}

KTU
selection(list, i, j + 1, size, 0);
NOT
}
selection(list, i + 1, 0, size, 1);
}
}

Output
Enter the size of the list: 5
Enter the elements in list:
23
45
64
12
34

Downloaded from Ktunotes.in


The sorted list in ascending order is
12 23 34 45 64
b)
if statement
if (testExpression)
{
// statements
}
The if statement evaluates the test expression inside the parenthesis.
If the test expression is evaluated to true (nonzero), statements inside the body of if
is executed.
If the test expression is evaluated to false (0), statements inside the body of if is
skipped from execution.
#include <stdio.h>
int main()
{

E S . I N
NOT
int number;

KTU
printf("Enter an integer: ");
scanf("%d", &number);

// Test expression is true if number is less than 0


if (number < 0)
{
printf("You entered %d.\n", number);
}
printf("The if statement is easy.");
return 0;
}
Output
Enter an integer: -2
You entered -2.

Downloaded from Ktunotes.in


The if statement is easy.

if...else statement
The if...else statement executes some code if the test expression is true (nonzero)
and some other code if the test expression is false (0).
Syntax of if...else
if (testExpression) {
// codes inside the body of if
}
else {
// codes inside the body of else
}
If test expression is true, codes inside the body of if statement is executed and,
codes inside the body of else statement is skipped.
If test expression is false, codes inside the body of else statement is executed and,
codes inside the body of if statement is skipped.
#include <stdio.h>
E S . I N
int main()
{
KTU NOT
int number;
printf("Enter an integer: ");
scanf("%d",&number);

// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output
Enter an integer: 7

Downloaded from Ktunotes.in


7 is an odd integer

Switch case conditions


Switch case is clean alternative of ‘if-else-if’ condition. Here, several conditions are
given in cases that facilitates user to select case as per input entered. Basic syntax
for using switch case statement is given below.
switch(expression) {
case constant expression1:
statements1; break;
case constant expression2:
statements1; break;
..
..
default : statementsN;
}
#include <stdio.h>

E S . I N
NOT
int main(int argc, char *argv[]) {

KTU
char ch;
int num1, num2;

printf("\nBasic operation:");
printf("\nAdd [a]");
printf("\nSubtract [s]");
printf("\nMultiply [m]");
printf("\nDivide [d]");

printf("\nEnter character for operation:");


scanf("%c", &ch);

printf("\nEnter two numbers for operation:");


printf("\nEnter num1=");
scanf("%d", &num1);

Downloaded from Ktunotes.in


printf("\nEnter num2=");
scanf("%d", &num2);

switch (ch) {
case 'a':
printf("\nAddition of num1 and num2=%d", (num1+num2));
break;

case 's':
printf("\nSubtraction of num1 and num2=%d", (num1-num2));
break;

case 'm':
printf("\nMultiplication of num1 and num2=%d", (num1*num2));
break;
case 'd':
E S . I N
break;
KTU NOT
printf("\nDivision of num1 and num2=%d", (num1/num2));

case 'x':
printf ("\nTest switch case1");
case 'y':
printf ("\nTest switch case2");
default:
printf("\nInvalid value eneterd");
break;
}
printf("\n");
return 0;
}
Output
Basic operation:

Downloaded from Ktunotes.in


Add [a]
Subtract [s]
Multiply [m]
Divide [d]
Enter character for operation:a
Enter two numbers for operation:
Enter num1=10
Enter num2=5
Addition of num1 and num2=15

E S . I N
KTU NOT

Downloaded from Ktunotes.in

You might also like