POP Imp Question and Answers From Module 1 -5
POP Imp Question and Answers From Module 1 -5
AY 2024-25
Subject Code: BPOPS103 Subject: Principles of Programming Using C Date: 04/11/2024
Semester: 1 Module: 1 &2 Branch: CSE
Module – 1
Q# CO# BTL Questions Marks
● Computer is an electronic device, which takes input from the user in the
form of data and instructions.
● On receiving the instructions from the user, the computer processes the
data and generates the output and displays it to the user.
1.Supercomputers
● Fastest, most powerful, and most expensive computer
● Used to process large amounts of data and to solve complex scientific
problems
● Can support thousands of users at the same time
● Mainly used for weather forecasting, nuclear energy research, aircraft
design, automotive design, online banking, etc.
● Some examples of supercomputers are CRAY-1, CRAY-2, Control Data
CYBER 205, and ETA A-10
2.Mainframe Computers
● Large-scale computers, but smaller than Supercomputers
● Very expensive
● Need a very large clean room with air conditioning
● Used as servers on the World Wide Web
1. 8M
1 1 ● Some examples are IBM S/390, Control Data CYBER 176
3.Minicomputers
● Smaller, cheaper, and slower than Mainframes
● Can be used as servers in a networked environment
● Widely used in business, education, hospitals, government
● Some examples are AS/400 computers (IBM Corporation), Data General
Corporation, and Prime Computer
4.Microcomputers
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)
Design an algorithm, flowchart and program to compute area and perimeter of
a circle.
Step 1: Start
Step 2: Input the value radius
Step 3: Calculate Area= 3.14 * radius * radius
Step 4: Calculate Perimeter of the Circle Peri = 2 * 3.14 * radius
Step 5: PRINT Area and Peri
Step 6: END
Flowchart
● A flowchart is a graphical representation of an algorithm.
2. 2 2 6M
Program
#include <stdio.h>
int main()
{
int radius;
float area, perimeter;
printf("Enter radius of the Circle:\n");
scanf("%d", & radius);
area = 3.14 * radius * radius;
printf("Area of the Circle = %f \n", area);
perimeter = 2 * 3.14 * radius;
printf("Perimeter of the Circle = %f \n", perimeter);
return 0;
}
Output
Enter radius of the Circle:
3
Area of the Circle =28.26
Perimeter of the Circle =18.84
Explain generations of computers
3. 1 1
First Generation
Second Generation
Advantage
Disadvantage
Third Generation
Advantage
Fourth Generation
● These computers were manufactured using transistors integrated
chips(IC’s) with LSI’s and later with VLSI.
● Semiconductors memory was used as primary memory and magnetic
tapes and floppy disks were used as portable storage devices.
● Programming was done in high level programming language such as C
and C++.
Advantage
Fifth Generation
Advantage
Draw a flowchart and C program which takes as input p,t,r. Compute the
simple interest and display the result.
Flowchart
4. 2 2 6M
Program
#include <stdio.h>
void main()
{
int p,t,r;
float si=0.0;
printf("Enter the values for p,t,r:\n");
scanf("%d%d%d", &p, &t, &r);
si= p*t*r/100.0;
printf("si = %f \n", si);
}
Output
Enter the values for p,t,r:
1200
2
5
si =120.000000
Explain the structure of C program in detail. Write a sample program to
demonstrate the components in the structure of C program
Documentation
Preprocessor Directives
Global Declarations
main( )
{
Local declaration
Statements;
}
Function1( )
{
Local declaration
Statements;
}
......................
......................
FunctionN( )
{
Local declaration
Statements;
}
Documentation
● It includes the statement specified at the beginning of a program, such as
a program's name, date, description, and title.
● It is represented as:
//name of a program
Or
/*
Overview of the code
5. 2 1 8M
*/
Preprocessor Section
● This section contains all the header files used in a program.
● It informs the system to link the header files to the system libraries. It is
given by:
#include<stdio.h>
#include<stdio.h>
● Preprocessor directives are instructions given to the compiler before
actual compilation begins.
● For example, #include is used to include libraries that provide essential
functions like printf() from the standard input-output library (<stdio.h>)
Global Declarations
● Global variables are declared outside any function, usually at the top of
the program.
● These variables can be accessed and modified by any function in the
program.
main() Function
● The main() function is the entry point of every C program.
● It defines where the program starts executing and returns an integer
value (0 means successful execution).
● Formatted I/O functions are used to take various inputs from the user
and display multiple outputs to the user.
● These types of I/O functions can help to display the output to the user in
different formats using the format specifiers.
● These functions are called formatted I/O functions because we can use
format specifiers in these functions
Format Specifier Description
Example Program
#include <stdio.h>
void main()
{
int x;
printf(“Please enter any number:\n ”);
scanf(“%d”,&x);
printf(“The entered number is= %d”,x);
}
Output
Please enter any number:
20
The entered number is = 20
Explain the various rules for forming identifiers names. Give examples for valid
and invalid identifiers for the same.
8.
Handheld device
1.Joystick
● A joystick is a pointing device for computers that allows you to move the
pointer around the screen.
● Both the bottom and top ends of the stick are connected to a spherical
ball, and the bottom spherical ball slips in a socket.
● Wecan move the joystick in all four directions.
● The basic data types are also known as fundamental or primary data
10. 1 2 types. 8M
● Basic data types are used in the C language for storing the available
values in decimal as well as integer forms
● These provide support for both – unsigned and signed literals.
Integer Datatype
● The variables that are of integer type are capable of storing negative,
zero, as well as positive values without the decimals.
● The C language represents the integer data type by the keyword int.
● Size: 4 bytes
● Format Specifier: %d
Syntax of Integer
● int var_name;
● Example: int a;
Character Data Type
● Character data type allows its variable to store only a single character.
● The size of the character is 1 byte.
● It is the most basic data type in C.
● It stores a single character and requires a single byte of memory in
almost all compilers.
● Range: (-128 to 127) or (0 to 255)
● Size: 1 byte
● Format Specifier: %c
Syntax of char
● The char keyword is used to declare the variable of character type:
● char var_name;
● Example : char a = 'z';
printf("Value of a: %c\n", a);
Float Data Type
● In C programming float data type is used to store floating-point values.
● Float in C is used to store decimal and exponential values.
● It is used to store decimal numbers (numbers with floating point values)
with single precision.
● Range: 1.2E-38 to 3.4E+38
● Size: 4 bytes
● Format Specifier: %f
Syntax of float
● The float keyword is used to declare the variable as a floating point:
● float var_name;
● Example: float a;
Double Data Type
● A Double data type in C is used to store decimal numbers (numbers with
floating point values) with double precision.
● It is used to define numeric values which hold numbers with decimal
values in C.
● The double data type is basically a precision sort of data type that is
capable of holding 64 bits of decimal numbers or floating points.
● It can easily accommodate about 16 to 17 digits after or before a decimal
point.
● Range: 1.7E-308 to 1.7E+308
● Size: 8 bytes
● Format Specifier: %lf
Syntax of Double
● The variable can be declared as double precision floating point using the
double keyword:
● double var_name;
● Example : double a;
Course Outcomes:
● CO 1 Elucidate the basic architecture and functionalities of a computer and also recognize the
hardware parts.
● CO 2 Apply programming constructs of C language to solve the real-world problem
● CO 3 Explore user-defined data structures like arrays in implementing solutions to problems like
searching and sorting
● CO 4 Explore user-defined data structures like structures, unions and pointers in implementing
solutions
● CO 5 Design and Develop Solutions to problems using modular programming constructs using
functions
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Important Question and Answers AY 2024-25
Subject Code: BPOPS103 Subject: Principles of Programming Using C Date: 04/11/2024
Semester: 1 Module: 1 &2 Branch: CSE
Module – 2
Marks
Q Mod# CO# BTL Questions
#
Write a note on the following operators. i) Relational ii) Logical iii) Conditional 6M
1. 2 2 2 1)Relational Operator
These operators are used to compare the value of two variables.
Following table shows all the relational operators supported by C language.
Assume variable A holds 10 and variable B holds 20, then:
Operator Description Example
== Checks if the values of two operands (A == B) is not true.
are equal or not, if yes then condition
becomes true.
!= Checks if the values of two operands (A != B) is true.
are equal or not, if values are not
equal then condition becomes true.
> Checks if the value of left operand is (A > B) is not true.
greater than the value of right
operand, if yes then condition
becomes true.
< Checks if the value of left operand is (A < B) is true.
less than the value of right operand, if
yes then condition becomes true.
>= Checks if the value of left operand is (A >= B) is not true.
greater than or equal to the value of
right operand, if yes then condition
becomes true.
<= Checks if the value of left operand is (A <= B) is true.
less than or equal to the value of right
operand, if yes then condition
becomes true.
ii) Logical Operators:
These operators are used to perform logical operations on the given two
variables.
Following table shows all the logical operators supported by C language.
Assume variable A holds 1 and variable B holds 0, then:
Operator Description Example
&& Called Logical AND (A && B) is false.
operator. If both the
operands are nonzero,
then condition becomes
true.
|| Called Logical OR (A || B) is true.
Operator. If any of the
two operands is
non-zero, then condition
becomes true.
! Called Logical NOT !(A && B) is true.
Operator. Use to reverses
the logical state of its
operand. If a condition is
true then Logical NOT
operator will make false.
iii) Conditional Operator
Conditional Operators (? :)
Conditional operators are used in decision making in C programming, i.e,
executes different statements according to test condition whether it is either true
or false.
Syntax of conditional operators;
conditional_expression?expression1:expression2
If the test condition is true (that is, if its value is non-zero), expression1 is
returned and if false expression2 is returned.
Let us understand this with the help of a few examples:
int x, y ;
scanf ( “%d”, &x ) ;
y = ( x> 5 ? 3 : 4 ) ;
This statement will store 3 in y if x is greater than 5, otherwise it will store 4 in
y.
The equivalent if statement will be,
if ( x > 5 )
y=3;
else
y=4;
2. 2 1 3 Demonstrate the functioning of Bitwise operator in C 6M
Bitwise Operators
Bitwise operator works on bits and performs bit-by-bit operation. Bitwise
operators are used in bit level programming. These operators can operate upon
int and char but not on float and double.
Showbits( ) function can be used to display the binary representation of any
integer or character value.
Bit wise operators in C language are; & (bitwise AND), | (bitwise OR), ~
(bitwise OR), ^ (XOR),
<< (left shift) and >> (right shift).
The truth tables for &, |, and ^ are as follows
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
List the conditional branching statements in C. Explain any two with example.
3. 2 1 1 Conditional branch statements 6M
The statements that transfer the control from one place to another place in the
program based on some conditions are called Conditional branch statements.
Simple- if
if-else
Nested-if
if-else-if
switch
If Statement:
✔ The ‘if’ statement is the simplest form of decision control statement.
✔ When a set of statements have to be executed when an expression
(condition) is evaluated to true or skipped when an expression
(condition) is evaluated to false, then if statement is used.
✔ It is used whenever there is only one choice (alternative). Hence it is
also called as “One- way decision or selection statement”.
Syntax of if statement
if(test Expression)
{
Statement 1;
Statement 2;
...
…
… Statement n;
}
Statement x;
Working Principle
First the test expression is evaluated. If the test expression is true, then the
statements of ‘if’ block (statement 1 to n) are executed. Otherwise these
statements will be skipped and the execution will jump to statement x.
Example
#include<stdio.h>
void main()
{
int age;
printf(“Enter the age:”);
scanf(“%d”,&age);
if(age>=18)
printf(“\nThe person is eligible to vote”);
if(age<18)
printf(“\nThe person is not eligible to vote”);
}
if-else statement
✔ If one set of activities have to be performed when an expression is
evaluated to true and another set of activities have to be performed when
an expression is evaluated to false, then if-else statement is used.
✔ The is-else statement is used when we must choose between two
choices (alternatives). Hence is also called as “Two-way Decision or
Selection Statement”.
Syntax of if-else statement:
if(test Expression)
{
Statement block 1;
}
else
{
Statement block 2;
}
Statement x;
Example
#include<stdio.h>
void main()
{
int age;
printf(“Enter the age:”);
scanf(“%d”,&age);
if(age>=18)
printf(“\nThe person is eligible to vote”);
else
printf(“\nThe person is not eligible to vote”);
}
Write an algorithm, flow chart and C program to check whether the integer is
5. 2 1 3 even or odd. 8M
Program
#include<stdio.h>
void main()
{
int n;
printf(“Enter a number:”);
scanf(“%d”,&n);
if(n%2==0)
printf(“Number is even”);
else
printf(“Number is odd”);
}
Flow Chart
ALGORITHM :
STEP 1: START
STEP 2: Receive data from a user or dynamically assign value
STEP 3: if num percent 2 == 0. Even Integer should be printed.
STEP 4: Else,
STEP 5: Print an Odd Number
STEP 6: END
Write an algorithm, flow chart and C program to check whether the 8M
6. 2 1 3
entered year is leap year or not
Algorithm
Step 1: Start
Step 2: Read the value of the year to be checked from the user
Step 3: Assign the value to a variable, say ‘year’
Step 4: If (year%4 = 0 AND year%100 != 0) OR year%400 = 0, then:
Step 4.1: Display “Leap Year”
Step 5: Else
Step 5.1: Display “Not Leap Year”
Step 6: Stop
Flowchart
Program
#include<stdio.h>
void main()
{
int year;
printf(“Enter any year:”);
scanf(“%d”,&year);
if(((year%4==0)&&(year%100!=0))||(year%400==0))
printf(“%d is a leap year”,year);
else
}
printf(“%d is not a leap year”,year);
}
Write a C program to print whether a given number is palindrome or not 8M
7 2 2 3
#include<stdio.h>
void main()
{
int digit,rev=0,num,n;
printf("Enter the number:\n");
scanf("%d",&num);
n=num;
while(num!=0)
{
digit=num%10;
rev=rev*10+digit;
num=num/10;
}
printf("The reversed number is=%d\n",rev);
if(n==rev)
printf(“ The number is a palindrome”);
else
}
printf(“The number is not a palindrome”);
}
10. Define looping. Explain while and do-while with suitable example
2 2 2
while loop
Loop Statements
for loop
do-while loop
while Loop
It is a control statement using which the programmer can give
instructions to the computer to execute a set of statements repeatedly as
long as specified condition is satisfied.
The expression is evaluated to TRUE or FALSE in the beginning of the while
loop. Hence it is called as “Entry-Controlled Loop”.
Syntax of while loop
while(test expression)
{
Statements;
}
Statement x;
Example
Write a C program to print the natural numbers from 1 to 10.
#include<stdio.h>
void main()
{
int i=1;
while(i<=10)
{
printf(“%d\n”,i);
i++;
}
}
do-while Loop
do- while loop is used when a set of statements have to be repeatedly
executed at least once.
Since the test expression is evaluated to TRUE or FALSE at the end of
do-while loop, the do- while loop is called as exit-controlled loop.
The while and for loop test the expression at the top.
The do-while tests the expression at the bottom after making each passes
through the loop body
Syntax of do-while loop
do
{
Statements;
} while(test expression);
Statement x;
11 List and explain unconditional branching statements with
example(goto,break,continue)
2 2 1
break statement
In C, break statement is used to terminate the execution of the nearest
enclosing loop in which it appears.
It is ‘jump’ statement which can be used in switch statement and loops.
The break statement in switch statement causes the control to come out
of the switch statement and transfers the control to the statement which
follows the switch statement.
switch(ch)
{
case 1: printf(“1st statement”);
break;
case 2: printf(“2nd statement”);
break;
default: printf(“nth statement”);
}
Example
Write a C program to print the numbers (0 to 4) using break.
#include<stdio.h>
void main()
{
int i=0;
while(i<=10)
{
if(i==5)
break;
printf(“%d\n”,i);
i=i+1;
}
}
continue statement
During execution of a loop, it may be necessary to skip a part of the loop
based on some condition. In such cases, we use continue statement.
The continue statement is used only in the loops to terminate the current
iteration and continue with the remaining iterations.
Syntax:
1. while(… )
{
if(condition) continue;
……….
}
……….
Course Outcomes:
● CO 1 Elucidate the basic architecture and functionalities of a computer and also recognize the
hardware parts.
● CO 2 Apply programming constructs of C language to solve the real-world problem
● CO 3 Explore user-defined data structures like arrays in implementing solutions to problems like
searching and sorting
● CO 4 Explore user-defined data structures like structures, unions and pointers in implementing
solutions
● CO 5 Design and Develop Solutions to problems using modular programming constructs using
functions
Department of Computer Science and Engineering
Module 3
1. Discuss the implementation of user defined function with suitable example.
Sol A user-defined function is a type of function in C language that is defined by the user
himself to perform some specific task. User-defined functions are different from built-in
functions as their working is specified by the user and no header file is required for their
usage.
The user-defined function in C can be divided into three parts:
a. Function Prototype
b. Function Definition
c. Function Call
#include <stdio.h>
// Driver code
int main()
{
int x = 10, y = 20;
printf("Values of x and y before swap are: %d, %d\n", x,
y);
swap(x, y); //function call
printf("Values of x and y after swap are: %d, %d", x,
y);
return 0;
}
Output
Values of x and y before swap are: 10, 20
Values of x and y after swap are: 10, 20
2. Explain the syntax of Function Declaration and Function Definition And Function
call with example.
Sol:
a. C Function Prototype/ Function Declaration
A function prototype is also known as a function declaration which specifies the function’s
name, function parameters, and return type. The function prototype does not contain the body
of the function.
Syntax
return_type function_name (type1 arg1, type2 arg2, ... typeN argN);
b. C Function Definition
Once the function has been called, the function definition contains the actual statements that
will be executed. All the statements of the function definition are enclosed within {} braces.
Syntax
return_type function_name (type1 arg1, type2 arg2 .... typeN argN)
{
// actual statements to be executed
// return value if any
}
c. Function Call
In order to transfer control to a user-defined function, we need to call it. Functions are called
using their names followed by round brackets. Their arguments are passed inside the
brackets.
Syntax
function_name(arg1, arg2, ... argN);
// Function prototype
int sum(int, int);
// Function definition
int sum(int x, int y)
{
int sum;
sum = x + y;
return x + y;
}
// Driver code
int main()
{
int x = 10, y = 11;
// Function call
int result = sum(x, y);
printf("Sum of %d and %d = %d ", x, y, result);
return 0;
}
3. Explain the different parameter passing techniques with example (OR) Differentiate
between call by value and call by reference. Using suitable example
Sol:
We can pass parameters to a function in C using two methods:
A. Call by Value
B. Call by Reference
A. Call by value
In call by value, a copy of the value is passed to the function and changes that are made to the
function are not reflected back to the values. Actual and formal arguments are created in
different memory locations.
Example
// Driver code
int main()
{
int x = 10, y = 20;
printf("Values of x and y before swap are: %d, %d\n", x,
y);
swap(x, y);
printf("Values of x and y after swap are: %d, %d", x,
y);
return 0;
}
Output
Values of x and y before swap are: 10, 20
Values of x and y after swap are: 10, 20
Note: Values aren’t changed in the call by value since they aren’t passed by reference.
B. Call by Reference
In a call by Reference, the address of the argument is passed to the function, and changes that
are made to the function are reflected back to the values. We use the pointers of the required
type to receive the address in the function.
Example
// C program to implement
// Call by Reference
#include <stdio.h>
// Driver code
int main()
{
int x = 10, y = 20;
printf("Values of x and y before swap are: %d, %d\n", x,
y);
swap(&x, &y);
printf("Values of x and y after swap are: %d, %d", x,
y);
return 0;
}
Output
Values of x and y before swap are: 10, 20
Values of x and y after swap are: 20, 10
Automatic
o Automatic variables are allocated memory automatically at runtime.
o The visibility of the automatic variables is limited to the block in which they
are defined.
The scope of the automatic variables is limited to the block in which they
are defined.
Static
o The variables defined as static specifier can hold their value between the
multiple function calls.
o Static local variables are visible only to the function or the block in which
they are defined.
o A same static variable can be declared many times but can be assigned at
only one time.
o Default initial value of the static integral variable is 0 otherwise null.
o The visibility of the static global variable is limited to the file in which it has
declared.
o The keyword used to define static variable is static.
Register
o The variables defined as the register is allocated the memory into the CPU
registers depending upon the size of the memory remaining in the CPU.
o We can not dereference the register variables, i.e., we can not use &operator
for the register variable.
o The access time of the register variables is faster than the automatic
variables.
o The initial default value of the register local variables is 0.
o The register keyword is used for the variable which should be stored in the
CPU register. However, it is compiler?s choice whether or not; the variables
can be stored in the register.
o We can store pointers into the register, i.e., a register can store the address
of a variable.
o Static variables can not be stored into the register since we can not use more
than one storage specifier for the same variable.
External
o The external storage class is used to tell the compiler that the variable
defined as extern is declared with an external linkage elsewhere in the
program.
o The variables declared as extern are not allocated any memory. It is only
declaration and intended to specify that the variable is declared elsewhere
in the program.
o The default initial value of external integral type is 0 otherwise null.
o We can only initialize the extern variable globally, i.e., we can not initialize
the external variable within any block or method.
o An external variable can be declared many times but can be initialized at
only once.
o If a variable is declared as external then the compiler searches for that
variable to be initialized somewhere in the program which may be extern or
static. If it is not, then the compiler will show an error.
#include<stdio.h>
int fibonacci(int);
void main ()
{
int n,f;
n = 12;
f = fibonacci(n);
printf("%d",f);
}
int fibonacci (int n)
{
if (n==0)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
return fibonacci(n-1)+fibonacci(n-2);
}
}
6. Explain the declaration and initialization of one dimensional and two dimensional
arrays with an example.
Sol: An array is a collection of one or more values of the same data type stored in contiguous
memory locations. The data type can be user-defined or even any other primitive data-type.
While declaring a one-dimensional array in C, the data type can be of any type, and also, we
can give any name to the array, just like naming a random variable.
Syntax:
int arr[5]; //arr is the array name of type integer, and 5 is the size of the array
Array Initialization
In static uninitialized arrays, all the elements initially contain garbage values, but we can
explicitly initialize them at their declaration.
Syntax:
<data_type> <arr_name> [arr_size]={value1, value2, value3,…};
Array Accessing
In one-dimensional arrays in C, elements are accessed by specifying the array name and the
index value within the square brackets. Array indexing starts from 0 and ends with size- If
we try to access array elements out of the range, the compiler will not show any error
message; rather, it will return some garbage value.
Syntax:
<arr_name>[index];
//program
#include < stdio.h >
int main() {
//declaring and initializing one-dimensional array in C
int arr[3] = {10, 20, 30};
Module – 4
Mo
Q# CO# BTL Questions Marks
d#
Define String. Explain any 4 string manipulation function with
1. 4 4 2 suitable example. 8M
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.
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.
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.
Strlen Function
Syntax:
Size_t strlen(const char * str);
This function calculates the length of the string str up to but not including
the null character, i.e., the function returns the number of characters in the
string.
Strcmp function
Syntax:
int strcmp(const char * str1, const char *str2);
The strcmp function compares the string pointed to by str1 to the string
pointed to by str2. The function returns zero if the strings are equal.
Otherwise, it returns a value less than zero or greater than zero if str1 is
less than or greater than str2 respectively.
Develop a C program to compare 2 strings without using built-in 6M
2. 4 4 3 function.
Answer
int main()
{
char s[20] = “college”;
char d[20] = “terna”;
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;
}
Write functions to implement string operations such as find string
3. 4 4 3 6M
length. Use the parameter passing techniques. (Without String
Length Function)
#include <stdio.h>
int len_str(char s[50]);
int comp_str(char s1[50], char s2[50]) ; void concat_str(char s1[50],char
s2[50]);
void main()
{
char s1[50],s2[50],len,c; printf("enter the 1st string\n"); scanf("%s",s1);
printf("enter the 2nd string\n");
scanf("%s",s2); len=len_str(s1);
printf("length of the string1 = %d\n",len); len=len_str(s2);
printf("length of the string2 = %d\n",len); c=comp_str(s1,s2);
if(c==0)
{
printf("strings are equal\n");
}
else
{
printf("strings are not equal\n");
}
concat_str(s1,s2);
}
In C, both puts() and printf() functions are used for printing a string on the
console and are defined in <stdio.h> header file.
puts() Function
The puts() function is used to write a string to the console and it
automatically adds a new line character ‘\n’ at the end.
Syntax
puts("str");
Parameters
• str: It takes a null-terminated string as the argument.
Return Value
• It returns a non-negative value if the output is successful, or
End-of-File if an error occurs.
Printf() Function
The printf() function is also used to print data on the console, but it can
also be used to print the formatted data to the console based on a
specified format string.
Syntax
printf(“format_string”, Arguments);
Parameters
• format_string: It can be a simple string or a string containing
format specifiers.
• Arguments: It is the variable names whose value is to be
printed.
Return Value
• It returns the number of characters successfully written to the
console and a negative value if an error occurs.
Develop a C program to find the largest of three numbers using
7. 4 4 3 6M
pointer.
Answer
#include<stdio.h>
int main()
{
int a,b,c,*pa, *pb, *pc;
printf(“Enter three numbers:\n”);
scanf(“%d%d%d”, &a,&b,&c);
/* Referencing */
pa= &a;
pb= &b;
pc= &c;
if(*pa > *pb && *pa > *pc)
{
printf(“Largest is: %d”, *pa);
}
else if(*pb > *pc && *pb > *pc)
{
printf(“Largest is : %d”, *pb);
}
else
{
printf(“Largest = %d”, *pc);
}
return 0;
}
Define Pointer. Explain pointer variable declaration and initialization
8. 4 4 2 with suitable example. 8M
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;
Here, data_type is the data type of the value that the pointer will point to.
For example:
int *pnum; char *pch; float *pfnum;
int x= 10;
int *ptr = &x;
The ‘*’ informs the compiler that ptr is a pointer variable and the int
specifies that it will
store the address of an integer variable.
The & operator retrieves the lvalue (address) of x, and copies that to the
contents of the
pointer ptr.
● We can “dereference” a pointer, i.e. refer to the value of the variable to
which it points
by using unary ‘*’ operator as in *ptr. That is, *ptr = 10, since 10 is value
of x.
#include<stdio.h>
int main()
{
int num, *pnum;
pnum = #
printf(“\n Enter the number : “);
scanf(“%d”, &num);
printf(“\n The number that was entered is : %d”, *pnum);
return 0;
}
OUTPUT:
Enter the number : 10
The number that was entered is : 10
4 Explain the difference between a null pointer and a void pointer.
9. 4 2 6M
Following table clearly compare Null pointer against void pointer.
return 0;
}
• For dynamic memory allocation by using malloc() and calloc()
functions .
One of the most important applications of C pointers is to declare
memory for the variables dynamically.
1. The malloc() Function
This function is defined in the "stdlib.h" header file. It allocates a
block memory of the required size and returns a void pointer.
void *malloc (size)
2. The calloc() Function
The C library function "calloc" (stands for contiguous allocation)
allocates the requested memory and returns a pointer to it.
void *calloc(n, size);
Where "n" is the number of elements to be allocated and "size" is
the byte size of each element.
3. The realloc() Function
The realloc() function in C is used to dynamically change the
memory allocation of a previously allocated memory. You can
increase or decrease the size of an allocated memory block by
calling the realloc() function.
void *realloc(*ptr, size);
The first parameter "ptr" is the pointer to a memory block
previously allocated with malloc, calloc or realloc to be
reallocated.
• For returning multiple values.
In C language, the functions can have only one return statement to
return one value at a time. With the help of C pointers, you can
return multiple values from a function by passing arguments as
references.
void funAddSub(int a, int b, int* add, int* sub)
{
*add = a + b;
*sub = a - b;
}
int main() {
int num1 = 10;
int num2 = 3;
// Variables to store results
int res1, res2;
// Calling function to get add and sub
// by passing the address of res1 and res2
funAddSub(num1, num2, &res1, &res2);
// Printing the result
printf("Addition is %d and subtraction is %d", res1, res2);
return 0;
}
Develop a C program to compute the sum, mean and standard
11. 4 4 3 deviation of all element of an array using pointer 8M
Answer
Here's a C program that uses pointers to compute the sum, mean, and
standard deviation of an array of N real numbers:
#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);
}
Course Outcomes:
• CO 1 Elucidate the basic architecture and functionalities of a computer and also recognize the
hardware parts.
• CO 2 Apply programming constructs of C language to solve the real-world problem
• CO 3 Explore user-defined data structures like arrays in implementing solutions to problems like
searching and sorting
• CO 4 Explore user-defined data structures like structures, unions and pointers in implementing
solutions
• CO 5 Design and Develop Solutions to problems using modular programming constructs using
functions
Department of Computer Science and Engineering
Module 5
Structure declaration:
A structure is declared using the keyword struct followed by a structure name .all the variable of the
structure is declared within the structure.
Syntax:
Struct structure name
{
Data type var-name;
Data type var-name;
……..
};
Example:1
Struct student
{
int r_no;
char name[20];
char course[20];
float fees;
};
Now ,structure has become user defined data type each var-name declared within a structure is called
a member of the structure.
Example:2
Struct student
{
int r_no;
char name[20];
char course[20];
float fees;
}stud1,stud2;
In declaration ,we declare two variable stud1 and stud2 of the structure student. So,if you want to
declare more than one variable of the structure, then separate the variable using comma.
2. Develop a C program to read and display the information of all the students
in the class.
Sol:
#include <stdio.h>
// Structure to store student information
struct Student {
int roll_number;
char name[20];
float marks;
};
int main()
{
int n;
// Ask the user for the number of students
printf("Enter the number of students: ");
scanf("%d", &n);
// Array to store student information
struct Student students[n];
// Input student details
for (int i = 0; i < n; i++)
{
printf("\nEnter details for student %d:\n", i + 1);
5. Explain various modes of operations in which file can be opened for processing.
Sol:
• 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.
Example: which creates a new type of variable called COLOURS to store colour constants
enum COLOURS {RED, BLUE, BLACK, GREEN, YELLOW, PURPPLE, WHITE};
COLOUR is the name given to the set of constants. In case you do not assign any value to a constant.
the default value for the first one in the list –RED has the value of 0.The rest of the undefined constants
have a value 1 more than its previous one.
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:
enum COLOUR{RED=2,BLUE,BLACK=5,GREEN=7,YELLOW,PURPLE,WHITE=15};
as a result of this statement
RED=2,BLUE=3,BLACK=5,GREEN=7,YELLOW=8,PURPLE=9,WHITE=15.
Example:
#include<stdio.h>
main()
{
enum{RED=2,BLUE,BLACK=5,GREEN=7,YELLOW,PURPLE,WHITE=15};
Printf(“\n RED=%d”,RED);
Printf(“\n BLUE=%d”,BLUE);
Printf(“\n BLACK=%d”,BLACK);
return 0;
}