0% found this document useful (0 votes)
74 views89 pages

19AI304 Fundamentals of C AnsKey NOV 2023

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
74 views89 pages

19AI304 Fundamentals of C AnsKey NOV 2023

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 89

Answer Key for Question Repository for NOV 2023 Examinations

(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.

Syntax of a conditional operator


Expression1? expression2: expression3;

#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;

// Input the first fraction


printf("Enter the first fraction (numerator denominator): ");
scanf("%d %d", &num1, &den1);
// Input the second fraction
printf("Enter the second fraction (numerator denominator): ");
scanf("%d %d", &num2, &den2);

// Calculate the product of the two fractions


int product_num = num1 * num2;
int product_den = den1 * den2;

// Print the product as a simplified fraction


printf("Product of the fractions: %d/%d\n", product_num, product_den);

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.

Syntax of a conditional operator


Expression1? expression2: expression3;

Write a C program to read the age of a


person and determine whether the person is
9
eligible for casting the vote using ternary #include <stdio.h>
operator 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;
}
Show the output for the below code:

#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("\nNatural numbers from %d to %d:\n", count, num);

while(count <= num)


{
Develop code to sum all the prime numbers printf("%d ", count);
13
from 1 to 10 using do while loop. count++;
}

printf("\n");

return 0;
}

The switch statement in C is an alternate to if-else-if ladder statement which allows us to


execute multiple operations for the different possible values of a single variable called switch
variable.
syntax
switch(expression){
case value1:
//code to be executed;
Write short notes on switch statements with break; //optional
14 case value2:
its syntax.
//code to be executed;
break; //optional
......

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);

while(count <= num)


17 Write a C Program to print 1 to N numbers using
{
While loop
printf("%d ", count);
count++;
}
printf("\n");
return 0;
}

#include <stdio.h>

int main() {
int N, sum = 0;

printf("Enter a positive integer N: ");


scanf("%d", &N);

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;
}

printf("The sum of even numbers from 2 to %d is: %d\n", N, sum);


}

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;

// Input two numbers from the user


printf("Enter the first number: ");
scanf("%lf", &num1);

printf("Enter the second number: ");


scanf("%lf", &num2);

// Compare the two numbers


if (num1 > num2) {
choice = 1; // num1 is greater
} else if (num2 > num1) {
choice = 2; // num2 is greater
} else {
choice = 0; // Both numbers are equal
}

// Use a switch statement to display the result


switch (choice) {
case 1:
printf("The maximum number is %.2lf\n", num1);
break;
case 2:
printf("The maximum number is %.2lf\n", num2);
break;
case 0:
printf("Both numbers are equal.\n");
break;
default:
printf("Invalid choice.\n");
}

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; }

void swap(int x, int y)


{
int temp;

3 Construct a function to swap two numbers. temp = x;


x = y;
y = temp;

printf("\nAfter swapping: a = %d and b = %d\n", x, y);


}
long int multiplyNumbers(int n)
{
if (n>=1)
Write a C function for factorial of the given
4 return n*multiplyNumbers(n-1);
number. else
return 1;
}
Show the output of the following program.
#include<stdio.h>
#include<string.h>
int main ()
{
5 char str1[20] = "C Program"; C Practicals
char str2[20] = "C Practicals";
printf("%s\n", strcpy(strcat(str1, str2), str2));
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

// Calculate EMI using the formula


double emi = (principal * interest * pow(1 + interest, n)) / (pow(1 + interest, n) - 1);

return emi;
}

int main() {
double principal = 25000; // Loan amount
double rate = 8; // Annual interest rate
int time = 5; // Loan tenure in years

// Calculate EMI using the calculateEMI function


double emi = calculateEMI(principal, rate, time);

printf("Loan Amount: %.2f\n", principal);


printf("Annual Interest Rate: %.2f%%\n", rate);
printf("Loan Tenure: %d years\n", time);
printf("EMI: %.2f\n", emi);

return 0;
}
8 #include <stdio.h>

Construct a program to count total number int main() {


int n; // Size of the array
of positive elements in an array. int count = 0; // Initialize count to 0

printf("Enter the size of the array: ");


scanf("%d", &n);

// Check for valid array size


if (n <= 0) {
printf("Invalid array size. Please enter a positive size.\n");
return 1; // Exit with an error code
}

int array[n]; // Declare an array of size 'n'

// Input the elements of the array


printf("Enter %d elements:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &array[i]);
}
// Count positive elements
for (int i = 0; i < n; i++) {
if (array[i] > 0) {
count++;
}
}

printf("Total number of positive elements in the array: %d\n", count);

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]);
}

printf("String in lowercase: %s\n", inputString);

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.

3 Show the output of the following program 30

# 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;

printf("%c\t%c", *(p + 3),s[1]);

}
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>

void swap(int a, int b) {


int temp = a;
a = b;
b = temp;
}

