Professional Documents
Culture Documents
CS 100 QP1 Solved Ktunotes - in
CS 100 QP1 Solved Ktunotes - in
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.
S . I N
T U N OTE
K
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.
E S .a
I N continue statement
it terminates the block and gets the encountered, it gets the control to the
is
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.
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
printf("Sum = %.2lf",sum);
E S . I N
}
return 0;
KTU NOT
Output
where control string refers to a string containing certain required formatting information, and
arg1,arg2,….,argN are arguments that represent the individual data items.
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.
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.
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
5.
Nested for loop
A for loop inside another for loop is called nested for loop.
Syntax of Nested for loop
}
... ... ...
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;
}
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
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.
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;
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.
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);
OUTPUT OUTPUT
====== ======
n1: 10, n2: 20 n1: 20, n2: 10
10
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.
E S . I N (increments and
NOT
decrements) the control
variable.
Infinite Repetition Infinite recursion can crash Infinite loop uses CPU
the system. cycles repeatedly.
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.
binary file-
1. extension is .doc
13.
a)strlen()
strlen() function returns the length of the string. strlen() function returns integer
value.
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);
Output:
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);
Output:
0
f)strncmp()
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);
Output:
0
h) strncmpi()
strncmpi() is used to compare only left most ‘n’ characters from the strings.
strncmpi() function does a case insensitive comparison.
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() {
or
KTU
int main(int argc, char** argv)
{
cout << "You have entered " << argc
<< " arguments:" << "\n";
return 0;
}
Input:
Output:
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
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.
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;
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.
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.
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.
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
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: ");
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()
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();
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
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++) {
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;
}
#include <stdio.h>
int main()
{
int array[100], search, c, 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
E S . I N
NOT
int number;
KTU
printf("Enter an integer: ");
scanf("%d", &number);
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
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]");
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:
E S . I N
KTU NOT