19AI304 Fundamentals of C AnsKey NOV 2023
19AI304 Fundamentals of C AnsKey NOV 2023
(PART A – 2 Marks)
UNIT - I
Q. No Questions Answers
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
1 What are keywords? Give Examples identifier.
Ex: int, float, char, if, else, do, while, for.
1. An identifier/variable name must be start with an alphabet or underscore (_) only, no other
special characters
2. Digits are allowed but not as first character of the identifier/variable name.
List any 2 rules to be followed while naming
2 3. Any space cannot be used between two words of an identifier/variable; you can use
the identifier/variable name underscore (_) instead of space.
4. Case-sensitive.
5. Keywords are not allowed for naming an identifier.
3 Demonstrate the ternary operators with The conditional operator is also known as a ternary operator.As conditional operator works
examples. on three operands, so it is also known as the ternary operator.
The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else'
statement is also a decision-making statement.
#include <stdio.h>
int main()
{
int age; // variable declaration
printf("Enter your age");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditional
operator
return 0;
}
A compiler is a computer program that reads a program written in a high-level language such
as FORTRAN, PL/I, COBOL, etc. It can translate it into the same program in a low-level
language including machine language. The compiler also finds out the various errors
4 Differentiate Compiler and Interpreter encountered during the compilation of a program.
Interpreter is a program that executes the programming code directly instead of just
translating it into another format. It translates and executes programming language
statements one by one
Show the output of the following program
#include <stdio.h>
void main ()
{
int m=40, n=30;
5 if (m == n) m and n are not equal
{
printf("m and n are equal");
}
printf("m and n are not equal");
}
#include <stdio.h>
int main()
Write a program to read only positive integer {
6 value from the user and display the value on unsigned int a;
the monitor. scanf("%u",&a);
printf("%u",a);
}
7 Write a program to find product of two #include <stdio.h>
fraction values. int main() {
int num1, den1, num2, den2;
return 0;
}
#include <stdio.h>
Write a program to find maximum between int main()
two integer numbers using conditional {
8 int num1, num2, p;
operator. scanf("%f%f",&num1,&num2);
num1>num2?:printf(“%d”,num1):printf(“%d”,num2);
return 0;}
The conditional operator is also known as a ternary operator.As conditional operator works
on three operands, so it is also known as the ternary operator.
The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else'
statement is also a decision-making statement.
#include <stdio.h>
int main()
{
int num;
scanf("%d", &num);
if(num%6==0) Output:
10 { 18
printf("Divisible by 6"); Divisible by 6
}
else
{
printf("Not Divisible by 6");
}
return 0;
}
UNIT - II
Q. No Questions Answers
While Statement
Condition is checked first then statement(s) is executed.
It might occur statement(s) is executed zero times, If condition is false.
while loop is entry controlled loop.while(condition)
{ statement(s); }
List out the difference between while and do
11 do while statement
while statements.
Statement(s) is executed atleast once, thereafter condition is checked.
At least once the statement(s) is executed.
do-while loop is exit controlled loop.
do { statement(s); }
while(condition);
12 Construct a program to check whether a #include <stdio.h>
given number is even or odd. int main() {
int num;
printf("Enter an integer: ");
scanf("%d", &num);
if(num % 2 == 0)
printf("%d is even.", num);
else
printf("%d is odd.", num);
return 0;
}
#include<stdio.h>
int main()
{
int num=10, count = 1;
printf("\n");
return 0;
}
default:
// code to be executed if all cases are not matched;
}
1.break
What are the unconditional control 2.continue
15 3.goto
statements in C?
4.return
#include <stdio.h>
int main() {
char vowel;
printf("Enter a vowel (A, E, I, O, U): ");
scanf("%c", &vowel);
switch (vowel) {
case 'A':
case 'a':
printf("The ASCII value of %c is %d\n", vowel, (int)vowel);
break;
case 'E':
case 'e':
printf("The ASCII value of %c is %d\n", vowel, (int)vowel);
break;
Construct a C Program to print the ASCII value of
case 'I':
16 vowels (A,E,I,O,U) using the switch statement (EX.
case 'i':
A-65, E-69)
printf("The ASCII value of %c is %d\n", vowel, (int)vowel);
break;
case 'O':
case 'o':
printf("The ASCII value of %c is %d\n", vowel, (int)vowel);
break;
case 'U':
case 'u':
printf("The ASCII value of %c is %d\n", vowel, (int)vowel);
break;
default:
printf("Not a vowel.\n");
}
return 0;
}
#include<stdio.h>
int main()
{
int num, count = 1;
printf("Enter a positive number\n");
scanf("%d", &num);
printf("\nNatural numbers from %d to %d:\n", count, num);
#include <stdio.h>
int main() {
int N, sum = 0;
if (N < 1) {
Construct a C Program to print the sum of even
printf("N must be a positive integer.\n");
18 numbers from 1 to N using for loop
} else {
for (int i = 2; i <= N; i += 2) {
sum += i;
}
return 0;
}
19 Write a C program to print the following triangular #include <stdio.h>
Star pattern using loop
*** int main() {
** int n = 3; // Number of rows in the pattern
*
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
printf("*");
}
printf("\n");
}
return 0;
}
20 Construct a C program to input two numbers from #include <stdio.h>
user and find maximum between two numbers
using switch case. int main() {
double num1, num2;
int choice;
return 0;
}
UNIT - III
Q. No Questions CO
An array is a collection of similar kind of data elements stored in adjacent memory locations
and are referred to by a single name.
Arrays are defined in much the same manner as ordinary variables, except that each array
1 Define array with examples. name must be accompanied by a size specification.
data_type array_name[array_size];
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns.
data type array_name[rows][columns];
Ex: int twodimen[3][4]; 3 is the number of rows, and 4 is the number of columns.
#include<stdio.h>
int main(){
int i=0,j=0;
Demonstrate two dimensional arrays with
2 int arr[3][3]={{1,2,3},{2,3,4},{3,4,5}};
examples. //traversing 2D array
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0; }
#include <stdio.h>
int main()
{
int n;
scanf("%d",&n);
Write a program to read n elements as input int a[n];
for(int i=0;i<n;i++)
6 and print the second element of the array {
(integer). scanf("%d",&a[i]);
}
printf("%d\n",a[1]);
return 0;
}
7 Construct a program to prepare EMI #include <stdio.h>
calculation for the sum of 25000, at 8% rate #include <math.h>
of interest,5 years using function with return
// Function to calculate EMI
type with arguments. double calculateEMI(double principal, double rate, int time) {
double interest = rate / 1200; // Monthly interest rate
int n = time * 12; // Total number of payments
return emi;
}
int main() {
double principal = 25000; // Loan amount
double rate = 8; // Annual interest rate
int time = 5; // Loan tenure in years
return 0;
}
8 #include <stdio.h>
return 0;
}
#include <stdio.h>
#include <ctype.h> // for tolower function
int main() {
char inputString[] = "PROGRAMMING FUNDAMENTALS";
int length = strlen(inputString);
write a program to convert the string
printf("Original String: %s\n", inputString);
9 ‘PROGRAMMING FUNDAMENTALS’
into lowercase for (int i = 0; i < length; i++) {
inputString[i] = tolower(inputString[i]);
}
return 0;}
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "abcd", str2[] = "abCd";
Construct a Program to compare
10 int result;
two strings using strcmp (). result = strcmp(str1, str2);
printf("strcmp(str1, str2) = %d\n", result);
return 0;
}
UNIT - IV
Q. No Questions Answers
Sorting is the process of arranging the data in ascending or descending order. The term
sorting came into picture, as humans realized the importance of searching quickly.
Sorting arranges data in a sequence which makes searching easier.
What is sorting & List out some of sorting There are many different techniques available for sorting, differentiated by their efficiency
1 and space requirements.
techniques?
Bubble Sort
Insertion Sort
Selection Sort
Dynamic memory allocation is a technique in computer programming where memory is
allocated at runtime (during program execution) rather than at compile time. It allows you to
allocate memory for data structures, such as arrays, linked lists, and other data types, when
What is Dynamic memory allocation? List you don't know the size of these data structures beforehand or when you want to manage
2 memory more flexibly.
out the library functions.
In C and C++, dynamic memory allocation is commonly used with library functions like
malloc, calloc, realloc, and free.
# include <stdio.h>
void fun(int *ptr)
{
*ptr = 30;
}
int main()
{
int y = 20;
fun(&y);
printf("%d", y);
return 0;
}
Show the output of the following program
#include <stdio.h>
void main()
{
4 LE
char *s= "HELLO";
char *p = s;
}
The address (&) of the variable is passed to the function as parameter.
The value of the actual parameter can be modified by formal parameter.
5 Define Call by Reference. Same memory is used for both actual and formal parameters since only address is used by
both parameters.
malloc is a C standard library function that is used for dynamic memory allocation. It stands
for "memory allocation" and is used to allocate a block of memory of a specified size at
Explain malloc () with syntax. Give
6 runtime. The syntax of malloc is as follows:
example. void *malloc(size_t size);
eg., int *dynamicArray = (int *)malloc(n * sizeof(int));
7 Define Call by value. Give example. "Call by value" is a method of passing arguments to a function in programming. In call by
value, a copy of the actual argument's value is passed to the function parameter.
#include <stdio.h>
int main() {
int x = 5;
int y = 10;
swap(x, y);
return 0;
}
8 How do you free the block of used memory In dynamic memory allocation, you use the free function to deallocate or release the memory
in dynamic memory allocation? Write the that was previously allocated using functions like malloc, calloc, or realloc.
Syntax : void free(void *ptr);
syntax and give example. #include <stdio.h>
#include <stdlib.h>
int main() {
int n = 5; // Number of integers
if (dynamicArray == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *arr;
arr=(int*)malloc(50). int newSize = 100
9 Write the code snippet to reallocate the arr = (int *)malloc(50 * sizeof(int));
memory as 100 using realloc(). printf("Memory allocated for 50 integers.\n");
int *temp = (int *)realloc(arr, newSize * sizeof(int));
arr = temp;
printf("Memory reallocated for 100 integers.\n");
free(arr);
return 0;
}
#include <stdio.h>
int main() {
int num1, num2, sum;
int *ptr1, *ptr2;
scanf("%d", &num1);
Construct a program to add two integer scanf("%d", &num2);
10
numbers using pointers.
ptr1 = &num1;
ptr2 = &num2;
sum = *ptr1 + *ptr2;
printf("Sum of %d and %d is: %d\n", *ptr1, *ptr2, sum);
return 0;
}
UNIT - V
Q. No Questions Answers
structure is a composite data type that allows you to group together variables of different data
types under a single name. Each variable within a structure is known as a "member" or
"field."
#include <stdio.h>
int main() {
11 Define structure with an example. // Declare a variable of type Point
struct Point p1;
return 0;
}
Structure Members can be accessed through structure variable using the dot or period
operator
Syntax :
struct structurename variable1, variable2, ..... variable n;
Example
Struct book b1; /* b1 is a structure variable name */
12 What is structure variable? Accessing Structure Data members:
Syntax :
Stru_variablename.membername;
Example
b1.pages=400;
b1.price=450.00;
struct book
{
How to Declare a structure for storing book char title[20];
13 float price;
information?
int quantity ;
}b;
Structure
Every member is assigned a unique memory location.
A structure can store multiple values of the different members
structure’s total size is the sum of the size of every data member.
Users can access or retrieve any member at a time
14 Differentiate Structure and Union.
Union
All the data members share a memory location.
A union stores one value at a time for all of its members
A union’s total size is the size of the largest data member.
You can access or retrieve only one member at a time.
The typedef is a keyword used in C programming to provide some meaningful names to the
already existing variable. It behaves similarly as we define the alias for the commands. In
short, we can say that this keyword is used to redefine the name of an already existing
variable.
15 Define typedef with an example.
Example:
typedef int unit;
int main() {
// Declare a variable of type Laptop
struct Laptop myLaptop;
Create a structure to hold the information of
18 // Assign values to the structure members
a Laptop(Brand name, Size in inches, price).
strcpy(myLaptop.brand, "Dell"); // Assuming the brand is "Dell"
myLaptop.sizeInInches = 15.6; // Example size
myLaptop.price = 799.99; // Example price
return 0;
}
19 Create a C program to print the value of the #include <stdio.h>
wednesday using enumeration.
enum DaysOfWeek {
enum day {sunday, monday, tuesday, wed- SUNDAY, // 0
nesday, thursday, friday, saturday}; MONDAY, // 1
TUESDAY, // 2
WEDNESDAY, // 3
THURSDAY, // 4
FRIDAY, // 5
SATURDAY // 6
};
int main() {
enum DaysOfWeek today = WEDNESDAY;
enum TV {
FOX = 11,
CNN = 25,
ESPN = 15,
HBO = 22,
MAX = 30,
Create a C Program to print the list of cable NBC = 32
station using enumeration. };
20 enum TV { FOX = 11, CNN = 25, ESPN = int main() {
15, HBO = 22, MAX = 30, NBC = 32 }; printf("List of Cable Stations:\n");
printf("FOX: Channel %d\n", FOX);
printf("CNN: Channel %d\n", CNN);
printf("ESPN: Channel %d\n", ESPN);
printf("HBO: Channel %d\n", HBO);
printf("MAX: Channel %d\n", MAX);
printf("NBC: Channel %d\n", NBC);
return 0;
}
UNIT - I
Q. No Questions Answers
1 Explain various data types & Constant in C – Data Types
C with examples
C data types are defined as the data storage format that a variable can store a data to perform
a specific operation.
Data types are used to define a variable before to use in a program.
Size of variable, constant and array are determined by data types.
There are four data types in C language. They are,
Types Data Types
1. float
2. double
FLOAT:
Float data type allows a variable to store decimal values.
Storage size of float data type is 4. This also varies depend upon the processor in the
CPU as “int” data type.
We can use up-to 6 digits after decimal using float data type.
For example, 10.456789 can be stored in a variable using float data type.
DOUBLE:
Double data type is also same as float data type which allows up-to 10 digits after deci -
mal.
The range for double data type is from 1E–37 to 1E+37.
MODIFIERS IN C LANGUAGE:
CONSTANT IN C
C Constants are also like normal variables. But, only difference is, their values cannot be
modified by the program once they are defined.
Constants refer to fixed values. They are also called as literals
Constants may be belonging to any of the data type.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
TYPES OF C CONSTANT:
1. Integer constants
4. Character constants
5. String constants
1. INTEGER CONSTANTS IN C:
2. REAL CONSTANTS IN C:
A real constant must have at least one digit
It must have a decimal point
It could be either positive or negative
If no sign precedes an integer constant, it is assumed to be positive.
No commas or blanks are allowed within a real constant.
#include <stdio.h>
int main()
{
int n; // variable declaration
int count=0; // variable declaration
printf("Enter a number");
Write a program to count the number of scanf("%d",&n);
digits in the given number . while(n!=0)
2 {
n=n/10;
count++;
}
+ (Addition) A+B
– (Subtraction) A-B
* (multiplication) A*B
/ (Division) A/B
% (Modulus) A%B
2. RELATIONAL OPERATORS IN C:
Relational operators are used to find the relation between two variables. i.e. to compare the
values of two variables in a C program.
operators Example/Description
== x == y (x is equal to y)
!= x != y (x is not equal to y)
3. LOGICAL OPERATORS IN C:
These operators are used to perform logical operations on the given expressions.
There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and
logical NOT (!).
Operators Example/Description
# include <stdio.h>
void main()
{
int a, b, c, big ;
Construct a program to find greatest of scanf("%d %d %d", &a, &b, &c) ;
4 three numbers using ternary operators. big = a > b ? (a > c ? a : c) : (b > c ? b : c) ;
printf("The biggest number is : %d", big) ;
}
78 90 76
The biggest number is : 90
5 Explain bitwise operator with examples. BIT WISE OPERATORS IN C:
These operators are used to perform bit operations. Decimal values are converted into
binary values which are the sequence of bits and bit wise operators work on these bits.
Bit wise operators in C language are
& (bitwise AND),
| (bitwise OR),
~ (bitwise NOT),
^ (XOR),
<< (left shift) and
>> (right shift).
TRUTH TABLE FOR BIT WISE OPERATION & BIT WISE OPERATORS:
#include <stdio.h>
int main()
{
int a=30,b=2;
printf("Bitwise AND Result is: %d",a&b);
printf("\nBitwise OR Result is: %d",a|b);
printf("\nBitwise XOR Result is: %d",a^b);
printf("\nLeft Shift Result is: %d",a<<b);
printf("\nRight Shift Result is: %d",a>>b);
return 0;
}
output
Bitwise AND Result is: 2
Bitwise OR Result is: 30
Bitwise XOR Result is: 28
Left Shift Result is: 120
Right Shift Result is: 7
6 #include <stdio.h>
Construct a program to generate the first int main() {
10 terms of the Fibonacci series.
int i, n;
return 0;
}
7
#include <stdio.h>
Construct a program to find simple #include <math.h>
interest & compound interest. int main()
{
float principle, year, rate, CI,SI;
scanf("%f", &principle);
scanf("%f", &year);
scanf("%f", &rate);
SI = (principle * year * rate) / 100;
printf("Simple Interest = %.2f", SI);
CI = principle* (pow((1 + rate / 100), year));
printf("\nCompound Interest = %.2f", CI);
return 0;
}
int year;
Construct a program to check whether the
scanf("%d", &year);
8 given year is leap year or not using
conditional operator. (year%4==0 && year%100!=0) ? printf("LEAP YEAR") :
return 0;
}
# include <stdio.h>
void main()
Develop a program to find maximum {
9 between -700, -850, -650 using int a, b, c, big ;
conditional operator scanf("%d %d %d", &a, &b, &c) ;
big = a > b ? (a > c ? a : c) : (b > c ? b : c) ;
printf("The biggest number is : %d", big) ; }
#include <stdio.h>
int main()
{
int days, years, weeks;
years=10;
Develop a program to convert 10 years
10 weeks = (days % 365) / 7;
into days & weeks. days = days - ((years * 365) + (weeks * 7));
return 0; }
UNIT - II
Q. No Questions Answers
#include<stdio.h>
Construct a program to find whether a int main()
given number is positive or negative or {
int number;
zero. scanf("%d",&number);
if(number>0)
1 Sample Sample Output printf("Number is positive");
Input else if(number<0)
45 Number is positive printf("Number is negative");
else
-35 Number is negative printf("Number is equal to 0");
0 Number is equal to return 0;
0 }
2 Summarize various conditional Control Generally C program statement is executed in a order in which they appear in the program.
statements with examples. But sometimes we use decision making condition for execution only a part of program that is
called control statement. Control statement defined how the control is transferred from one
part to the other part of the program.
C provides the following statements for implementing the selection control structure.
if statement
if else statement
nested if statement
switch statement
if statement
Statement execute set of command like when condition is true and its syntax is
if (condition)
Statement;
The statement is executed only when condition is true. If the if statement body is consists of
several statement then better to use pair of curly braces. Here in case
condition is false then compiler skip the line within the if block.
void main()
int n;
scanf(“%d”,&n);
If (n>10)
Output:
Enter a number:12
Number is greater
if.....else ... Statement : it is bidirectional conditional control statement that contains one
condition & two possible action. Condition may be true or false, where non-zero value
regarded as true & zero value regarded as false. If condition are satisfy true, then a single or
block of statement executed otherwise another single or block of statement is executed.
syntax is:-
if (condition)
{ Statement1;Statement2;}
Else statement cannot be used without if or no multiple else statement are allowed
within one if statement. It means there must be a if statement with in an else statement.
void main()
{
int n;
If (n%2==0)
else
printf(“odd number”);
odd number
Nesting of if ...else
When there are another if else statement in if-block or else-block, then it is called
Syntax is :-
if (condition)
if (condition)
Statement1;
else
statement2;
}
Statement3;
If....else LADDER
In this type of nesting there is an if else statement in every else part except the last
part. If condition is false control pass to block where condition is again checked with its if
statement.
Syntax is :-
if (condition)
Statement1;
else if (condition)
statement2;
else if (condition)
statement3;
else
statement4;
This process continue until there is no if statement in the last block. if one of the
condition is satisfy the condition other nested “else if” would not executed.
But it has disadvantage over if else statement that, in if else statement whenever the condition
is true, other condition are not checked. While in this case, all condition are checked.
switch statement
switch (var / expression)
{ case constant1 : statement 1;
break;
case constant2 : statement2;
break;
default: statement3;
break;
}
3 Develop a program to prepare an EB Bill #include <stdio.h>
int main()
{
int unit;
float amt;
scanf("%d", &unit);
return 0;}
return 0;
}
5 Explain the various Looping statements in Looping statement is the statements execute one or more statement repeatedly several
C. number of times. In C programming language there are three types of loops; while, for and
do-while.
Types of Loops
Depending upon the position of a control statement in a program, a loop is classified into two
types:
1. Entry controlled loop (while loop & for loop )
2. Exit controlled loop (do..while)
In an entry controlled loop, a condition is checked before executing the body of a loop. It is
also called as a pre-checking loop.
In an exit controlled loop, a condition is checked after executing the body of a loop. It is also
called as a post-checking loop.
For loop
For Loop in C is a statement which allows code to be repeatedly executed. For loop contains
3 parts Initialization, Condition and Increment or Decrements.
While loop
In While Loop in C First check the condition if condition is true then control goes inside the
loop body otherwise goes outside the body. while loop will be repeats in clock wise direction.
Syntax
Assignment;
while(condition)
{
Statements;
......
Increment/decrements (++ or --);
}
do-while
Syntax
do
{
Statements;
........
Increment/decrement (++ or --)
} while();
#include <stdio.h>
void main()
{
int i, num1, num2, count = 0, sum = 0;
Construct a program to print the numbers
ranging from M to N (including M and N printf("Enter the value of num1 and num2 \n");
values divisible by 11. scanf("%d %d", &num1, &num2);
6 Sample input: 20 40 (20 and 40 are printf("Integers divisible by 5 are \n");
included) for (i = num1; i <= num2; i++)
Sample Output: 22 33. {
if (i % 11 == 0)
{
printf("%3d", i);
}
}
}
7 Construct a Program to print the sum of N #include <stdio.h>
numbers which is divisible by 3 and 9.
int main() {
int N, number, sum = 0;
if (N <= 0) {
printf("N must be a positive integer.\n");
return 1;
}
printf("Enter %d numbers:\n", N);
for (int i = 0; i < N; i++) {
scanf("%d", &number);
return 0;
}
8 #include <stdio.h>
Construct a program to input month int main()
{
number and print the month name using int month;
switch case. scanf("%d", &month);
switch(month)
{
case 1:
printf("January");
break;
case 2:
printf("February");
break;
case 3:
printf("March");
break;
case 4:
printf("April");
break;
case 5:
printf("May");
break;
case 6:
printf("June");
break;
case 7:
printf("July");
break;
case 8:
printf("August");
break;
case 9:
printf("September");
break;
case 10:
printf("October");
break;
case 11:
printf("November");
break;
case 12:
printf("December");
break;
default:
printf("Invalid input! Please enter month number between 1-12");
}
return 0;
}
9 Write a C program to find the eligibility of #include <stdio.h>
admission for a professional course based void main()
{ int p,c,m,t,mp;
on the following criteria:
Total in all three subject >=180 printf("Eligibility Criteria :\n");
Marks in Maths >=60 printf("Marks in Maths >=60\n");
Marks in Phy >=60 printf("and Marks in Phy >=60\n");
Marks in Chem>=60 printf("and Marks in Chem>=60\n");
printf("and Total in all three subject >=180\n");
printf("-------------------------------------\n");
if (m>=60)
if(p>=60)
if(c>=60)
if((m+p+c)>=180))
printf("The candidate is eligible for admission.\n");
else
printf("The candidate is not eligible.\n");
else
printf("The candidate is not eligible.\n");
else
printf("The candidate is not eligible.\n");
else
printf("The candidate is not eligible.\n");
}
#include<stdio.h>
int main()
{
int i, number, flag=0;
return 0;
}
UNIT - III
Q. No Questions Answers
1 Explain array and its types with examples. An array is defined as the collection of similar type of data items stored at contiguous
memory locations. Arrays are the derived data type in C programming language which can
store the primitive type of data such as int, char, double, float, etc.
Types of Array
Declaration of Array
Ex: int marks[5]; Here, int is the data_type, marks are the array_name, and 5 is the
array_size.
#include<stdio.h>
int main(){
int i=0;
int marks[5];//declaration of array
marks[0]=80;//initialization of array
marks[1]=60;
marks[2]=70;
marks[3]=85;
marks[4]=75;
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}//end of for loop
return 0;
}
80
60
70
85
75
Two Dimensional Arrays:
The two-dimensional array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. However, 2D
arrays are created to implement a relational database lookalike data structure.
ex: int twodimen[3][4]; 3 is the number of rows, and 4 is the number of columns.
#include<stdio.h>
int main(){
int i=0,j=0;
int arr[3][3]={{1,2,3},{2,3,4},{3,4,5}};
//traversing 2D array
for(i=0;i<3;i++){
for(j=0;j<3;j++){
printf("arr[%d] [%d] = %d \n",i,j,arr[i][j]);
}//end of j
}//end of i
return 0;
}
arr[0] [0] = 1
arr[0] [1] = 2
arr[0] [2] = 3
arr[1] [0] = 2
arr[1] [1] = 3
arr[1] [2] = 4
arr[2] [0] = 3
arr[2] [1] = 4
arr[2] [2] = 5
Array operations
1. Insertion
2. Deletion
3. Searching
4. Updating
5.Traversal
(Or)
#include <stdio.h>
int main() {
int a[10][10], transpose[10][10], r, c;
printf("Enter rows and columns: ");
scanf("%d %d", &r, &c);
#include <stdio.h>
int add();
int main()
{
int c;
c= add();
printf("%d",c);
}
int add()
{
int a,b,c;
scanf("%d%d",&a,&b);
c=a+b;
return c;
}
12 12
24
#include <stdio.h>
void add(int a, int b);
int main()
{
int a,b;
scanf("%d%d",&a,&b);
add(a,b);
}
void add(int a,int b)
{
int c=a+b;
printf("%d",c);
}
12 12
24
int c=a+b;
return c;
}
12 12
24
#include<stdio.h>
#include<math.h>
int main()
{
printf("Enter a Number to Find Factorial: ");
printf("\nFactorial of a Given Number is: %d ",fact());
return 0;
Construct a program to find the factorial }
int fact()
4 of the given number using recursive {
function. int i,fact=1,n;
scanf("%d",&n);
for(i=1; i<=n; i++)
{
fact=fact*i;
}
return fact;
}
#include <stdio.h>
int main()
{ char str1[50], str2[50], i, j;
printf("Enter first string: ");
scanf("%s",str1);
printf("\nEnter second string: "); scanf("%s",str2);
for(i=0; str1[i]!='\0'; ++i);
Construct a program to combine the two //This loop would concatenate the string str2 at the end of str1
5 for(j=0; str2[j]!='\0'; ++j, ++i)
strings without using built-in functions.
{ str1[i]=str2[j];
} // \0 represents end of string
str1[i]='\0';
printf("\nOutput: %s",str1);
return 0;
}
while (y != 0) {
// Calculate sum without considering carry
sum = x ^ y;
return totalCarries;
}
int main() {
int x = 89878;
int y = 73638;
return 0;
}
8 Construct a C Program to find largest and
second largest elements in the given array #include <stdio.h>
int main ()
using sorting. {
int n = 0, i = 0, largest1 = 0, largest2 = 0, temp = 0;
printf ("\n");
largest1 = array[0];
largest2 = array[1];
return 0;
}
)#include <stdio.h>
int main( )
{
auto int j = 1;
{
auto int j= 2;
Write a program to display the value using
{
9 auto storage class without using looping auto int j = 3;
statements printf ( " %d ", j);
}
printf ( "\t %d ",j);
}
printf( "%d\n", j);}
int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);
UNIT - IV
Q. No Questions Answers
1 Build a program to perform search #include<stdio.h>
operation to find whether the given int main()
{
element is found or not . int a[100], n, element, pos=0;
int i;
Selection Sort in C
This sorting algorithm iterates through the array and finds the smallest number in the array
and swaps it with the first element if it is smaller than the first element. Next, it goes on to the
second element and so on until all elements are sorted.
Step 3 – swap the first location with the minimum value in the array
Build a program to arrange the following Step 5 − Repeat the process until we get a sorted array
#include <stdio.h>
2 values 56, 34, 23, 64, 12 in ascending int main()
order using Selection sorting technique. {
int a[10]={56,34,23,64,12};
int n=9, i, j, position, swap;
for(i = 0; i < n - 1; i++) {
position=i;
for(j = i + 1; j < n; j++) {
if(a[position] > a[j])
position=j; }
if(position != i) {
swap=a[i];
a[i]=a[position];
a[position]=swap; } }
printf("Sorted Array:");
for(i = 0; i < n; i++)
printf("%d ", a[i]);
return 0;
}
3 Explain Pointer with Examples. Pointer is a variable which stores the address of another variable. This variable can be of type
int, char, array, function, or any other pointer. The size of the pointer depends on the
architecture. However, in 32-bit architecture the size of a pointer is 2 byte.
Declaration of pointer :
syntax : datatype *pointername;
The pointer in c language can be declared using * (asterisk symbol). It is also known as
indirection pointer used to dereference a pointer.
Example :
int *ptr; int num=26;
ptr=#
Pointer Operator
Advantages:
#include <stdio.h>
int main()
{
int x, y, *a, *b, temp;
temp = *b;
*b = *a;
*a = temp;
return 0;
}
5 Explain in detail on Parameter Passing Function Calling or Parameter Passing Mechanism:
mechanism with suitable examples. 1. Pass by value 2. Pass by reference
1. PASS BY VA LUE:
#include<stdio.h>
void swap(int a, int b);// function prototype or function declaration
int main()
{ int m = 22, n = 44;
// calling swap function by value
printf(" values before swap m = %d \nand n = %d", m, n);
swap(m, n);printf("values after swap m = %d \nand n = %d", m, n); }
2. PASS BY REFERENCE:
int main() {
int numbers[] = {14, 15, 16, 17};
int n = sizeof(numbers) / sizeof(numbers[0]);
int *ptr = numbers; // Initialize a pointer to the first element of the array
int sum = 0;
double average;
printf("Numbers: ");
for (int i = 0; i < n; i++) {
printf("%d ", numbers[i]);
}
return 0;
}
9 Construct a program to print the reverse of #include <stdio.h>
the string using pointers. #include <string.h>
int main() {
char str[100]; // Declare a character array to store the string
char *ptr; // Declare a pointer to traverse the string
// Input a string
printf("Enter a string: ");
gets(str); // Input the string (note: gets is used for simplicity; it's generally not
recommended due to security issues)
// Initialize the pointer to the end of the string
ptr = str + strlen(str) - 1;
printf("\n");
return 0;
}
#include <stdio.h>
int main() {
float length, width, area;
Construct a C program to find area of rec- printf("Enter the length of the rectangle: ");
10 tangle using pointer. scanf("%f", &length);
return 0;
}
UNIT - V
Q. No Questions Answers
1 Explain structure with examples. Structures are collection of different data type grouped together under a single variable name
for convenient handling. 'struct' is a keyword, struct type is a name which identifies the
structure.
Structure Members can be accessed through structure variable using the dot or period
operator
Syntax :
struct structurename variable1, variable2, ..... variable n;
Example
Struct book b1; /* b1 is a structure variable name */
Syntax :
Stru_variablename.membername;
Example
b1.pages=400;
b1.price=450.00;
strcpy(bookname,"Harry Potter");
#include<stdio.h>
struct stud
{
int id;
char name[20];
int mark1,mark2,mark3;
int total;
int avg;
}b;
void main()
{
printf("\nEnter the student details");
scanf("%d %s %d %d %d",&b.id,&b.name, &b.mark1,&b.mark2,&b.mark3);
b.total=b.mark1+b.mark2+b.mark3;
b.avg=b.total/3;
printf("%d %s %d %d ",b.id,b.name, b.total, b.avg);
}
A structure within another structure is called Nesting of structures. The declaration of the
embedded structure must appear before the declaration of the outer structure.
#include<stdio.h>
struct dob {
int date;
int month;
int year; };
struct stud{
int sno;
char sname[10];
Explain briefly on nested structure with
2 struct dob sdob;
suitable examples. char sex; };
void main() {
struct stud s;
scanf("%d",&s.sno);
printf("enter the sname\n");
scanf("%s",s.sname);
printf("enter the dob\n");
scanf("%d%d%d %c",&s.sdob.date, &s.sdob.month,&s.sdob.year,&s.sex);
printf("%d\t %s\t %d %d %d \t %c", s.sno, s.sname, s.sdob.date, s.sdob.month, s.sdob.year,
s.sex); getch(); }
Self-referential structure:
Explain briefly on Self-referential
3
structures with examples. Self-referential structures are those which have structure pointer of the same type as their
member, we can define pointers to structures in the same way as you define pointer to any
other variable.
struct stud *b,p; // struct structurename *pointervariable variablename;
The address of a structure variable can be stored in the above defined pointer variable. To
find the address of a structure variable, place the ‘&’; operator before the structure’s name
b=&p; //pointervariable= address of variable name;
To access the members of a structure using a pointer to that structure, you must use the →
operator
b->name; //pointervariable->membervariable;
#include<stdio.h>
struct stud
{
int id;
char name[20];
int mark1,mark2,mark3;
int total;
int avg;
};
void main()
{
struct stud *b,p;
b=&p;
printf("\nEnter the student details");
scanf("%d %s %d %d %d",&b->id,b->name, &b->mark1,&b->mark2,&b->mark3);
b->total=b->mark1+b->mark2+b->mark3;
b->avg=b->total/3;
printf("%d %s %d %d",b->id,b->name, b->total, b->avg);
}
6 Summarize Union with Examples. Write Union: Union and structure in C are same in concepts, except allocating memory for their
a Program to print integer, float, character members. Structure allocates storage space for all its members separately. Whereas, Union
allocates one common storage space for all its members.
data using union.
1.Syntax:
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
#include<stdio.h>
#include<string.h>
union student
{
int age;
char name[10];
float salary;
};
int main()
{
union student s;
s.age=30;
strcpy(s.name,"saveetha");
s.salary=35000.88;
printf("%d",s.age);
printf("\n%s",s.name);
printf("\n%f",s.salary);
return 0;
}
#include <stdio.h>
#include <string.h>
union Data {
int i;
float f;
char str[20];
};
int main( ) {
data.i = 10;
printf( "data.i : %d\n", data.i);
data.f = 220.5;
printf( "data.f : %f\n", data.f);
return 0;
}
7 Create a C program to print 12 months in #include <stdio.h>
numbers using enumeration.
// Define an enumeration for months
enum Months {
JANUARY = 1,
FEBRUARY,
MARCH,
APRIL,
MAY,
JUNE,
JULY,
AUGUST,
SEPTEMBER,
OCTOBER,
NOVEMBER,
DECEMBER
};
int main() {
// Loop through the months and print them with their corresponding numbers
for (enum Months month = JANUARY; month <= DECEMBER; month++) {
printf("%d - ", month);
switch (month) {
case JANUARY: printf("January\n"); break;
case FEBRUARY: printf("February\n"); break;
case MARCH: printf("March\n"); break;
case APRIL: printf("April\n"); break;
case MAY: printf("May\n"); break;
case JUNE: printf("June\n"); break;
case JULY: printf("July\n"); break;
case AUGUST: printf("August\n"); break;
case SEPTEMBER: printf("September\n"); break;
case OCTOBER: printf("October\n"); break;
case NOVEMBER: printf("November\n"); break;
case DECEMBER: printf("December\n"); break;
}
}
return 0;
}
8 Construct a program to read the Details of #include <stdio.h>
the 3 courses offered by the college #include <string.h>
(course name, department, credits). // Define a structure for Course
Suggest a course with the highest credit struct Course {
using Structure. char name[100];
Example: course suggestion: Data char department[50];
Science, AI&DS, 6 int credits;
};
int main() {
struct Course courses[3];
struct Course maxCreditCourse;
int maxCredits = 0;
printf("Department: ");
scanf(" %[^\n]", courses[i].department);
printf("Credits: ");
scanf("%d", &courses[i].credits);
// Display course details and suggest the course with the highest credit
printf("\nCourse Details:\n");
for (int i = 0; i < 3; i++) {
printf("Course %d:\n", i + 1);
printf("Course Name: %s\n", courses[i].name);
printf("Department: %s\n", courses[i].department);
printf("Credits: %d\n\n", courses[i].credits);
}
return 0;
}
9 Construct a C program to find the given #include <stdio.h>
date lies in the leap year or not using
// Define a structure for Date
structure. Create a structure Date (day, struct Date {
month, year). int day;
int month;
int year;
};
int main() {
struct Date date;
if (isLeapYear(date.year)) {
printf("%d/%d/%d is in a leap year.\n", date.day, date.month, date.year);
} else {
printf("%d/%d/%d is not in a leap year.\n", date.day, date.month, date.year);
}
return 0;
}
10 Demonstrate Typedef in structure with typedef in C is used to create an alias (a new name) for an existing data type, including user-
suitable coding snippet. defined data types like structures. It simplifies the code and makes it more readable. Here's an
example of using typedef with a structure:
#include <stdio.h>
int main() {
// Declare variables of type Point
Point p1, p2;
p2.x = -3;
p2.y = 7;
// Print the points
printf("Point 1: (%d, %d)\n", p1.x, p1.y);
printf("Point 2: (%d, %d)\n", p2.x, p2.y);
return 0;
}
UNIT - I
Q. No Questions Answers
#include <stdio.h>
int main()
{
float eng, phy, chem, math, comp;
float total, average, percentage;
printf("Enter marks of five subjects: \n");
scanf("%f%f%f%f%f", &eng, &phy, &chem, &math, &comp);
total = eng + phy + chem + math + comp;
Construct a program to calculate total, average = total / 5.0;
percentage = (total / 500.0) * 100;
1 average and percentage of five subjects printf("Total marks = %.2f\n", total);
without using array. printf("Average marks = %.2f\n", average);
printf("Percentage = %.2f", percentage);
return 0;
}
Enter marks of five subjects:
89 87 67 90 99
Total marks = 432.00
Average marks = 86.40
Percentage = 86.40
2 Construct a C program to read the student #include<stdio.h>
marks and print the which class he/she int main()
{
got. int marks;
int main() {
Construct a program to swap two numbers int num1, num2;
3
using bit-wise operator.
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
swap(&num1, &num2);
return 0;
}
4 (i) Develop a C program to input a number (i) #include <stdio.h>
from the user and check whether the
number is positive, negative or zero using intint
main() {
number;
a switch case. (6)
printf("Enter a number: ");
(ii) Read M & N as inputs from the user to scanf("%d", &number);
specify the range. Construct a C Program
to if (number > 0) {
printf("The number is positive.\n");
print the sum of numbers within the } else if (number < 0) {
given range. (7) printf("The number is negative.\n");
Constraints: } else {
1<=M<=100 printf("The number is zero.\n");
1<=N<=100 }
and N>M. return 0;
}
(ii) #include <stdio.h>
int main() {
int M, N;
int sum = 0;
return 0;
}
UNIT - II
Q. No Questions CO
1 Develop a C program to print the pascal’s #include<stdio.h>
triangle pattern
long factorial(int);
1 int main()
11 {
121 int i, n, c;
1331
14641 printf("How many rows you want to show in pascal triangle?\n");
1 5 10 10 5 1 scanf("%d",&n);
1 6 15 20 15 6 1
for ( i = 0 ; i < n ; i++ )
{
for ( c = 0 ; c <= ( n - i - 2 ) ; c++ )
printf(" ");
for( c = 0 ; c <= i ; c++ )
{
printf("%ld ",factorial(i)/(factorial(c)*factorial(i-c)));
printf("\n");
}
return 0;
}
long factorial(int n)
{
int c;
long result = 1;
#include <stdio.h>
int main()
{
int n,k=2,m=1;
printf("Enter the number of rows");
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
for(int j=1;j<=i;j++)
Construct a C program for this following {
pattern: if(i%2==0)
1 {
3 24 printf("%d",k);
135 k=k+2;
2468 }
Else
13579 {
printf("%d",m);
m=m+2;
}
}
printf("\n");
}
return 0;
}
4 Construct a C program for this following #include <stdio.h>
pattern:
AAAAA int main() {
int rows, i, j;
AAAAA
AAAAA printf("Enter the number of rows: ");
AAAAA scanf("%d", &rows);
AAAAA
if (rows <= 0) {
printf("Please enter a positive number of rows.\n");
return 1;
}
for (i = 1; i <= rows; i++) {
// Print spaces
for (j = 1; j <= rows - i; j++) {
printf(" ");
}
printf("\n");
}
return 0;
}
UNIT - III
Q. No Questions Answers
1 Build a program to find the number of #include<stdio.h>
vowels, consonants, Special Characters int main(){
char words[200];
and white spaces in a given text. int vowels=0, letters=0, word=0, digits=0, spaces=0;
int flag=0, i;
clrscr();
printf("Enter a line of Text :\n");
gets(words);
for(i=0;words[i]!='\0';++i)
{
if(words[i]=='a' || words[i]=='e' || words[i]=='i' || words[i]=='o' || words[i]=='u' ||
words[i]=='A' || words[i]=='E' || words[i]=='I' || words[i]=='O' || words[i]=='U')
++vowels;
else
if((words[i]>='a'&& words[i]<='z') || (words[i]>='A'&& words[i]<='Z'))
++letters;
else
if(words[i] >='0' && words[i] <='9')
++digits;
else
if (words[i]==' '){
++spaces;
flag=0;}
if (words[i] !=' '&& flag==0){
++word;
flag=1;
}
}
letters += vowels;
printf("\n\n Number of words: %d", word);
printf("\n Number of Digits: %d", digits);
printf("\n Number of Consonants: %d", letters);
//Alphabetic letters
printf("\n Number of Vowels: %d", vowels);
printf("\n Number of White spaces: %d", spaces);
printf("\n Number of Characters: %d", i);
getch();
return 0;
}
Number of words: 5
Number of Digits: 2
Number of Consonants: 11
Number of Vowels: 5
Number of White spaces: 4
Number of Characters: 19
2 Build a Menu-driven program to count the #include<stdio.h>
numbers which are divisible by 3, 5 and #include<stdlib.h>
//function declarations
by both.(passing an array to a function) void divisible_by_three(int a[]);
void divisible_by_five(int a[]);
void divisible_by_threeandfive(int a[]);
int main()
{
int a[5];
int c,i;
for(i=0;i<5;i++)
scanf("%d",&a[i]);
do{
printf("\nMenu");
printf("\n1.Divisible by three");
printf("\n2.Divisible by five");
printf("\n3.Divisible by three & five");
printf("\n4.Exit");
printf("\nEnter your choice: ");
scanf("%d",&c);
switch(c)
{
case 1:
divisible_by_three(a);
break;
case 2:
divisible_by_five(a);
break;
case 3:
divisible_by_threeandfive(a);
break;
case 4:
printf("Thank You.");
exit(0);
}
}while(1);
return 0;
}
void divisible_by_three(int a[])
{
int i,count=0;
printf("The Divisible Numbers in array are : ");
for(i=0;i<5;i++)
{
if(a[i]%3==0)
{
printf("%d ",a[i]);
count++;
}
}
printf("\nTotal Numbers Divisible by Three is : %d",count);
}
void divisible_by_five(int a[])
{
int i,count=0;
printf("The Divisible Numbers in array are : ");
for(i=0;i<5;i++)
{
if(a[i]%5==0)
printf("%d ",a[i]);
count++;
}
printf("\nTotal Numbers Divisible by Five is : %d",count);
}
void divisible_by_threeandfive(int a[])
{
int i,count=0;
printf("The Divisible Numbers in array are : ");
for(i=0;i<5;i++)
{
if(a[i]%3==0 && a[i]%5==0)
{
printf("%d ",a[i]);
count++;
}
}
printf("\nTotal Numbers Divisible by Three & Five is : %d",count);
}
3 Construct a program to find sum of digits #include <stdio.h>
using recursion.
// Function to find the sum of digits using recursion
int sumOfDigits(int number) {
if (number == 0) {
return 0; // Base case: When the number becomes 0, the sum is 0.
} else {
// Recursively find the sum of digits for the remaining part of the number.
return (number % 10) + sumOfDigits(number / 10);
}
}
int main() {
int number;
return 0;
}
/* Function declaration */
void printEvenOdd(int cur, int limit);
int main()
{
int lowerLimit, upperLimit;
return 0;
}
/**
* Recursive function to print even or odd numbers in a given range.
*/
void printEvenOdd(int cur, int limit)
{
if(cur > limit)
return;
UNIT - IV
Q. No Questions Answers
1 Build a program to arrange the following Insertion Sort is a sorting algorithm where the array is sorted by taking one element at a time.
values 100,300,50,30,89,201 in ascending The principle behind insertion sort is to take one element, iterate through the sorted array &
find its correct position in the sorted array.
order using Insertion sorting technique.
Insertion Sort works in a similar manner as we arrange a deck of cards.
Insertion sort algorithm picks elements one by one and places it to the right position where it
belongs in the sorted list of elements. Following are the steps involved in insertion
sort(Algorithm):
1. We start by making the second element of the given array, i.e. element at index 1, the key.
The key element here is the new card that we need to add to our existing sorted set of cards
(remember the example with cards above).
2.We compare the key element with the element(s) before it, in this case, element at index 0:
If the key element is less than the first element, we insert the key element before the first
element.
If the key element is greater than the first element, then we insert it after the first element.
3. Then, we make the third element of the array as key and will compare it with elements to
it's left and insert it at the right position.
#include <stdio.h>
int main()
{
int n, i, j, temp;
int arr[64];
int main() {
int number;
return 0;
}
(ii) #include <stdio.h>
#include <stdlib.h>
int main() {
int *list = (int *)malloc(1 * sizeof(int)); // Allocate memory for one integer
if (list == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
if (list == NULL) {
printf("Memory reallocation failed.\n");
free(list);
return 1;
}
return 0;
}
4 (i)Write a program in C to print the (i) #include <stdio.h>
elements of an array in reverse order using #include <stdlib.h>
pointer. int main() {
(ii) Construct a C program to count total int size;
number of even elements in an array using
calloc (). // Prompt the user for the size of the array
printf("Enter the size of the float array: ");
scanf("%d", &size);
return 0;
}
int main() {
int n;
return 0;
}
UNIT - V
Q. No Questions Answers
1 Construct a program to add two distances #include <stdio.h>
in inch –feet system using structure. struct distance
{
(12 inches= 1 feet) int feet;
int inch;
};
void addDistance(struct distance d1,struct distance d2)
{
struct distance d3;
d3.feet= d1.feet + d2.feet;
d3.inch= d1.inch + d2.inch;
int main()
{
struct distance d1,d2;
printf("Enter first distance in feet & inches:");
scanf("%d%d",&d1.feet, &d1.inch);
int main() {
struct Employee employees[3];
// Input employee data and calculate Gross Salary for each employee
for (int i = 0; i < 3; i++) {
printf("Enter employee %d details:\n", i + 1);
printf("Department: ");
scanf("%s", employees[i].dept);
return 0;
}
4 (i) Construct a C program to store the data (i)#include <stdio.h>
of different type & retrieve them using union unionJob
{
union. (8) //defining a union
(ii) Write a program to display the class char name[32];
timings using enumeration. float salary;
(like first hour=8 am. fifth hour=12 int workerNo;
pm)(7) } uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
(ii) enum classtime{hr1=8,hr2=9,hr3=10,hr4=11,hr5=12};
int main()
{
int k=1;
// printing the values of months
for(int i=hr1;i<=hr5;i++)
{
printf("%d Hour=%d am,”,k,i);
k++;
}
return 0;
}