int main() {
int x = 5;
int y = 10;

printf("Before calling the swap function: x = %d, y = %d\n", x, y);

swap(x, y);

printf("After calling the swap function: x = %d, y = %d\n", 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

// Allocate memory for an array of integers


int *dynamicArray = (int *)malloc(n * sizeof(int));

if (dynamicArray == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

// Initialize the array


for (int i = 0; i < n; i++) {
dynamicArray[i] = i * 10;
}

// Print the values in the dynamically allocated array


for (int i = 0; i < n; i++) {
printf("dynamicArray[%d] = %d\n", i, dynamicArray[i]);
}

// Deallocate the memory using free


free(dynamicArray);

// Check if the pointer is now NULL after deallocation


if (dynamicArray == NULL) {
printf("Memory has been deallocated.\n");
}

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>

// Define a structure for a point


struct Point {
int x;
int y;
};

int main() {
11 Define structure with an example. // Declare a variable of type Point
struct Point p1;

// Assign values to the structure members


p1.x = 10;
p1.y = 20;

// Access and print the values


printf("Coordinates of p1: x = %d, y = %d\n", p1.x, p1.y);

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;

unit a, b; instead of writing: int a,b;


An enum (short for "enumeration") is a user-defined data type that consists of a set of named
integer constants. It's used to create symbolic names for a list of related constants, making the
code more readable and self-explanatory. Enumerations provide a way to associate
meaningful names with integer values, improving code clarity and maintainability.

16 Explain Enum in C. enum enumeration_name {


constant1,
constant2,
constant3,
// ...
};
Grouping Related Data
Complex Data Types
Data Organization
17 Explain the need of structure. Parameter Passing
Code Maintainability
Abstraction
#include <stdio.h>

// Define a structure to hold laptop information


struct Laptop {
char brand[50]; // Brand name (assuming a maximum of 49 characters)
float sizeInInches; // Size in inches
double price; // Price in dollars
};

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

// Print the laptop information


printf("Laptop Information:\n");
printf("Brand: %s\n", myLaptop.brand);
printf("Size (in inches): %.1f\n", myLaptop.sizeInInches);
printf("Price: $%.2f\n", myLaptop.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;

printf("Today is day number %d\n", today);


return 0;
}
#include <stdio.h>

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;
}

(PART B – 13 Marks - Either Or Type)

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

Basic data types int, char, float, double

Enumeration data type Enum

Derived data type pointer, array, structure, union

Void data type Void

1. BASIC DATA TYPES IN C LANGUAGE:

INTEGER DATA TYPE:


 Integer data type allows a variable to store numeric values.
 “int” keyword is used to refer integer data type.
 The storage size of int data type is 2 or 4 or 8 byte.
 It varies depend upon the processor in the CPU that we use.

FLOATING POINT DATA TYPE:

Floating point data type consists of 2 types. They are,

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.

CHARACTER DATA TYPE:

 Character data type allows a variable to store only one character.


 Storage size of character data type is 1. We can store only one character using character
data type.
 “char” keyword is used to refer character data type.
 For example, ‘A’ can be stored using char data type. You can’t store more than one
character using char data type.

MODIFIERS IN C LANGUAGE:

 The amount of memory space to be allocated for a variable is derived by modifiers.


 Modifiers are prefixed with basic data types to modify (either increase or decrease) the
amount of storage space allocated to a variable.
 For example, storage space for int data type is 4 byte for 32 bit processor. We can in-
crease the range by using long int which is 8 byte. We can decrease the range by using
short int which is 2 byte.

There are 5 modifiers available in C language. They are,


1. short
2. long
3. signed
4. unsigned

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

2. Real or Floating point constants

3. Octal & Hexadecimal constants

4. Character constants

5. String constants

6. Backslash character constants

Constant type data type (Example)


int (53, 762, -478 etc )

unsigned int (5000u, 1000U etc)

long int, long long int

Integer constants (483,647 2,147,483,680)


float (10.456789)

Real or Floating point constants doule (600.123456789)


Octal constant int (Example: 013 /*starts with 0 */)
Hexadecimal constant int (Example: 0x90 /*starts with 0x*/)
character constants char (Example: ‘A’, ‘B’, ‘C’)
string constants char (Example: “ABCD”, “Hai”)

RULES FOR CONSTRUCTING C CONSTANT:

1. INTEGER CONSTANTS IN C:

 An integer constant must have at least one digit.


 It must not have a decimal point.
 It can either be positive or negative.
 No commas or blanks are allowed within an integer constant.
 If no sign precedes an integer constant, it is assumed to be positive.
 The allowable range for integer constants is -32768 to 32767.

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.

3. CHARACTER AND STRING CONSTANTS IN C:


 A character constant is a single alphabet, a single digit or a single special symbol en-
closed within single quotes.
 The maximum length of a character constant is 1 character.
 String constants are enclosed within double quotes.

4. BACKSLASH CHARACTER CONSTANTS IN C:


 There are some characters which have special meaning in C language.
 They should be preceded by backslash symbol to make use of special function of them.
 Given below is the list of special characters and their purpose.
Backslash_character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\” Double quote
\’ Single quote
\\ Backslash
\v Vertical tab
\a Alert or bell
\? Question mark
\N Octal constant (N is an octal constant)
\XN Hexadecimal constant (N – hex.dcml cnst)

#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++;
}

printf("\nThe number of digits in an integer is : %d",count);


return 0;
}
3 Explain various types of Arithmetic, 1. ARITHMETIC OPERATORS IN C:
Relational & Logical Operators with
Examples. C Arithmetic operators are used to perform mathematical calculations like addition, subtrac-
tion, multiplication, division and modulus in C programs.

Arithmetic Operators/Operation Example

+ (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 greater than y)

< x < y (x is less than y)

>= x >= y (x is greater than or equal to y)

<= x <= y (x is less than or equal to y)

== 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

&& (logical AND) (x>5)&&(y<5)

It returns true when both conditions are true

|| (logical OR) (x>=10)||(y>=10)

It returns true when at-least one of the condition is true

! (logical NOT) !((x>5)&&(y<5))

It reverses the state of the operand “((x>5) && (y<5))”

If “((x>5) && (y<5))” is true, logical NOT operator makes it false

# 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;

// initialize first and second terms


int t1 = 0, t2 = 1;

// initialize the next term (3rd term)


int nextTerm = t1 + t2;

// get no. of terms from user


printf("Enter the number of terms: ");
scanf("%d", &n);

// print the first two terms t1 and t2


printf("Fibonacci Series: %d, %d, ", t1, t2);

// print 3rd to nth terms


for (i = 3; i <= n; ++i) {
printf("%d, ", nextTerm);
t1 = t2;
t2 = nextTerm;
nextTerm = t1 + t2;
}

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;
}

