DOC-20250226-WA0008.
DOC-20250226-WA0008.
vtuedge.co
Note: 01. Answer any FIVE full questions, choosing at least ONE question from each
MODULE. 02. Use C code snippet to illustrate a specific code design or a purpose
Mod *Bloom’s Ma
ule -1 Taxonomy rks
Level
Q.0
1
m a Explain the structure of C program in detail. Write a sample program to
demonstrate the components in the structure of C program
The basic structure of a C program is divided into 6 parts which makes it
easy to read, modify, document, and understand in a particular format.
C program must follow the below-mentioned outline in order to
L2 8
1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
a. Sub Programs
1. Documentation
This section consists of the description of the program, the name of the
program, and the creation date and time of the program. It is specified at
the start of the program in the form of comments. Documentation can be
represented as:
or
/*
description, name of the program, programmer name, date, time etc.
*/
Anything written as comments will be treated as documentation of the
program and this will not interfere with the given code. Basically, it gives
an overview to the reader of the program.
2. Preprocessor Section
All the header files of the program will be declared in the preprocessor
section of the program. Header files help us to access other’s improved
vtuedge.co
code into our code. A copy of these multiple files is inserted into our
program before the process of compilation.
Example:
#include<stdio.h>
#include<math.h>
m
3. Definition
Preprocessors are the programs that process our source code before the
process of compilation. There are multiple steps which are involved in the
writing and execution of the program. Preprocessor directives start with
the ‘#’ symbol. The #define preprocessor is used to create a constant
throughout the program. Whenever this name is encountered by the
compiler, it is replaced by the actual piece of defined code.
Example:
4. Global Declaration
Example:
5. Main() Function
Every C program must have a main function. The main() function of the
program is written in this section. Operations like declaration and
execution are performed inside the curly braces of the main program. The
return type of the main() function can be int as well as void too. void()
main tells the compiler that the program will not return any value. The
int main() tells the compiler that the program will return an integer value.
Example:
void main()
or
int main()
6. Sub Programs
vtuedge.co
per the requirements of the programmer.
Example:
m
}
int main() {
int number = 42;
return 0;
}
int main() {
int number;
// Prompt the user for input
printf("Enter an integer: ");
vtuedge.co
}
return 0;
}
m
c Discuss different types of error occur in L2 6
program Syntax Errors:
● Definition: Syntax errors occur when the code violates the rules
of the programming language.
● Examples: Missing semicolons at the end of statements,
mismatched parentheses or braces, incorrect use of keywords, etc.
● Impact: The program will not compile until syntax errors are
fixed. The compiler will generate error messages pointing to the
location of the syntax error.
// Example of syntax error
#include <stdio.h>
int main() {
printf("Hello, world!" // Missing semicolon
return 0;
}
Logic Errors:
● Definition: Logic errors occur when the code does not produce the
expected output due to mistakes in the algorithm or overall design.
● Examples: Incorrect calculations, improper conditional
statements, wrong loop conditions, etc.
● Impact: The program may compile and run, but it will not
produce the desired or correct results. Debugging is required to
identify and fix logic errors.
// Example of logic
error #include <stdio.h>
int main() {
int x = 5, y = 10;
int sum = x - y; // Incorrect operation
Runtime Errors:
● Definition: Runtime errors occur while the program is
running. They are often related to unexpected conditions or
invalid operations during execution.
● Examples: Division by zero, accessing an array out of
bounds, dereferencing a null pointer, etc.
● Impact: The program may terminate abruptly (crash) or exhibit
unpredictable behavior. Identifying and fixing runtime errors
often involves debugging tools.
// Example of runtime error
#include <stdio.h>
vtuedge.co
int main() {
int divisor = 0;
int result = 10 / divisor; // Division by zero
m
}
OR
Q.0 a Explain the various rules for forming identifiers names. Give examples L2 8
2 for valid and invalid identifiers for the same.
In C programming, identifiers are names given to various program
elements such as variables, functions, arrays, etc. Identifiers must follow
certain rules to be valid.
Character Set:
● Valid characters for identifiers are letters (both
uppercase and lowercase), digits, and the underscore _.
● The first character of an identifier must be a letter or an
underscore.
Length:
● Identifiers can be of any length, but only the first 31
characters are significant. Some compilers may
support longer identifiers.
Keywords:
● Identifiers cannot be the same as C keywords (reserved
words). For example, int, for, while, etc., are reserved
and cannot be used as identifiers.
Whitespace:
● No whitespace characters are allowed within an identifier.
Examples of Valid Identifiers:
vtuedge.co
int 123number; // invalid (starts with a digit)
double my-score; // invalid (contains a hyphen)
char first name; // invalid (contains a whitespace)
float while; // invalid (while is a keyword)
m
b Mention various output devices and explain hardcopy devices
Hardcopy Devices:
Mod Module-2
ule-2
vtuedge.co
among bits.
m
Bitwise OR( | ) : Ittakes two numbers as operands and does OR on every
bit of two numbers. The result of OR is 1 if any of the two bits is 1.
Bitwise XOR (^) :It takes two numbers as operands and does XOR on
every bit of two numbers. The result of XOR is 1 if the two bits are
different.
Left shift(<<) : It takes two numbers, the left shifts the bits of the first
operand, and the second operand decides the number of places to shift.
Right shift(>>) : It takes two numbers, right shifts the bits of the first
operand, and the second operand decides the number of places to shift.
Bitwise NOT(~): It takes one number and inverts all bits of it.
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int main()
{
float a, b, c, d,root1,root2,real,imag;
printf("enter the coefficients a, b, c:\n");
scanf("%f%f%f",&a,&b,&c); if(a==0||b==0||
c==0)
{
printf("Invalid coefficients\n");
exit(0);
}
d=b*b-4*a*c;
if(d>0)
{
root1=(-b+sqrt(d))/(2.0*a);
root2=(-b-sqrt(d))/(2.0*a);
printf("the roots are real and distinct...\n");
printf("root1=%.2f\n”,root1); printf(“root2=
%.2f\n",root2);
}
else if(d==0)
{
root1=root2=-b/(2.0*a);
printf("the roots are real and equal..\n"); printf("root1=%.2f\
n”,root1);
printf(“root2=%.2f\n",root2);
}
{
real= -b/(2.0*a);
imag=sqrt(fabs(d))/(2.0*a);
printf("the roots are complex and
imaginary..\n");
printf("root1=%.2f+i%.2f\n",real,imag);
printf(“root2=%.2f-i%.2f\n",real,imag);
}
vtuedge.co
return 0;
}
m
Example:
#include <stdio.h>
int main()
{
int i = 0, j = 0;
if (j==2 )
break;
}
return 0;
}
continue statement: This statement skips the rest of the loop statement
and starts the next iteration of the loop to take place. Below is the
program to illustrate the same.
Example:
#include <stdio.h>
int main()
{
int i = 0, j = 0;
}
return 0;
}
vtuedge.co
OR
m
define any number of loops inside another loop.
Syntax:
for ( initialization; condition; increment )
int main()
{
int arr[2][3] = { { 0, 6 }, { 1, 7 }, { 2, 8 } };
{
printf("Element at arr[%i][%i][%i] = %d\n", i, j, k, arr[i][j][k]);
return 0;
}
while(condition)
{ while(condition)
vtuedge.co
}
m
#include <stdio.h>
int main()
{
int end = 5;
int i = 1;
printf("\n");
int j = 1;
while (j <= i)
{ printf("%d ",
j); j = j + 1;
i = i + 1;
return 0;
}
Output
Pattern Printing using Nested While loop
1
12
123
1234
12345
vtuedge.co
m
3. Nested do-while Loop
A nested do-while loop refers to any type of loop that is defined inside a
do-while loop. Below is the equivalent flow diagram for nested ‘do-while’
loops:
vtuedge.co
m
Syntax:
do{
do{
Example: Below program uses a nested for loop to print all prime factors
of a number.
#include <math.h>
#include <stdio.h>
void primeFactors(int n)
{
// Print the number of 2s that divide n
while (n % 2 == 0) {
n = n / 2;
vtuedge.co
for (int i = 3; i <= sqrt(n); i = i + 2) {
while (n % i == 0) {
m
printf("%d ", i);
n = n / i;
if (n > 2)
int main()
{
int n = 315;
primeFactors(n);
return 0;
}
#include <stdio.h>
int main()
{ int
n,r,s=0,x;
scanf("%d",&n);
x=n;
while(x!=0)
{
r=x%10;
s=s*10+r;
x/=10;
}
printf("Reverse of the number is %d",s);
if(s==n)
printf("\nNumber is a palindrome");
else
printf("\nNumber is not a palindrome");
return 0;
}
vtuedge.co
Switch Statement
The switch statement in C is an alternate to if-else-if ladder statement
which allows us to execute multiple operations for the different possibles
values of a single variable called switch variable.Here, We can define
various statements in the multiple cases for the different values of a
single variable.
m
Syntax:
switch(expression){
case value1:
//code to be
executed; break;
//optional case
value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Example :
#include<stdio.h>
#include<stdlib.h>
int main()
{
int a, b, res; char op;
printf("Enter a simple arithmetic expression:\n"); scanf("%d%c
%d",&a,&op,&b);
switch(op)
{
case '+':res=a+b;
break;
case '-':res=a-b;
break;
case '*':res=a*b;
break;
case '/':if(b!=0)
res=a/b;
else
{
printf("division by zero is not possible\n");
exit(0);
}
break;
case '%':res=a%b
; break;
default:printf("Illigal operator\n");
exit(0);
}
printf("\nResult=%d”,res);
return 0;
}
vtuedge.co
Mod
ule-3
m
void main()
{
int i,j,a[10],temp;
clrscr();
printf(“ Enter the number of elements:”);
scanf(“%d”,&n);
printf(“Enter the elements into an array\n”);
for(i=0;i<n;i++);
{ scanf(“%d”,a[i]);
}
for(i=0;i<n-1;i++)
{
for(j=0;j<n-1-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}}
printf(“ The sorted elements are \n“);
for(i=0;i<n;i++)
{
printf(“%d”,a[i]”);
}
return 0;
getch();
}
vtuedge.co
return 1;
else
return(x*fact(x-1));
}
Output:
m
Enter the number: 5
5!=120
OR
vtuedge.co
modified by the change in parameters of the called function(formal
arguments)
● Different memory is allocated for actual and formal
parameters. Example : program to show call by value.
#include<stdio.h>
#include<conio.h>
void main()
m
{
int a,b,swap();
clrscr();
a=5;
b=10;
printf(“ value of a=%d and value of b=%d before swap”,a,b);
swap(a,b);
printf(“\n value of a=%d and b=%d after swap”,a,b);
getch();
}
int swap(int x,int y)
{
int temp;
temp=x;
x=y;
y=temp;
}
Call by reference:
● The address of the variable is passed into the function call as
the actual parameter
● The value of the actual parameters can be modified by changing
the formal parameters since the address of the actual parameters
is passed
● Same memory is allocated for both formal parameters.
Example: program to show call by reference.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,*aa,*bb,swap();
clrscr();
a=5;
b=10;
aa=&a;
bb=&b;
printf(“value of a=%d and value of b=%d before swap”,a,b);
swap(aa,bb);
printf(“\n value of a=%d and b=%d after swap”,a,b);
getch();
}
int swap(int *x,int*y)
{
int temp;
temp=*x;
*x=*y;
*y=temp;
}
vtuedge.co
b Write a C program to transpose a MxN matrix
#include<stdio.h>
L3 8
m
#include<conio.h>
void main()
{
Int a[3][2],b[2][3],i,j;
clrscr();
printf(“Enter values of matrix:”);
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
scanf(“%d”,&a[i][j]);
}
printf(“Matrix:\n”);
for(i=0;i<3;i++)
{
for(j=0;j<2;j++)
printf(“%d”,a[i][j]); printf(“\
n”);
}
for(i=0;i<3;i++)
{
b[j][i]=a[i][j];
}
printf(“Transpose matrix:\n”);
for(i=0;i<2;i++)
{
for(j=0;j<3;j++)
printf(“%d”,b[i][j]); printf(“\
n”);
}
getch();
}
Output:
Enter values of the matrix: 4
5
6
1
2
3
Matrix:
45
61
23
Transpose matrix:
462
513
vtuedge.co
m
1. auto
This is the default storage class for all the variables declared inside a
function or a block. Hence, the keyword auto is rarely used while writing
programs in C language. Auto variables can be only accessed within the
block/function they have been declared and not outside them (which
defines their scope). Of course, these can be accessed within nested blocks
within the parent block/function in which the auto variable was declared.
However, they can be accessed outside their scope as well using the
concept of pointers given here by pointing to the very exact memory
location where the variables reside. They are assigned a garbage value by
default whenever they are declared.
2. extern
Extern storage class simply tells us that the variable is defined elsewhere
and not within the same block where it is used. Basically, the value is
assigned to it in a different block and this can be overwritten/changed in a
different block as well. So an extern variable is nothing but a global
variable initialized with a legal value where it is declared in order to be
used elsewhere. It can be accessed within any function/block.
Also, a normal global variable can be made extern as well by placing the
‘extern’ keyword before its declaration/definition in any function/block.
This basically signifies that we are not initializing a new variable but
instead, we are using/accessing the global variable only. The main purpose
of using extern variables is that they can be accessed between two different
files which are part of a large program.
3. static
This storage class is used to declare static variables which are popularly
used while writing programs in C language. Static variables have the
property of preserving their value even after they are out of their scope!
Hence, static variables preserve the value of their last use in their scope.
So we can say that they are initialized only once and exist till the
termination of the program. Thus, no new memory is allocated because
they are not re-declared.
Their scope is local to the function to which they were defined. Global
static variables can be accessed anywhere in the program. By default, they
vtuedge.co
are assigned the value 0 by the compiler.
4. register
This storage class declares register variables that have the same
functionality as that of the auto variables. The only difference is that the
compiler tries to store these variables in the register of the microprocessor
if a free register is available. This makes the use of register variables to be
m
much faster than that of the variables stored in the memory during the
runtime of the program.
If a free registration is not available, these are then stored in the memory
only. Usually, a few variables which are to be accessed very frequently in a
program are declared with the register keyword which improves the
running time of the program. An important and interesting point to be
noted here is that we cannot obtain the address of a register variable using
pointers.
Module-4
int main() {
char myString[] = "Hello, world!";
int length = strlen(myString);
printf("Length of the string: %d\n", length);
return 0;
}
```
**Output:** `Length of the string: 13`
vtuedge.co
2. **String Copy (strcpy):**
- **Description:** The `strcpy` function is used to copy one string to
another. It copies the characters from the source string to the
destination string until it encounters the null terminator.
- **Example:**
m
```c
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, world!";
char destination[20]; // Ensure the destination buffer is large
enough
strcpy(destination, source);
printf("Copied string: %s\n", destination);
return 0;
}
```
**Output:** `Copied string: Hello, world!`
b Develop a program using pointer to compute the sum, mean and standard L4 8
deviation of all element stored in array of N real number
Here's a C program that uses pointers to compute the sum, mean, and
standard deviation of an array of N real numbers:
```c
#include <stdio.h>
#include <math.h>
void calculateStats(double *arr, int size, double *sum, double *mean,
double *stdDev) {
// Calculate sum
*sum = 0;
for (int i = 0; i < size; i++) {
*sum += arr[i];
}
// Calculate mean
*mean = *sum / size;
vtuedge.co
// Calculate standard deviation
*stdDev = 0;
for (int i = 0; i < size; i++) {
*stdDev += pow(arr[i] - *mean, 2);
}
*stdDev = sqrt(*stdDev / size);
m
}
int main()
{ int size;
printf("Enter the number of elements: ");
scanf("%d", &size);
double numbers[size];
return 0;
}
This program prompts the user to enter the number of elements and then
takes the input for each real number. It calculates the sum, mean, and
standard deviation using pointers and prints the results. The `%lf` format
specifier is used for reading and printing double values.
The strings declared as character arrays are stored like other arrays
in C. For example, if str[] is an auto variable, the string is stored in
the stack segment; if it’s a global or static variable, then stored in the
data segment.
vtuedge.co
Strings as character arrays can be stored in two ways:
terminator*/
char str[6] = {‘N‘,‘i’, ‘n’, ‘j‘, ‘a‘, '\0'}; /* '\0' is string terminator */
m
Storing Strings as Character Pointers
char *str;
int size = 6; /*one extra for ‘\0’*/
str = (char *)malloc(sizeof(char)*size);
*(str+0) = 'N';
*(str+1) = 'i';
*(str+2) = 'n';
*(str+3) = 'j';
*(str+4) = 'a';
*(str+5) = '\0';
int main()
{
char str[] = "Ninja";
*(str+1) = 'n';
getchar();
return 0;
}
OR
vtuedge.co
int main()
{
char s[20] = “college”;
char d[20] = “terna”;
m
int i = 0;
while(s[i] != ‘\0’ || d[i] != ‘\0’)
{
if(d[i] == s[i])
{
cmp = 0; i+
+;
}
else
{
cmp = 1;
break;
}
}
f(cmp == 0)
printf(“Strings are
equal); else
printf(“Strings are different”);
return 0;
}
Incrementing a Pointer
Syntax :
data_type *ptr;
ptr = /* initialize ptr to point to some memory location */;
Example:
#include <stdio.h>
int main(){
int numbers[] = {10, 20, 30, 40, 50};
vtuedge.co
int *ptr = numbers; // Point to the first element
ptr++; // Increment the pointer to move to the next element
return 0;
} // Now ptr points to the second element (20)
Decrementing a Pointer
m
Decrementing a pointer is identical to incrementing it, except it
transfers it to the prior memory address.
Syntax :
data_type *ptr;
ptr = / * initialize ptr to point to some memory location */;
Example:
#include <stdio.h>
int main(){
int numbers[] = {10, 20, 30, 40, 50};
int *ptr = numbers;
ptr--;
return 0;
}
Example:
// Driver Code
int main()
{
// Integer variable //
int N = 4;
// Pointer to an integer
int *ptr1, *ptr2;
vtuedge.co
// Addition of 3 to ptr2
ptr2 = ptr2 + 3;
printf("Pointer ptr2 after Addition: ");
printf("%p \n", ptr2);
return 0;
m
}
Output
Pointer ptr2 before Addition: 0x7ffca373da9c
Pointer ptr2 after Addition: 0x7ffca373daa8
// Driver Code
int main()
{
// Integer variable
int N = 4;
// Pointer to an integer
int *ptr1, *ptr2;
// Subtraction of 3 to ptr2
ptr2 = ptr2 - 3;
printf("Pointer ptr2 after Subtraction: ");
printf("%p \n", ptr2);
return 0;
}
Output
Pointer ptr2 before Subtraction: 0x7ffd718ffebc
Pointer ptr2 after Subtraction: 0x7ffd718ffeb0
The gets() and puts() are declared in the header file stdio.h. Both
the functions are involved in the input/output operations of the
vtuedge.co
strings.
C gets() function
The gets() function enables the user to enter some characters followed
by the enter key. All the characters entered by the user get stored in a
m
character array. The null character is added to the array to make it a
string. The gets() allows the user to enter the space-separated strings.
It returns the string entered by the user.
Declaration
char[] gets(char[]);
#include<stdio.h>
void main ()
char s[30];
gets(s);
Output
Enter the string?
How are you doing?
You entered How are you doing?
C puts() function
The puts() function is used to print the string on the console which is
previously read by using gets() or scanf() function. The puts() function
returns an integer value representing the number of characters being
printed on the console. Since, it prints an additional newline character
with the string, which moves the cursor to the new line on the console,
the integer value returned by puts() will always be equal to the
number of characters present in the string plus 1.
Declaration:
int puts(char[])
Example:
#include<stdio.h>
#include <string.h>
vtuedge.co
int main(){
char name[50];
");
m
gets(name); //reads string from
return 0;
Output:
Enter your name: chaitanya
Your name is: chaitanya
Module-5
M Meaning Description
od
e
vtuedge.co
EXAMPLE
#include <stdio.h>
m
FILE *fp;
fp= fopen (" myfile.dat " ," r "); // file opening mode.
if (fp == NULL) {
#include<stdio.h>
#include<string.h>
struct student {
int rollno;
char name[20];
float marks;
};
int main()
{
int i,n,found=0;
struct student s[10];
float sum=0,average;
printf("\nEnter the number of student details");
scanf("%d",&n);
for(i=0; i<n; i++) {
printf("\nenter the %d student details",i+1);
printf("\n enter roll number:");
scanf("%d",&s[i].rollno);
printf("\n enter student name");
scanf("%s",s[i].name); printf("\
n enter the marks:");
scanf("%f",&s[i].marks);
}
vtuedge.co
printf("\nStudent details are\n");
printf("\nRollno\t\tName\t\tMarks\n");
for(i=0; i<n; i++)
printf("%d\t\t%s\t\t%f\n",s[i].rollno,s[i].name,s[i].marks);
m
for(i=0; i<n; i++)
sum=sum+s[i].marks;
average=sum/n;
printf("\nAVERAGE=%,2f",average); printf("\
n students scoring above average\n"); for(i=0;
i<n; i++) {
if(s[i].marks>=average) {
printf("%s\t",s[i].name);
}
}
printf("\n students scoring below average\n");
for(i=0; i<n; i++) {
if(s[i].marks<average) {
printf("%s\t",s[i].name);
found=1;
}
}
if(found==0)
printf("\n no students scored below average");
return 0;
}
m
>>example of enum declaration>>
// Or
>>PROGRAM EXAMPLE>>
int main()
{
enum week day;
day = Wed;
printf("%d",day);
return 0;
}
Output:
2
OR
vtuedge.co
There are three different functions dedicated to reading data from a
file
m
● fgets(buffer, n, file_pointer): It reads n-1 characters from
the file and stores the string in a buffer in which the NULL
character ‘\0’ is appended as the last character.
● fscanf(file_pointer, conversion_specifiers, variable_adresses):
It is used to parse and analyze data. It reads characters from
the file and assigns the input to a list of variable pointers
variable_adresses using conversion specifiers. Keep in mind
that as with scanf, fscanf stops reading a string when space or
newline is encountered.
struct structure_name {
member definition;
m
} structure_variables;
Where,
Example
struct Data {
int a;
long int b;
} data, data1;
Syntax
union union_name {
member definition;
} union_variables;
Where,
Example
union Data {
int i;
float f;
} data, data1;
vtuedge.co
This is demo!
This is demo!
Example
m
#include <stdio.h>
int main() {
FILE *f = fopen("new.txt", "r");
int c = getc(f);
while (c != EOF) {
putchar(c);
c = getc(f);
}
if (feof(f))
printf("
Reached to the end of file.");
else
printf("
Failure.");
fclose(f);
getchar();
return 0;
}
Output
This is demo!
This is demo!
Reached to the end of file.
Table showing the Bloom’s Taxonomy level, course outcome and program outcomes
Q. 1 a L2 CO1 PO1,PO2
b L3 CO2 PO1,PO2
c L2 CO2 PO1,PO2
c L2 CO1 PO1
b L3 CO2,CO5 PO1,PO2,PO3
c L4 CO2 PO1,PO2
vtuedge.co
b L3 CO2,CO5 PO1,PO2,PO3
c L3 CO2,CO5 PO1,PO2
b L3 CO3,CO5 PO1,PO2,PO3
m
c L2 CO2 PO1,PO2
b L3 CO3 PO1,PO2,PO3
c L2 CO2 PO1,PO2
b L4 CO4 PO1,PO2,PO3
c L2 CO2 PO1
b L2 CO4 PO1,PO2
c L2 CO2 PO1
Page 02 of 02
22POP13
Q.9 a L2 CO5 PO1,PO2
b L3 CO4,CO5 PO1,PO2,PO3
c L1 CO4 PO1
b L4 CO4 PO1,PO2
c L2 CO2 PO1
Page 03 of 02