#include <stdio.h>int main()

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") :

(year%400==0)?printf("LEAP YEAR"):printf("COMMON 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));

printf("WEEKS: %d\n", weeks);


printf("DAYS: %d", days);

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;

printf (“ enter a number:”);

scanf(“%d”,&n);

If (n>10)

Printf(“ number is greater”);

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{ 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.

Example:- /* To check a number is eve or odd */

void main()
{

int n;

printf (“enter a number:”);

sacnf (“%d”, &n);

If (n%2==0)

printf (“even number”);

else

printf(“odd number”);

Output: enter a number:121

odd number

Nesting of if ...else

When there are another if else statement in if-block or else-block, then it is called

Nesting of if-else statement.

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);

/* Calculate electricity bill according to given conditions */


if(unit <= 100)
{
amt = unit *2;
}
else if((unit>100)&&(unit <= 300))
based on following conditions. {
(First 100 units Rs.2 per unit, unit 101 to amt = 200 + ((unit-100) * 3);
300 Rs 3 per unit, unit 301 to 500 Rs.4 per }
unit, above 500 units Rs 5 per unit) else if((unit >300)&&(unit<=400))
{
amt = 200+600 + ((unit-300) * 4);
}
else
{
amt = 200+600+800 + ((unit-400) * 5);
}

printf("Electricity Bill = Rs. %.2f",amt);

return 0;}

4 Construct a program to check the input #include <stdio.h>


entered by the user is palindrome or not int main() {
int n, reversed = 0, remainder, original;
Sample Input : 11 printf("Enter an integer: ");
Output: Palindrome Number scanf("%d", &n);
original = n;

// reversed integer is stored in reversed variable


while (n != 0) {
remainder = n % 10;
reversed = reversed * 10 + remainder;
n /= 10;
}

// palindrome if orignal and reversed are equal


if (original == reversed)
printf("%d is a palindrome.", original);
else
printf("%d is not a palindrome.", original);

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.

Difference between conditional and looping statement


Conditional statement executes only once in the program where as looping statements
executes repeatedly several number of time.

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

A do-while Loop in C is similar to a


while loop, except that a do-while loop is
execute at least one time.
A do while loop is a control flow
statement that executes a block of code at
least once, and then repeatedly executes
the block, or not, depending on a given
condition at the end of the block (in
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;

printf("Enter the value of N: ");


scanf("%d", &N);

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);

if (number % 3 == 0 && number % 9 == 0) {


sum += number;
}
}

printf("The sum of numbers divisible by 3 and 9 is: %d\n", sum);

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");

printf("Input the marks obtained in Physics :");


scanf("%d",&p);
printf("Input the marks obtained in Chemistry :");
scanf("%d",&c);
printf("Input the marks obtained in Mathematics :");
scanf("%d",&m);
printf("Total marks of Maths, Physics and Chemistry : %d\n",m+p+c);
printf("Total marks of Maths and Physics : %d\n",m+p);

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;

printf("Enter a number: ");


scanf("%d", &number);

if(number == 1 || number == 0){


printf("%d is a Perfect Square.", number);
flag=1;
}
Develop a C program to check whether
10 for(i = 2; i <= number/2; i++)
the given number is perfect square or not. {
if(number == i*i)
{
printf("%d is a Perfect Square.", number);
flag=1;
break;
}
}
if(flag == 0)
printf("%d is not a Perfect Square\n", number);

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

1. One Dimensional Array 2.Two dimensional array

One Dimensional array

Declaration of Array

Syn : data_type array_name[array_size];

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.

Declaration of two dimensional Arrays

Syn : 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;
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);

// asssigning elements to the matrix


printf("\nEnter matrix elements:\n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", &a[i][j]);
}

// printing the matrix a[][]


printf("\nEntered matrix: \n");
for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
printf("%d ", a[i][j]);
Construct a program to find the transpose if (j == c - 1)
2 printf("\n");
of the given matrix.
}

// computing the transpose


for (int i = 0; i < r; ++i)
for (int j = 0; j < c; ++j) {
transpose[j][i] = a[i][j];
}

// printing the transpose


printf("\nTranspose of the matrix:\n");
for (int i = 0; i < c; ++i)
for (int j = 0; j < r; ++j) {
printf("%d ", transpose[i][j]);
if (j == r - 1)
printf("\n");
}
return 0;
}
3 Explain function prototypes with proper Function Prototype or types of invoking function
Examples. A function may or may not accept any argument. It may or may not return any value. Based
on these facts, There are four different aspects of function calls.
1. function without arguments and without return value
void function_name(); Ex: void add();
#include <stdio.h>
void add();
int main()
{
add();
}
void add()
{
int a,b,c;
scanf("%d%d",&a,&b);
c=a+b;
printf("%d",c);
}
12 12
24

2. function without arguments and with return value


data_type function_name(); Ex: int add();

#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

3. function with arguments and without return value


void function_name(datatype var1,datatype var 2);
Ex: void add(int a, int b);

#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

4. function with arguments and with return value


datatype function_name(datatype var1,datatype var 2);
Ex: int add(int a, int b);
#include <stdio.h>
int add(int a, int b);
int main()
{
int a,b,c;
scanf("%d%d",&a,&b);
c=add(a,b);
printf("%d",c);
}
int add(int a,int b)
{

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;
}

6 Construct a program to compare the two #include <stdio.h>


strings without using built-in functions. #include <string.h>
int main()
{
char str1[30], str2[30]; int i;
gets(str1); gets(str2); i = 0;
while (str1[i] == str2[i] && str1[i] != '\0')
i++;
if (str1[i] > str2[i])
printf("Both strings are not same");
else if (str1[i] < str2[i])
printf("Both strings are not same");
else
printf("Both strings are same");
return 0;
}
#include <stdio.h>

int addWithCarry(int x, int y) {


int carry = 0; // Initialize carry to 0
int sum = 0; // Initialize sum to 0
int totalCarries = 0;

while (y != 0) {
// Calculate sum without considering carry
sum = x ^ y;

// Calculate carry for next step


carry = (x & y) << 1;

// Add sum and carry to get the final result


Write a C program for a function that x = sum;
accepts x = 89878, y = 73638. Calculate y = carry;
7 the sum and return the total number of // Count carries
carries. totalCarries++;
}

return totalCarries;
}

int main() {
int x = 89878;
int y = 73638;

int totalCarries = addWithCarry(x, y);

printf("Sum: %d\n", x);


printf("Total number of carries: %d\n", totalCarries);

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 ("Enter the size of the array\n");


scanf ("%d", &n);
int array[n];
printf ("Enter the elements\n");
for (i = 0; i < n; i++)
{
scanf ("%d", &array[i]);
}

printf ("The array elements are : \n");


for (i = 0; i < n; i++)
{
printf ("%d\t", array[i]);
}

printf ("\n");

largest1 = array[0];
largest2 = array[1];

if (largest1 < largest2)


{
temp = largest1;
largest1 = largest2;
largest2 = temp;
}

for (int i = 2; i < n; i++)


{
if (array[i] > largest1)
{
largest2 = largest1;
largest1 = array[i];
}
else if (array[i] > largest2 && array[i] != largest1)
{
largest2 = array[i];
}
}

printf ("The FIRST LARGEST = %d\n", largest1);


printf ("THE SECOND LARGEST = %d\n", largest2);

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);}

10 Construct a C program to sort elements of #include <stdio.h>


array in ascending order. void main()
{

int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);

printf("Enter the numbers \n");


for (i = 0; i < n; ++i)
scanf("%d", &number[i]);

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


{

for (j = i + 1; j < n; ++j)


{

if (number[i] > number[j])


{
a = number[i];
number[i] = number[j];
number[j] = a;

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;

printf("Enter array size [1-100]: ");


scanf("%d", &n);

printf("Enter array elements: ");


for(i=0; i<n; i++)scanf("%d", &a[i]);

printf("Enter element to search: ");


scanf("%d",&element);

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


{
if(a[i]==element)
{
printf("%d found at position %d", element, i+1);
return 0;
}
}

printf("%d not found.", element);


return 0;
}

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.

Algorithm for Selection Sort:

Step 1 − Set min to the first location

Step 2 − Search the minimum element in the array

Step 3 – swap the first location with the minimum value in the array

Step 4 – assign the second element as min.

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=&num;

Pointer Operator

* Gives Value stored at particular address

& Gives Address of Variable.


#include<stdio.h>
void main()
{
int var=10; int *p; p=&var;
printf("Value of var is %d",var);
printf("\nAddress of n is %x",&var);
printf("\nAddres of pointer is %x",p);
printf("\nvalue stored in pointer is %d",*p);
}
Incrementing / Decrementing Pointer :
1. Incrementing / Decrementing Pointer is generally used in array because we have
contiguous memory in array and we know the contents of next memory location.
2. Incrementing / Decrementing Pointer Variable Depends Upon data type of the Pointer
variable.

Formula : ( After incrementing / Decrementing)


new value = current address + i * size_of(data type)
Three Rules should be used to increment / Decrement pointer –
Address + 1 = Address Address - 1 = Address
Address++ = Address Address-- = Address
++Address = Address --Address = Address

Advantages:

A pointer enables us to access a variable that is defined outside the function.


Pointers are more efficient in handling the data tables.
Pointers reduce the length and complexity of a program.
They increase the execution speed.
The use of a pointer array to character strings results in saving of data storage space in
memory.

#include <stdio.h>

int main()
{
int x, y, *a, *b, temp;

printf("Enter the value of x and y\n");


scanf("%d%d", &x, &y);

printf("Before Swapping\nx = %d\ny = %d\n", x, y);


Construct a program in C to swap two
4
numbers using pointers. a = &x;
b = &y;

temp = *b;
*b = *a;
*a = temp;

printf("After Swapping\nx = %d\ny = %d\n", x, y);

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:

The value of the variable is passed to the function as parameter.


The value of the actual parameter cannot be modified by formal parameter.
Different Memory is allocated for both actual and formal parameters. Because, value of
actual parameter is copied to formal parameter.

Actual parameter – This is the argument which is used in function call.


Formal parameter – This is the argument which is used in function definition

#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); }

void swap(int a, int b)


{ int tmp;
tmp = a;
a = b;
b = tmp;
}
OUTPUT
values before swap m = 22 and n = 44
values after swap m = 22 and n = 44

2. PASS BY REFERENCE:

The address (&) of the variable is passed to the function as parameter.


The value of the actual parameter can be modified by formal parameter.
Same memory is used for both actual and formal parameters since only address is used by
both parameters.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
int main()
{
int m = 22, n = 44;
// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
printf("\n values after swap a = %d \nand b = %d", m, n); }

void swap(int *a, int *b)


{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;}
OUTPUT
values before swap m = 22 and n = 44
values after swap a = 44 and b = 22
6 Construct a program to copy a String one #include<stdio.h>
to other using Pointers. void copy_string(char*, char*);
int main()
{
char source[100], target[100];
printf("Enter source string:");
fgets(source,100,stdin);
copy_string(target, source);
printf("Target string is:%s", target);
return 0;
}

void copy_string(char *target, char *source)


{
while(*source)
{
*target = *source;
source++;
target++;
}
*target = '\0';
}
Enter source string:saveetha
Target string is:saveetha
7 Construct a program to count total number
of even elements in the following array #include <stdio.h>
#include<stdlib.h>
3,5,32,21,20 using malloc(). int main()
{
int i, n=5, even,*ptr;
ptr=(int*)malloc(n*sizeof(int));
ptr[0]=3;
ptr[1]=5;
ptr[2]=2;
ptr[3]=21;
ptr[4]=20;
even = 0;
for(i=0; i<n; i++)
{
if(ptr[i]%2 == 0)
{
even++;
}
}
printf("Total even elements: %d\n", even);
return 0;
}
#include <stdio.h>

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;

// Calculate the sum


for (int i = 0; i < n; i++) {
sum += *ptr;
write a c program to find sum and average ptr++; // Move the pointer to the next element
8 }
in the range from 14 to 17 using pointer.
// Calculate the average
average = (double)sum / n;

printf("Numbers: ");
for (int i = 0; i < n; i++) {
printf("%d ", numbers[i]);
}

printf("\nSum: %d\n", sum);


printf("Average: %.2f\n", average);

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;

// Print the reversed string


printf("Reversed string: ");
while (ptr >= str) {
putchar(*ptr); // Output the character pointed to by ptr
ptr--; // Move the pointer backward
}

printf("\n");

return 0;
}
#include <stdio.h>

// Function to calculate the area of a rectangle using pointers


void calculateRectangleArea(float length, float width, float *area) {
*area = length * width;
}

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);

printf("Enter the width of the rectangle: ");


scanf("%f", &width);

// Call the function to calculate the area


calculateRectangleArea(length, width, &area);

printf("The area of the rectangle is: %.2f\n", area);

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.

syntax : struct <structure name or tagname>


{
datatype member1;
datatype member2;
};

Example : struct book


{
int pages;
char bookname[10];
char author[20];
float price;
};

Accessing Structure Data members:

Structure Members can be accessed through structure variable using the dot or period
operator

Creation of Structure Variable:

Syntax :
struct structurename variable1, variable2, ..... variable n;

Example
Struct book b1; /* b1 is a structure variable name */

Accessing Structure Data members:

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);
}

4 Construct a program to read (reg-no ,3 #include <stdio.h>


subject marks) and store the details of 5 union student
{
students and calculate the Total and int roll_no;
Average using union. int phy;
int chem;
int math;
float total;
float percentage;
};
int main()
{
union student s[5];
for(int i=0; i<5; i++)
{
scanf("%d %d %d %d", &s[i].roll_no, &s[i].phy, &s[i].chem, &s[i].math);
}
for(int i=0; i<5; i++)
{
s[i].total = s[i].phy + s[i].chem + s[i].math;
s[i].percentage = s[i].total/3;
}
printf("Student Details are\n");
for(int i=0; i<5; i++)
{
printf("%d %d %d %d %.2f %.2f\n", s[i].roll_no, s[i].phy, s[i].chem,
s[i].math, s[i].total, s[i].percentage);
}
return 0;
}

5 Construct a program to read and print a 10 #include<stdio.h>


Employee’s Details using array of struct employee
{
Structure. char name[20];
char designation[20];
int salary;
}s[10];
int main()
{
int i;
//Accepting information
printf("Enter details of 10 employees:\n");
for(i=0;i<10;i++)
{
printf("Enter name :");
scanf("%s", s[i].name);
printf("Enter designation :");
scanf("%s", s[i].designation);
printf("Enter salary :");
scanf("%d", &s[i].salary);
}
//displaying information
printf("\nThe details of emplyoees are :\n");
for(i=0;i<10;i++)
{
printf("%s\t%s\t%d", s[i].name, s[i].designation, s[i].salary);
}
return 0;
}

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;
};

2.Declaring union using normal variable:


union student report;

3.Initializing union using normal variable:


union student report = {100, “Mani”, 99.5};

4.Accessing union members using normal variable:


report.mark;

#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( ) {

union Data data;

data.i = 10;
printf( "data.i : %d\n", data.i);

data.f = 220.5;
printf( "data.f : %f\n", data.f);

strcpy( data.str, "C Programming");


printf( "data.str : %s\n", data.str);

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;

// Input course details for 3 courses


for (int i = 0; i < 3; i++) {
printf("Enter details for Course %d:\n", i + 1);
printf("Course Name: ");
scanf(" %[^\n]", courses[i].name);

printf("Department: ");
scanf(" %[^\n]", courses[i].department);

printf("Credits: ");
scanf("%d", &courses[i].credits);

if (courses[i].credits > maxCredits) {


maxCredits = courses[i].credits;
maxCreditCourse = courses[i];
}
}

// 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);
}

printf("Course Suggestion (Highest Credit):\n");


printf("Course Name: %s\n", maxCreditCourse.name);
printf("Department: %s\n", maxCreditCourse.department);
printf("Credits: %d\n", maxCreditCourse.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;
};

// Function to check if a year is a leap year


int isLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
return 1; // Leap year
} else {
return 0; // Not a leap year
}
}

int main() {
struct Date date;

printf("Enter the date (dd mm yyyy): ");


scanf("%d %d %d", &date.day, &date.month, &date.year);

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>

// Define a structure for representing a point


typedef struct {
int x;
int y;
} Point;

int main() {
// Declare variables of type Point
Point p1, p2;

// Initialize the points


p1.x = 5;
p1.y = 10;

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;
}

(PART C – 15 Marks - Either Or Type)

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;

marks>=70 print FIRST CLASS WITH scanf("%d",&marks);


DISTINCTION
if (marks>=70)
60>= marks <70 print FIRST CLASS {
printf("...FIRST CLASS WITH DISTINCTION...");
}
else if( (marks<70) && (marks>=60) )
{
printf("...FIRST CLASS...");
}
else if( (marks<60) && (marks>=50) )
50>= marks <60 print SECOND CLASS {
40>= marks <50 print THIRD CLASS printf("...SECOND CLASS...");
}
marks<40 print U r Failed...Better luck else if( (marks<50) && (marks>=40) )
next time {
printf("...THIRD CLASS...");
}
else
{
printf("...U r Falied...Better luck next time");
}
}
#include <stdio.h>

void swap(int *a, int *b) {


if (a != b) { // Check if the numbers are different
*a = *a ^ *b; // XOR operation to swap the values
*b = *a ^ *b;
*a = *a ^ *b;
}
}

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);

printf("Before swapping: num1 = %d, num2 = %d\n", num1, num2);

swap(&num1, &num2);

printf("After swapping: num1 = %d, num2 = %d\n", 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;

// Input the range values M and N


printf("Enter the range (M and N, where N > M): ");
scanf("%d %d", &M, &N);

// Check for valid input constraints


if (M < 1 || N < 1 || N <= M || M > 100 || N > 100) {
printf("Invalid input. Please follow the constraints.\n");
return 1;
}

// Calculate the sum of numbers within the range


for (int i = M; i <= N; i++) {
sum += i;
}

// Print the sum


printf("The sum of numbers from %d to %d is: %d\n", M, N, sum);

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;

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


result = result*c;
return ( result );
}
2 #include <stdio.h>
Construct a menu-based program to find void main()
{
the area of different shapes (triangle, int fig_code;
rectangle, circle & Square) using switch float side, base, length, breadth, height, area, radius;
statements. printf("-------------------------\n");
printf(" 1 --> Circle\n");
printf(" 2 --> Rectangle\n");
printf(" 3 --> Triangle\n");
printf(" 4 --> Square\n");
printf("-------------------------\n");
printf("Enter the Figure code\n");
scanf("%d", &fig_code);
switch(fig_code)
{
case 1:
printf("Enter the radius\n");
scanf("%f", &radius);
area = 3.142 * radius * radius;
printf("Area of a circle = %f\n", area);
break;
case 2:
printf("Enter the breadth and length\n");
scanf("%f %f", &breadth, &length);
area = breadth * length;
printf("Area of a Reactangle = %f\n", area);
break;
case 3:
printf("Enter the base and height\n");
scanf("%f %f", &base, &height);
area = 0.5 * base * height;
printf("Area of a Triangle = %f\n", area);
break;
case 4:
printf("Enter the side\n");
scanf("%f", &side);
area = side * side;
printf("Area of a Square=%f\n", area);
break;
default:
printf("Provide valid value\n");
break; }

#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(" ");
}

// Print 'A' character


for (j = 1; j <= rows; j++) {
printf("A");
}

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;
}

Enter a line of Text :


I am '30' years old

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;

printf("Enter a number: ");


scanf("%d", &number);

int sum = sumOfDigits(number);


printf("The sum of the digits of %d is: %d\n", number, sum);

return 0;
}

4 (i) Construct a C program to calculate the (i) #include <stdio.h>


power for 8,4 using recursion. int power(int n1, int n2);
int main() {
(ii) Write a program to print odd/even int base, a, result;
numbers in given range based on lower printf("Enter base number: ");
limit scanf("%d", &base);
value/starting value using recursion. printf("Enter power number(positive integer): ");
scanf("%d", &a);
result = power(base, a);
printf("%d^%d = %d", base, a, result);
return 0;
}

int power(int base, int a) {


if (a != 0)
return (base * power(base, a - 1));
else
return 1;
}
(ii) #include <stdio.h>

/* Function declaration */
void printEvenOdd(int cur, int limit);

int main()
{
int lowerLimit, upperLimit;

// Input lower and upper limit from user


printf("Enter lower limit: ");
scanf("%d", &lowerLimit);
printf("Enter upper limit: ");
scanf("%d", &upperLimit);
printf("Even/odd Numbers from %d to %d are: ", lowerLimit, upperLimit);
printEvenOdd(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;

printf("%d, ", cur);

// Recursively call to printEvenOdd to get next value


printEvenOdd(cur + 2, limit);
}

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.

4. And we go on repeating this, until the array is sorted.

#include <stdio.h>
int main()
{
int n, i, j, temp;
int arr[64];

printf("Enter number of elements\n");


scanf("%d", &n);

printf("Enter %d integers\n", n);


for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 1 ; i <= n - 1; i++)
{
j = i;
while ( j > 0 && arr[j-1] > arr[j])
{
temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
j--;
}
}
printf("Sorted list in ascending order:\n");
for (i = 0; i <= n - 1; i++)
{
printf("%d\n", arr[i]);
}
return 0;
}
#include <stdio.h>
#include<stdlib.h>
int main()
{
int i, n, even,*ptr;
scanf("%d", &n);
ptr=(int*)malloc(n*sizeof(int));
for(i=0; i<n; i++)
{
scanf("%d", &ptr[i]);
}
Construct a program to count the total
number of even elements in an array using even = 0;
2 for(i=0; i<n; i++)
Dynamic Memory Allocation.
{
if(ptr[i]%2 == 0)
{
even++;
}

printf("Total even elements: %d\n", even);


return 0;
}

3 (i) Develop a C program to add value 12 (i) #include <stdio.h>


to list which already have 10 in that using
// Function to find the sum of digits using recursion
int sumOfDigits(int number) {
realloc () and print that value. if (number == 0) {
(ii) Write a 'C' program to reverse a float return 0; // Base case: When the number becomes 0, the sum is 0.
array's elements using dynamic memory } else {
allocation. // Recursively find the sum of digits for the remaining part of the number.
return (number % 10) + sumOfDigits(number / 10);
}
}

int main() {
int number;

printf("Enter a number: ");


scanf("%d", &number);
int sum = sumOfDigits(number);

printf("The sum of the digits of %d is: %d\n", number, sum);

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;
}

list[0] = 10; // Initialize the list with the value 10


int size = 1; // Current size of the list

// Use realloc to add the value 12


size++; // Increase the size of the list
list = (int *)realloc(list, size * sizeof(int));

if (list == NULL) {
printf("Memory reallocation failed.\n");
free(list);
return 1;
}

list[size - 1] = 12; // Add the value 12

// Print the values in the list


printf("List values: ");
for (int i = 0; i < size; i++) {
printf("%d ", list[i]);
}
printf("\n");

// Free the dynamically allocated memory


free(list);

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);

// Check if the size is valid


if (size <= 0) {
printf("Invalid size. Please enter a positive size.\n");
return 1;
}

// Dynamically allocate memory for the float array


float *arr = (float *)malloc(size * sizeof(float);

// Check if memory allocation was successful


if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

// Input the elements of the float array


printf("Enter %d float elements:\n", size);
for (int i = 0; i < size; i++) {
scanf("%f", &arr[i]);
}

// Reverse the elements of the float array


for (int i = 0; i < size / 2; i++) {
float temp = arr[i];
arr[i] = arr[size - 1 - i];
arr[size - 1 - i] = temp;
}

// Print the reversed float array


printf("Reversed float array:\n");
for (int i = 0; i < size; i++) {
printf("%.2f ", arr[i]);
}
printf("\n");

// Free the dynamically allocated memory


free(arr);

return 0;
}

(ii) #include <stdio.h>


#include <stdlib.h>

int main() {
int n;

// Prompt the user for the number of elements in the array


printf("Enter the number of elements in the array: ");
scanf("%d", &n);

// Check if the size is valid


if (n <= 0) {
printf("Invalid size. Please enter a positive size.\n");
return 1;
}

// Dynamically allocate memory for the array


int *arr = (int *)calloc(n, sizeof(int);

// Check if memory allocation was successful


if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}

// Input the elements of the array


printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

// Count the total number of even elements


int evenCount = 0;
for (int i = 0; i < n; i++) {
if (arr[i] % 2 == 0) {
evenCount++;
}
}

// Print the count of even elements


printf("Total number of even elements: %d\n", evenCount);

// Free the dynamically allocated memory


free(arr);

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;

d3.feet= d3.feet + d3.inch/12; //1 feet has 12 inches


d3.inch= d3.inch%12;

printf("Total distance- Feet: %d, Inches: %d",d3.feet,d3.inch);


}

int main()
{
struct distance d1,d2;
printf("Enter first distance in feet & inches:");
scanf("%d%d",&d1.feet, &d1.inch);

printf("Enter second distance in feet & inches:");


scanf("%d%d",&d2.feet, &d2.inch);
/*add two distances*/
addDistance(d1,d2);
return 0;
}

2 Build a structure for Electricity Bill (use #include <stdio.h>


service no, name, previous reading, struct ebbill
{
current reading, unit consumption & int serviceno;
amount as data members) char servicename[20];
(units<=100 per unit Rs.2.00, units>100 int pr;
and unit<=300 Rs=3.00 per unit, above int cr;
300 units Rs.5.00 per unit) int uc;
float amount;
}eb;
int main()
{
scanf("%d%s%d%d",&eb.serviceno,eb.servicename,&eb.cr,&eb.pr);
eb.uc=eb.cr-eb.pr;
if(eb.uc<=100)
{
eb.amount=eb.uc*2.00;
}
else if(eb.uc>100 && eb.uc<=300)
{
eb.amount=200+((eb.uc-100)*3);
}
else
{
eb.amount=200+600+((eb.uc-300)*5);
}
printf("service number:%d",eb.serviceno);
printf("\nservice name:%s",eb.servicename);
printf("\nunit consumption:%d",eb.uc);
printf("\namount:%.2f",eb.amount);
return 0;
}
3 Build a structure program to read (empno, #include <stdio.h>
dept & basic pay) and store the data of 3
// Define a structure for Salary
employees and calculate their Gross struct Salary {
Salary (da =10% and HRA=30% from float basicPay;
BP) using nested structures. float da;
float hra;
float grossSalary;
};

// Define a structure for Employee


struct Employee {
int empno;
char dept[50];
struct Salary salary;
};

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("Employee Number: ");


scanf("%d", &employees[i].empno);

printf("Department: ");
scanf("%s", employees[i].dept);

printf("Basic Pay: ");


scanf("%f", &employees[i].salary.basicPay);

// Calculate DA (10%) and HRA (30%) from Basic Pay


employees[i].salary.da = 0.10 * employees[i].salary.basicPay;
employees[i].salary.hra = 0.30 * employees[i].salary.basicPay;

// Calculate Gross Salary


employees[i].salary.grossSalary = employees[i].salary.basicPay + employees[i].salary.da
+ employees[i].salary.hra;
}

// Display employee details and Gross Salary


printf("\nEmployee Details and Gross Salary:\n");
for (int i = 0; i < 3; i++) {
printf("Employee Number: %d\n", employees[i].empno);
printf("Department: %s\n", employees[i].dept);
printf("Basic Pay: %.2f\n", employees[i].salary.basicPay);
printf("DA: %.2f\n", employees[i].salary.da);
printf("HRA: %.2f\n", employees[i].salary.hra);
printf("Gross Salary: %.2f\n\n", employees[i].salary.grossSalary);
}

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;
}

You might also like