0% found this document useful (0 votes)
9 views63 pages

C CPP Language Complete Practice Assignment

C and C++ Programming 100+ questions with code and output divided in multiple assignments with the real output snapshots

Uploaded by

tarlanavikas12
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)
9 views63 pages

C CPP Language Complete Practice Assignment

C and C++ Programming 100+ questions with code and output divided in multiple assignments with the real output snapshots

Uploaded by

tarlanavikas12
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/ 63

INDEX

TITLE…………………………………………………………………………………………… PG. NO.


1. ASSIGNMENT 1………………………………………………………………………………. 3-8
2. ASSIGNMENT 2………………………………………………………………………………. 9-16
3. ASSIGNMENT 3……………………………………………………………………………… 17-24
4. ASSIGNMENT 4……………………………………………………………………………….24-29
5. ASSIGNMENT 5……………………………………………………………………………….30-33
6. ASSIGNMENT 6……………………………………………………………………………….34-41
7. ASSIGNMENT 7……………………………………………………………………………….42-49
8. ASSIGNMENT CPP-1….…………………………………………………………………….50-58
9. ASSIGNMENT CPP-2.……………………………………………………………………….59-64
ASSIGNMENT 1
DATE: 13-08-2024

1.Write a C Program using decision-making constructs.

a. Write a C program to calculate the area and perimeter of a circle given


its radius.
CODE:
#include <stdio.h>
#define pi 3.14
int main(){
float radius,perimeter,area;
printf("Enter the radius ");
scanf("%f",&radius);
perimeter = 2*pi*radius;
area = pi*radius*radius;
printf("Perimeter of the circle is %f and area is %f ",perimeter,area);
return 0;
}
OUTPUT:

b. Write a C program to calculate the simple interest given the principal,


rate of interest, and time period.
Hint: Simpleinterest = PRT/100
CODE:
#include <stdio.h>
int main(){
int principal,rate,time,si;
printf("Enter the principal amount: ");
scanf("%d",&principal);
printf("Enter the rate percentage: ");
scanf("%d",&rate);
printf("Enter the time period: ");
scanf("%d",&time);
si = principal*rate*time/100;
printf("Simple interest for the following details is %d",si);
return 0;
}
OUTPUT:

c. Write a C program to convert temperature from Celsius to Fahrenheit.


Hint: fahrenheit = (celsius * 9/5) + 32

CODE:
#include <stdio.h>
int main(){
float tempc,tempf;
printf("Enter the temperature in celsius: ");
scanf("%f",&tempc);
tempf = ((9/5)*tempc)+32;
printf("The temperature in fahrenheit is %f",tempf);
return 0;
}
OUTPUT:

d. Write a C program to calculate the sum and average of five numbers.


CODE:
#include <stdio.h>
int main(){
float a,b,c,d,e,sum,avg;
printf("Enter number 1: ");
scanf("%f",&a);
printf("Enter number 2: ");
scanf("%f",&b);
printf("Enter number 3: ");
scanf("%f",&c);
printf("Enter number 4: ");
scanf("%f",&d);
printf("Enter number 5: ");
scanf("%f",&e);
sum = a + b + c + d + e;
avg = sum/5;
printf("Sum of given five numbers is %f and average is %f",sum,avg);
return 0;
}
OUTPUT:

e. Develop a C program that can evaluate simple mathematical


expressions involving basic arithmetic operations: addition,
subtraction, multiplication, and division.
Expression: "3 + 5 * 2 - 8 / 4"
OutPut:
Expression: "3 + 5 * (2 - 8) /4"
OutPut:
Expression: "((a/b)*b)+(a%b)"
OutPut:
CODE:
#include <stdio.h>
int main(){
int a,b;
float sol1,sol2,sol3;
sol1 = (3 + 5 * 2 - 8 / 4);
sol2 = (3 + 5 *(2 - 8)/ 4);
printf("Answer of (3+5*2-8/4) is %f",sol1);
printf("\nAnswer of (3+5*(2-8)/4) is %f",sol2);
printf("\nEnter the value of a: ");
scanf("%d",&a);
printf("Enter the value of b: ");
scanf("%d",&b);
sol3 = ( ( a / b ) * b ) + ( a % b );
printf("Answer of ((a/b)*b)+(a%b) is %f",sol3);
return 0;
}
OUTPUT:

f. Imagine you are an employee receiving a monthly salary, and you want
to calculate your net salary after a fixed tax deduction. Write a C
program that calculates the net salary by deducting 14% tax from the
gross salary.
Input: Gross salary:5000
Output: Taxes withheld: 700.00
Net salary: 4300.00
CODE:

#include <stdio.h>
int main(){
float grosal,taxrate,taxwithheld,netsal;
taxrate = 0.14;
printf("Enter the gross salary: ");
scanf("%f",&grosal);
taxwithheld = grosal*taxrate;
netsal = grosal-taxwithheld;
printf("Taxes with held: %f\n",taxwithheld);
printf("Net Salary: %f",netsal);
return 0;
}
OUTPUT:

g. Imagine you are tasked with developing a simple C program for a


university's student management system. The program needs to read
and print student details. Each student has the following information:
- Name (a string of up to 50 characters)
- Roll number (an integer)
- Gender (a character ‘M’ or “F’)
- CGPA (a float representing their average marks in 3 subjects)

Your task is to write a C program that:

1. Prompts the user to enter the details of a student (name, roll number,
gender and marks in 3 subjects).
2. Reads the entered details.
3. Prints the entered details in a formatted manner.

Write a C program that implements the described functionality. Ensure


that the program uses appropriate data types and formatting for reading
and printing the student details.

CODE:
#include <stdio.h>
int main() {
char name[50];
int roll, m1, m2, m3;
char gender;
float cgpa;
printf("Enter the student's name: ");
scanf("%s", name);
printf("Enter the roll number: ");
scanf("%d", &roll);
printf("Enter the gender (M/F): ");
scanf(" %c", &gender);
printf("Enter marks of subject1, subject2, subject3 respectively: ");
scanf("%d", &m1);
scanf("%d", &m2);
scanf("%d", &m3);
cgpa = (m1 + m2 + m3) / 30.0;
printf("\nStudent Details:\n");
printf("Name: %s\n", name);
printf("Roll no: %d\n", roll);
printf("Gender: %c\n", gender);
printf("CGPA: %.2f\n", cgpa);
return 0;
}
OUTPUT:
ASSIGNMENT 2
DATE: 10-08-2024

Write a C Program using decision-making constructs.

a. Calculate the roots of a quadratic equation ax^2 + bx + c = 0.

CODE:
#include <stdio.h>
#include <math.h>
int main(){
int a,b,c;
float d,r1,r2;
printf("Enter the coefficient of x2: ");
scanf("%d",&a);
printf("Enter the coefficient of x: ");
scanf("%d",&b);
printf("Enter the constant term: ");
scanf("%d",&c);
d = (b*b - 4*a*c);
if(d>0){
r1 = (-b + sqrt(d)/(2 * a));
r2 = (-b - sqrt(d)/(2 * a));
printf("The roots of quadratic equation are: %.2f and %.2f ",r1,r2);
}
else if(d==0){
r1 = (-b)/(2 * a);
r2 = (-b)/(2 * a);
printf("The roots of quadratic equation are: %.2f and %.2f ",r1,r2);
}
else{
printf("Roots are imaginary");
}
return 0;
}

OUTPUT:
b. In a country there is a policy that for every new born child government
will give reward amount based on gender. If the new born is a baby boy
then reward amount is ten thousand and if the new born is a baby girl
then reward amount is fifty thousand. Also, if he/she is born in a leap
year then both will get same amount i.e., sixty thousand. Write C a
program that prompts the user to input date of birth (day, month and
year) of a child and determine how much amount government will give.

CODE:
#include <stdio.h>

int main() {
int day, month, yr;
char gender;

printf("Enter day of birth: ");


scanf("%d", &day);
printf("Enter month of birth: ");
scanf("%d", &month);
printf("Enter year of birth: ");
scanf("%d", &yr);

printf("Enter gender of the child (M for male, F for female): ");


scanf(" %c", &gender);

int isLeapYr = 0;
if (yr % 4 == 0) {
if (yr % 100 == 0) {
if (yr % 400 == 0)
isLeapYr = 1;
} else {
isLeapYr = 1;
}
}
int rewardamt;
if (isLeapYr) {
rewardamt = 60000;
} else {
if (gender == 'M' || gender == 'm') {
rewardamt = 10000;
} else if (gender == 'F' || gender == 'f') {
rewardamt = 50000;
} else {
printf("Invalid gender input.\n");
return 1;
}
}

printf("The reward amount is: %d\n", rewardamt);

return 0;
}

OUTPUT:

c. Write a C program that calculates the Body Mass Index (BMI) of a


person and categorizes it. The program should prompt the user to enter
their weight in kilograms and height in meters, then calculate the BMI
using the formula BMI = weight / (height * height). Finally, the program
should output the calculated BMI with two decimal places and display
the corresponding BMI category based on the following criteria:
i) BMI < 18.5: Underweight
ii)18.5 ≤ BMI < 24.9: Normal weight
iii) 25 ≤ BMI < 29.9: Overweight
iv) BMI ≥ 30: Obesity

CODE:
#include <stdio.h>

int main() {
float weight, height, bmi;

printf("Enter weight in kilograms: ");


scanf("%f", &weight);
printf("Enter height in meters: ");
scanf("%f", &height);

bmi = weight / (height * height);

printf("Your BMI is: %.2f\n", bmi);

if (bmi < 18.5) {


printf("Category: Underweight");
} else if (bmi >= 18.5 && bmi < 24.9) {
printf("Category: Normal weight");
} else if (bmi >= 25 && bmi < 29.9) {
printf("Category: Overweight");
} else {
printf("Category: Obesity");
}

return 0;
}
OUTPUT:

d. Write a switch statement that will examine the value of a char-type


variable called color and print one of the following messages, depending
on the character assigned to color.
(a) RED, if either r or R is assigned to color,
(b) GREEN, if either g or G is assigned to color,
(c) BLUE, if either b or B is assigned to color
(d) BLACK, if color is assigned any other character
CODE:
#include <stdio.h>

int main() {
char color;

printf("Enter a color character (r, R, g, G, b, B): ");


scanf(" %c", &color);

switch (color) {
case 'r':
case 'R':
printf("RED\n");
break;
case 'g':
case 'G':
printf("GREEN\n");
break;
case 'b':
case 'B':
printf("BLUE\n");
break;
default:
printf("BLACK\n");
break;
}

return 0;
}
OUTPUT:
e. Write an appropriate control structure that will examine the value of a
floating-point variable called temp and print one of the following
messages, depending on the value assigned to temp.
(a) ICE, if the value of temp is less than 0.
(b) WATER, if the value of temp lies between 0and 100.
(c) STEAM, if the value of temp exceeds 100.

CODE:
#include <stdio.h>

int main() {
float temp;

printf("Enter the temperature: ");


scanf("%f", &temp);

if (temp < 0) {
printf("ICE\n");
} else if (temp >= 0 && temp <= 100) {
printf("WATER\n");
} else {
printf("STEAM\n");
}

return 0;
}
OUTPUT:

e. You are a software developer working on an online bookstore


application. The bookstore offers different types of discounts based on
the total amount spent by a customer. The discount rules are as follows:
 If a customer spends less than $50, no discount is applied.
 If a customer spends between $50 and $100 (inclusive), a 5% discount
is applied.
 If a customer spends more than $100 but less than $200, a 10%
discount is applied.
 If a customer spends $200 or more, a 15% discount is applied.
Additionally, there's a special discount for members:
 Members receive an extra 5% discount on top of any applicable
discounts.
Write a program that calculates the final price a customer needs to
pay after applying the appropriate discount. The program should ask
the user to input the total amount spent and whether the customer is
a member.
Example:
Input:
 Total amount spent: 120
 Is the customer a member? Yes
Output:
 Final price to pay: 102

CODE:

#include <stdio.h>

int main() {
float totalAmount, finalPrice;
char isMember;

// Prompt user for the total amount spent


printf("Enter the total amount spent: ");
scanf("%f", &totalAmount);

// Prompt user to check if the customer is a member


printf("Is the customer a member? (Y/N): ");
scanf(" %c", &isMember);

// Calculate the discount based on the total amount spent


if (totalAmount >= 200) {
finalPrice = totalAmount * 0.85;
} else if (totalAmount >= 100) {
finalPrice = totalAmount * 0.90;
} else if (totalAmount >= 50) {
finalPrice = totalAmount * 0.95;
} else {
finalPrice = totalAmount;
}
// Apply additional member discount if applicable
if (isMember == 'Y' || isMember == 'y') {
finalPrice *= 0.95;
}

// Output the final price to pay


printf("Final price to pay: %.2f\n", finalPrice);

return 0;
}

OUTPUT:
ASSIGNMENT 3
DATE: 17-08-2024

Write a C Program using decision-making constructs.

1. Write a C program that implements a program to count the number of


digit in a given integer using a do-while loop and reverse the number and
display it.
CODE:
#include <stdio.h>

int main() {
int num, temp, count = 0, revNum = 0, rem;

printf("Enter an integer: ");


scanf("%d", &num);
temp = num;

do {
rem = num % 10;
revNum = revNum * 10 + rem;
num /= 10;
count++;
} while (num != 0);

printf("Number of digits: %d\n", count);


printf("Reversed number: %d\n", revNum);

return 0;
}

OUTPUT:
2.Write a C program that accepts a numbers until a zero is entered and
calculates the sum of squares of the positive values.

CODE:
#include <stdio.h>

int main() {
int num,sqr;
int sum=0;

while(num!=0){
printf("Enter an integer: ");
scanf("%d", &num);
sqr = num*num;
sum = sum + sqr;
}

printf("Sum of digits: %d\n", sum);

return 0;
}
OUTPUT:

3.Write a C program to remove all characters in a string except alphabets.


Input: Hello123Hi*
Output: HelloHi
CODE:
#include <stdio.h>
int main() {
char str[100];
int i, j = 0;

printf("Enter a string: ");


fgets(str, sizeof(str), stdin);

for (i = 0; str[i] != '\0'; i++) {


if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z')) {
str[j++] = str[i];
}
}
str[j] = '\0';

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

return 0;
}
OUTPUT:

4.Write a C program to read a string and print reverse of a string.


Input: Good
Output: dooG

CODE:
#include <stdio.h>

int main() {
char str[100], revstr[100];
int length = 0, i;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

for (i = 0; str[i] != '\0'; i++) {


if (str[i] == '\n') {
str[i] = '\0';
}
}
while (str[length] != '\0') {
length++;
}

for (i = 0; i < length; i++) {


revstr[i] = str[length - i - 1];
}
revstr[length] = '\0';

printf("Reversed string: %s\n", revstr);

return 0;
}OUTPUT:

5.Given an array of integers arr[] of size N and an integer, Write a C


program to swap minimum and maximum elements.
Example: Input: arr[] = {9, 4, 1, 6, 7, 3, 2}
Output: 1, 4, 9, 6, 7, 3, 2
CODE:

#include <stdio.h>

int main() {
int n;
printf("Enter the size of the array: ");
scanf("%d", &n);
int arr[n];

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


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

int min = 0, max = 0;

for (int i = 1; i < n; i++) {


if (arr[i] < arr[min]) {
min = i;
}
if (arr[i] > arr[max]) {
max = i;
}
}

int temp = arr[min];


arr[min] = arr[max];
arr[max] = temp;

printf("Array after swapping min and max: ");


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

return 0;
}
OUTPUT:

6.Imagine you are part of a team developing a navigation system for


autonomous vehicles. As part of the project, you need to implement a
feature that allows the vehicles to rotate their sensor data matrix. This
rotation is essential for adjusting the perception of the environment
based on the vehicle's orientation.
In the context of this project, you're tasked with implementing a
Java program to rotate the matrix elements representing the sensor
data. The matrix represents the readings captured by the vehicle's
sensors, such as lidar or radar, and needs to be rotated accordingly
to align with the vehicle's orientation changes.
Your program should take into account the following requirements:
- The matrix can be of any size, but it will always be square (i.e.,
same number of rows and columns).
- The rotation angle will be provided as input to the program.
- The rotation should be performed clockwise or counterclockwise
based on the specified angle.
- The rotated matrix should be displayed.
Your task is to design and implement the C program that effectively
rotates the matrix elements according to the provided angle while
maintaining the integrity of the sensor data for the autonomous
vehicle's navigation system.

CODE:

#include <stdio.h>

void rotate90Clockwise(int n, int mat[n][n]) {


for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
int temp = mat[i][j];
mat[i][j] = mat[n - 1 - j][i];
mat[n - 1 - j][i] = mat[n - 1 - i][n - 1 - j];
mat[n - 1 - i][n - 1 - j] = mat[j][n - 1 - i];
mat[j][n - 1 - i] = temp;
}
}
}

void rotate90CounterClockwise(int n, int mat[n][n]) {


for (int i = 0; i < n / 2; i++) {
for (int j = i; j < n - i - 1; j++) {
int temp = mat[i][j];
mat[i][j] = mat[j][n - 1 - i];
mat[j][n - 1 - i] = mat[n - 1 - i][n - 1 - j];
mat[n - 1 - i][n - 1 - j] = mat[n - 1 - j][i];
mat[n - 1 - j][i] = temp;
}
}
}

void rotateMatrix(int n, int mat[n][n], int angle) {


int rotations = (angle / 90) % 4;
if (rotations < 0) {
rotations += 4;
}

for (int i = 0; i < rotations; i++) {


rotate90Clockwise(n, mat);
}
}

void printMatrix(int n, int mat[n][n]) {


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

int main() {
int n, angle;

printf("Enter the size of the matrix (n x n): ");


scanf("%d", &n);

int mat[n][n];

printf("Enter the elements of the matrix:\n");


for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &mat[i][j]);
}
}
printf("Enter the rotation angle (positive for clockwise, negative for
counterclockwise): ");
scanf("%d", &angle);

rotateMatrix(n, mat, angle);

printf("Rotated matrix:\n");
printMatrix(n, mat);

return 0;
}
OUTPUT:
ASSIGNMENT 4
DATE: 24-08-2024

Write a C Program using decision-making constructs.

1. Write a function to find factorial of a given number.


CODE:
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n - 1);
}
}

int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);

if (num < 0) {
printf("Factorial of a negative number doesn't exist.\n");
} else {
printf("Factorial of %d is %d\n", num, factorial(num));
}

return 0;
}
OUTPUT:

2. Write a function to find inverse of a matrix.

CODE:
#include <stdio.h>
float determinant(float mat[2][2]) {
return (mat[0][0] * mat[1][1]) - (mat[0][1] * mat[1][0]);
}
void inverse(float mat[2][2], float invmat[2][2]) {
float det = determinant(mat);

if (det == 0) {
printf("Inverse doesn't exist as the determinant is zero.\n");
return;
}

invmat[0][0] = mat[1][1] / det;


invmat[0][1] = -mat[0][1] / det;
invmat[1][0] = -mat[1][0] / det;
invmat[1][1] = mat[0][0] / det;
}

int main() {
float mat[2][2], invmat[2][2];

printf("Enter the elements of the 2x2 matrix:\n");


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
scanf("%f", &mat[i][j]);
}
}

inverse(mat, invmat);

printf("The inverse of the matrix is:\n");


for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
printf("%f ", invmat[i][j]);
}
printf("\n");
}

return 0;
}
OUTPUT:
3. Write a function which reads in a single lowercase character, converts
it to uppercase using a programmer-defined function, and then
displays the uppercase equivalent.
CODE:
#include <stdio.h>
void toUpperCase(char str[]) {
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = str[i] - 32;
}
}
}

int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);

toUpperCase(str);

printf("The uppercase equivalent is: %s\n", str);

return 0;
}

OUTPUT:
4.Write a function that will allow a floating-point number to be raised
to an integer power. In other words, we wish to evaluate the formula.
Y=x^n
n
where y and x are floating-point variables and n is an integer variable.
CODE:
#include <stdio.h>
float power(float base, int expo) {
float result = 1.0;
int absexp;

if (expo < 0) {
absexp = -expo;
} else {
absexp = expo;
}

for (int i = 0; i < absexp; i++) {


result *= base;
}

if (expo < 0) {
result = 1.0 / result;
}

return result;
}

int main() {
float x;
int n;
printf("Enter the base (x): ");
scanf("%f", &x);

printf("Enter the exponent (n): ");


scanf("%d", &n);

float y = power(x, n);

printf("%f raised to the power of %d is %f\n", x, n, y);

return 0;
}
OUTPUT:
ASSIGNMENT 5
DATE: 13-09-2024

Write a C Program using decision-making constructs.

1. John and Emily are participating in a friendly math contest. The contest
organizer gives them two numbers, A = 10 and B = 20, and asks them to
swap the values without directly reassigning the numbers. Write a C
program to implement the above math contest using call-by-value and
call-by-reference. Justify which method is best.

CODE:
#include<stdio.h>

void swapValues(int a, int b){


a = a + b;
b = a - b;
a = a - b;
printf("Swaped by values: %d %d",a,b);
}

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


*a = *a + *b;
*b = *a - *b;
*a = *a - *b;
printf("\nSwaped by values: %d %d",*a,*b);
}

int main(){
int a=10, b=20;
swapValues(a,b);
printf("\nOriginal: %d %d",a,b);
swapReference(&a,&b);
printf("\nOriginal: %d %d",a,b);
}
OUTPUT:

2. Write recursive function to find nth Fibonacci number.

CODE:
#include <stdio.h>

void fibonacciseries(int current,int next,int n){


if(n>0){
printf("%d ",current);
int a = current + next;
fibonacciseries(next,a,n-1);
}
}

int main(){
int x;
printf("\nEnter the number of terms: ");
scanf("%d",&x);
fibonacciseries(0,1,x);
}
OUTPUT:

3. You are working on a project where you need to compute the trace of a
matrix (the sum of the elements on the main diagonal) for various
calculations. Implement a C function to calculate the trace of a square
matrix. Use pointer to an array to implement it.
Hint:
Input: mat [3][3]={{1,2,3},
{4,5,6},
{7, 8, 9}};
Output: Trace=1+5+9=15
CODE:
#include<stdio.h>

int main(){
int col=0,row=0,temp=0,trace=0;
printf("Enter rows and columns size: ");
scanf("%d",&row);
scanf("%d",&col);
int matrix[row][col];
printf("Enter the elements:\n ");

for(int i=0;i<row;i++){
printf("Row %d\n",i+1);
for(int j=0; j<col;j++){
scanf("%d",&temp);
matrix[i][j]=temp;
}
}
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
if(i==j){
trace+=matrix[i][j];
}
}
}
printf("Trace of Matrix: %d",trace);
}

OUTPUT:
ASSIGNMENT 6
DATE: 28-09-2024

Write a C Program using pointers.

a. Write a C program to reorder a one-dimensional, integer array from


smallest to largest, using pointer notation. Memory is initially assigned to
the pointer variable via the malloc library function.

CODE:
#include <stdio.h>
#include <stdlib.h>

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


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

void sortArray(int *arr, int size) {


for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (*(arr + i) > *(arr + j)) {
swap((arr + i), (arr + j));
}
}
}
}

int main() {
int size;
printf("Enter the number of elements: ");
scanf("%d", &size);

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


if (arr == NULL) {
printf("Memory allocation failed\n");
return 1;
}
printf("Enter the elements:\n");
for (int i = 0; i < size; i++) {
scanf("%d", (arr + i));
}
sortArray(arr, size);

printf("Sorted array:\n");
for (int i = 0; i < size; i++) {
printf("%d ", *(arr + i));
}
printf("\n");

free(arr);
return 0;
}

OUTPUT:

b. Analyzing a Line of Text Suppose we wish to analyze a line of text by


examining each of the characters and determining into which of several
different categories it falls. In particular, suppose we count the number of
vowels, consonants, digits, whitespace characters and “other” characters
(punctuation, operators, brackets, etc.) This can easily be accomplished by
reading in a line of text, storing it in a one-dimensional character array, and
then analyzing the individual array elements. An appropriate counter will be
incremented for each character. The value of each counter (number of
vowels, number of consonants, etc) can then be written out after all of the
characters have been analyzed.
Let us write a complete C program using call by reference that will carry out
such an analysis.
To do so, we first define the following variables.
line = an 80-element character array containing the line of text
vowels = an integer counter indicating the number of vowels
consonants = an integer counter indicating the number of consonants
digits = an integer counter indicating the number of digits
whitespc = an integer counter indicating the number of whitespace characters
(blank spaces or tabs) other = an integer counter indicating the number of
characters that do not fall into any of the preceding categories

CODE:
#include <stdio.h>

void analyzeText(char *line, int *vowels, int *consonants, int *digits, int
*whitespc, int *other) {
*vowels = *consonants = *digits = *whitespc = *other = 0;

for (int i = 0; line[i] != '\0'; i++) {


char ch = line[i];
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) {
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
(*vowels)++;
} else {
(*consonants)++;
}
} else if (ch >= '0' && ch <= '9') {
(*digits)++;
} else if (ch == ' ' || ch == '\t') {
(*whitespc)++;
} else {
(*other)++;
}
}
}

int main() {
char line[80];
int vowels, consonants, digits, whitespc, other;

printf("Enter a line of text (max 80 characters): ");


fgets(line, sizeof(line), stdin);

analyzeText(line, &vowels, &consonants, &digits, &whitespc, &other);

printf("Vowels: %d\n", vowels);


printf("Consonants: %d\n", consonants);
printf("Digits: %d\n", digits);
printf("Whitespace characters: %d\n", whitespc);
printf("Other characters: %d\n", other);

return 0;
}
OUTPUT:

3. You are developing a simple inventory management system for a


warehouse. The system will allow the user to keep track of quantities of
various items in stock. The goal is to store the quantities of items in an
array and allow operations like adding, viewing, and updating stock using
pointer arithmetic.
Requirements:
1. Input:
The user will enter the number of items in the inventory (up to 50
items).
For each item, the user will input the initial quantity in stock.
2. Pointer Arithmetic:
Use pointers to access and manipulate the quantities of items.
Instead of using array indexing (arr[i]), perform arithmetic operations
on pointers to move through the array.
3. Operations:
Add Stock: The user can add stock to an existing item.
Update Stock: The user can update the stock level for any item.
View Stock: The user can view the stock level of all items.
4. Functions:
addStock(): Takes a pointer to the start of the array and adds stock to a
specific item using pointer arithmetic.
updateStock(): Updates the stock for a specific item using pointer
arithmetic.
viewStock(): Displays the stock for all items using pointer arithmetic.

Expected input and output:


Enter the number of items in the inventory: 3
Enter quantity for Item 1: 10
Enter quantity for Item 2: 20
Enter quantity for Item 3: 15
Inventory Menu:
1. Add Stock
2. Update Stock
3. View Stock
4. Exit

Enter your choice: 3


Stock levels:
Item 1: 10
Item 2: 20
Item 3: 15

Enter your choice: 1


Enter item number to add stock: 2
Enter quantity to add: 5

Stock levels:
Item 1: 10
Item 2: 25
Item 3: 15
CODE:
#include <stdio.h>
#include <stdlib.h>

void addStock(int *inventory, int item, int quantity) {


*(inventory + item - 1) += quantity;
}

void updateStock(int *inventory, int item, int quantity) {


*(inventory + item - 1) = quantity;
}

void viewStock(int *inventory, int size) {


printf("Stock levels:\n");
for (int i = 0; i < size; i++) {
printf("Item %d: %d\n", i + 1, *(inventory + i));
}
}

int main() {
int size;
printf("Enter the number of items in the inventory (up to 50): ");
scanf("%d", &size);

int *inventory = (int *)malloc(size * sizeof(int));


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

for (int i = 0; i < size; i++) {


printf("Enter quantity for Item %d: ", i + 1);
scanf("%d", (inventory + i));
}

int choice, item, quantity;


while (1) {
printf("\nInventory Menu:\n");
printf("1. Add Stock\n");
printf("2. Update Stock\n");
printf("3. View Stock\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter item number to add stock: ");
scanf("%d", &item);
printf("Enter quantity to add: ");
scanf("%d", &quantity);
addStock(inventory, item, quantity);
break;
case 2:
printf("Enter item number to update stock: ");
scanf("%d", &item);
printf("Enter new quantity: ");
scanf("%d", &quantity);
updateStock(inventory, item, quantity);
break;
case 3:
viewStock(inventory, size);
break;
case 4:
free(inventory);
return 0;
default:
printf("Invalid choice. Please try again.\n");
}
}
}

OUTPUT:
ASSIGNMENT 7
DATE: 05-10-2024

1. Create a structure named Book to store book details like title, author,
and price. Write a C program to input details for n books, find the most
expensive and the lowest priced books, and display their information.
CODE:
#include <stdio.h>
#include <float.h>

struct Book {
char title[100];
char author[100];
float price;
};

int main() {
int n;
printf("Enter the number of books: ");
scanf("%d", &n);

struct Book books[n];

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


printf("\nInput details for Book %d:\n", i + 1);
printf("Title: ");
scanf("%s", books[i].title);
printf("Author: ");
scanf("%s", books[i].author);
printf("Price: ");
scanf("%f", &books[i].price);
}

struct Book mostExpensive = books[0];


struct Book lowestPriced = books[0];

for (int i = 1; i < n; i++) {


if (books[i].price > mostExpensive.price) {
mostExpensive = books[i];
}
if (books[i].price < lowestPriced.price) {
lowestPriced = books[i];
}
}

printf("\nMost Expensive Book:\n");


printf("Title: %s\n", mostExpensive.title);
printf("Author: %s\n", mostExpensive.author);
printf("Price: %.2f\n", mostExpensive.price);

printf("\nLowest Priced Book:\n");


printf("Title: %s\n", lowestPriced.title);
printf("Author: %s\n", lowestPriced.author);
printf("Price: %.2f\n", lowestPriced.price);

return 0;
}
OUTPUT:
2. Define a structure named "Date" with members day, month, and year.
Write a C program to input two dates and find the difference in days between
them.
CODE:
#include <stdio.h>

struct Date {
int day;
int month;
int year;
};

int isLeapYear(int year) {


return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

int daysInMonth(int month, int year) {


switch (month) {
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
return 31;
case 4: case 6: case 9: case 11:
return 30;
case 2:
return isLeapYear(year) ? 29 : 28;
default:
return 0;
}
}

int totalDays(struct Date date) {


int total = date.day;
for (int i = 1; i < date.month; i++) {
total += daysInMonth(i, date.year);
}
total += (date.year - 1) * 365 + (date.year - 1) / 4 - (date.year - 1) / 100 +
(date.year - 1) / 400;
return total;
}

int dateDifference(struct Date date1, struct Date date2) {


return totalDays(date2) - totalDays(date1);
}

int main() {
struct Date date1, date2;

printf("Input details for Date 1 (day month year): ");


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

printf("Input details for Date 2 (day month year): ");


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

int difference = dateDifference(date1, date2);


printf("\nDifference in Days: %d\n", difference);

return 0;
}
OUTPUT:
3. Create a structure named Complex to represent a complex number with
real and imaginary parts. Write a C program to add and multiply two
complex
numbers.
CODE:
#include <stdio.h>

struct Complex {
float real;
float imag;
};

struct Complex addComplex(struct Complex num1, struct Complex


num2) {
struct Complex result;
result.real = num1.real + num2.real;
result.imag = num1.imag + num2.imag;
return result;
}

struct Complex multiplyComplex(struct Complex num1, struct Complex


num2) {
struct Complex result;
result.real = (num1.real * num2.real) - (num1.imag * num2.imag);
result.imag = (num1.real * num2.imag) + (num1.imag * num2.real);
return result;
}

void displayComplex(struct Complex num) {


printf("%.2f + %.2fi\n", num.real, num.imag);
}

int main() {
struct Complex complexNum1, complexNum2, sumResult,
productResult;

printf("Input details for Complex Number 1 (real imag): ");


scanf("%f %f", &complexNum1.real, &complexNum1.imag);

printf("Input details for Complex Number 2 (real imag): ");


scanf("%f %f", &complexNum2.real, &complexNum2.imag);

sumResult = addComplex(complexNum1, complexNum2);

productResult = multiplyComplex(complexNum1, complexNum2);

printf("\nSum of Complex Numbers:\n");


displayComplex(sumResult);

printf("\nProduct of Complex Numbers:\n");


displayComplex(productResult);

return 0;
}
OUTPUT:

4. Create a program that manages student grades. The program should


store details such as the student's name, roll number, and marks for
three subjects.
Requirements:
● Define a struct Student with the necessary fields.
● Write a function to input details of n students.
● Write a function to calculate and display the average marks of
each student.
● Write a function to display the name of students who have
failed (marks in any subject are below 40).
CODE:
#include <stdio.h>
#include <string.h>
#define MAX_STUDENTS 100

struct Student {
char name[50];
int rollNumber;
int marks[3];
};

void inputStudentDetails(struct Student students[], int n) {


for (int i = 0; i < n; i++) {
printf("Enter details for student %d:\n", i + 1);
printf("Name: ");
scanf("%s", students[i].name);
printf("Roll Number: ");
scanf("%d", &students[i].rollNumber);
printf("Enter marks for 3 subjects: ");
for (int j = 0; j < 3; j++) {
scanf("%d", &students[i].marks[j]);
}
}
}
void displayAverageMarks(struct Student students[], int n) {
for (int i = 0; i < n; i++) {
int total = 0;
for (int j = 0; j < 3; j++) {
total += students[i].marks[j];
}
float average = total / 3.0;
printf("Average marks for %s (Roll Number: %d): %.2f\n",
students[i].name, students[i].rollNumber, average);
}
}
void displayFailedStudents(struct Student students[], int n) {
printf("Students who have failed:\n");
for (int i = 0; i < n; i++) {
for (int j = 0; j < 3; j++) {
if (students[i].marks[j] < 40) {
printf("%s (Roll Number: %d)\n", students[i].name,
students[i].rollNumber);
break;
}
}
}
}
int main() {
struct Student students[MAX_STUDENTS];
int n;

printf("Enter the number of students: ");


scanf("%d", &n);

inputStudentDetails(students, n);
displayAverageMarks(students, n);
displayFailedStudents(students, n);

return 0;
}
OUTPUT:
ASSIGNMENT 1 - CPP
DATE: 26-10-2024

1. Define a class named Movie. Include private fields for the title, year,
and name of the director. Include three public functions with the
prototypes void Movie::setTitle(string);, void Movie::setYear(int);, and
void setDirector(string);. Include another function that displays all the
information about a Movie. Write a main() function that declares a
movie object named myFavoriteMovie. Set and display the object’s
fields. Save the file as Movie.cpp.
CODE:
#include <iostream>
#include <string>

using namespace std;

class Movie {
private:
string title;
int year;
string director;

public:
void setTitle(string t) {
title = t;
}

void setYear(int y) {
year = y;
}

void setDirector(string d) {
director = d;
}

void displayInfo() {
cout << "Title: " << title << endl;
cout << "Year: " << year << endl;
cout << "Director: " << director << endl;
}
};

int main() {
Movie myFavoriteMovie;

myFavoriteMovie.setTitle("Kalki 2898 AD");


myFavoriteMovie.setYear(2024);
myFavoriteMovie.setDirector("Nag Ashwin");

myFavoriteMovie.displayInfo();

return 0;
}
OUTPUT:

2. a. Define a class named Customer that holds private fields for a customer
ID number, last name, first name, and credit limit. Include four public
functions that each set one of the four fields. Do not allow any credit limit
over $10,000. Include a public function that displays a Customer’s data. Write
a main() function in which you declare a Customer, set the Customer’s fields,
and display the results. Save the file as Customer.cpp.
b. Write a main() function that declares an array of five Customer objects.
Prompt the user for values for each Customer, and display all five Customer
objects. Save the file as Customer2.cpp.

CODE:
#include <iostream>
#include <string>

using namespace std;

class Customer {
private:
int customerID;
string lastName;
string firstName;
double creditLimit;

public:
void setCustomerID(int id) {
customerID = id;
}

void setLastName(string lname) {


lastName = lname;
}

void setFirstName(string fname) {


firstName = fname;
}

void setCreditLimit(double limit) {


if (limit > 10000) {
creditLimit = 10000;
} else {
creditLimit = limit;
}
}

void displayCustomer() {
cout << "Customer ID: " << customerID << endl;
cout << "Last Name: " << lastName << endl;
cout << "First Name: " << firstName << endl;
cout << "Credit Limit: $" << creditLimit << endl;
}
};

int main() {
Customer myCustomer;

myCustomer.setCustomerID(12345);
myCustomer.setLastName("Doe");
myCustomer.setFirstName("John");
myCustomer.setCreditLimit(15000);
myCustomer.displayCustomer();

return 0;
}
OUTPUT:

CODE:

#include <iostream>
#include <string>

using namespace std;

class Customer {
private:
int customerID;
string lastName;
string firstName;
double creditLimit;

public:
void setCustomerID(int id) {
customerID = id;
}

void setLastName(string lname) {


lastName = lname;
}

void setFirstName(string fname) {


firstName = fname;
}

void setCreditLimit(double limit) {


if (limit > 10000) {
creditLimit = 10000;
} else {
creditLimit = limit;
}
}

void displayCustomer() {
cout << "Customer ID: " << customerID << endl;
cout << "Last Name: " << lastName << endl;
cout << "First Name: " << firstName << endl;
cout << "Credit Limit: $" << creditLimit << endl;
}
};

int main() {
Customer customers[5];

for (int i = 0; i < 5; i++) {


int id;
string lname, fname;
double limit;

cout << "Enter details for customer " << i + 1 << ":" << endl;
cout << "Customer ID: ";
cin >> id;
cout << "Last Name: ";
cin >> lname;
cout << "First Name: ";
cin >> fname;
cout << "Credit Limit: ";
cin >> limit;

customers[i].setCustomerID(id);
customers[i].setLastName(lname);
customers[i].setFirstName(fname);
customers[i].setCreditLimit(limit);
}

cout << "\nCustomer Details:\n";


for (int i = 0; i < 5; i++) {
customers[i].displayCustomer();
cout << endl;
}

return 0;
}
OUTPUT:
3. You are developing a class Calculator in C++ to perform basic arithmetic
operations. You want to implement method overloading to support
different types of operands (integers and floating-point numbers) for
addition (add) and multiplication (multiply) operations.
1. Define a class Calculator with appropriate member functions for add
and multiply.
2. Implement method overloading for both functions to handle integers
and floating-point numbers separately.
3. Provide a sample usage code demonstrating the use of overloaded
methods in different scenarios.
CODE:
#include <iostream>

using namespace std;

class Calculator {
public:
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}

int multiply(int a, int b) {


return a * b;
}

double multiply(double a, double b) {


return a * b;
}
};

int main() {
Calculator calc;

int intSum = calc.add(5, 3);


double doubleSum = calc.add(5.5, 3.3);

int intProduct = calc.multiply(4, 2);


double doubleProduct = calc.multiply(4.5, 2.2);

cout << "Integer addition: 5 + 3 = " << intSum << endl;


cout << "Double addition: 5.5 + 3.3 = " << doubleSum << endl;
cout << "Integer multiplication: 4 * 2 = " << intProduct << endl;
cout << "Double multiplication: 4.5 * 2.2 = " << doubleProduct << endl;

return 0;
}
OUTPUT:
ASSIGNMENT 2 - CPP
DATE: 09-11-2024

1. You are developing a system for a university. There is a base class Person
that has attributes like name and age. The university has both Student and
Professor subclasses, each with unique attributes. For example, Student
has studentID and Professor has subject. How would you implement this
class hierarchy using inheritance in C++? Write the code for the classes
and implement a function introduce() in each subclass that provides a
unique introduction message.
CODE:
#include <iostream>
#include <string>

class Person {
protected:
std::string name;
int age;

public:
Person(const std::string& name, int age) : name(name), age(age) {}

virtual void introduce() const = 0; // Pure virtual function


};

class Student : public Person {


private:
std::string studentID;

public:
Student(const std::string& name, int age, const std::string& studentID)
: Person(name, age), studentID(studentID) {}

void introduce() const override {


std::cout << "Hi, I'm " << name << ", a " << age << " years old student.
My student ID is " << studentID << ".\n";
}
};
class Professor : public Person {
private:
std::string subject;

public:
Professor(const std::string& name, int age, const std::string& subject)
: Person(name, age), subject(subject) {}

void introduce() const override {


std::cout << "Hello, I'm Professor " << name << ", " << age << " years
old. I teach " << subject << ".\n";
}
};

int main() {
Student student("Shahid", 20, "S123");
Professor professor("Dr. Raj Vaishnav", 45, "Modern Physics");

student.introduce();
professor.introduce();

return 0;
}
OUTPUT:

2. In a banking application, there is a class Account with private attributes


accountNumber and balance. There is a subclass SavingsAccount that
needs access to balance to calculate interest.How would you design the
inheritance structure to allow the SavingsAccount class to access balance
while keeping it private from other classes? Should you use protected or
private inheritance, and why?
CODE:
#include <iostream>
class Account {
private:
int accountNumber;

protected:
double balance;

public:
Account(int accNum, double bal) : accountNumber(accNum), balance(bal)
{}

int getAccountNumber() const {


return accountNumber;
}

double getBalance() const {


return balance;
}

void deposit(double amount) {


balance += amount;
}

void withdraw(double amount) {


if (amount <= balance) {
balance -= amount;
} else {
std::cout << "Insufficient funds!" << std::endl;
}
}
};

class SavingsAccount : public Account {


private:
double interestRate;

public:
SavingsAccount(int accNum, double bal, double rate)
: Account(accNum, bal), interestRate(rate) {}
void calculateInterest() {
double interest = balance * interestRate;
deposit(interest);
std::cout << "Interest added: " << interest << std::endl;
}
};

int main() {
SavingsAccount sa(12345, 1000.0, 0.05);
sa.calculateInterest();
std::cout << "New balance: " << sa.getBalance() << std::endl;

return 0;
}
OUTPUT:

3. You are building a graphic design tool where there is a base class Shape
with a virtual function draw(). Derived classes Circle, Square, and
Triangle each have their own way of drawing themselves. Write the class
definitions for Shape, Circle, Square, and Triangle. Implement
polymorphism such that when draw() is called on a Shape* pointer
pointing to any derived object, the correct draw() function is executed.
CODE:
#include <iostream>

class Shape {
public:
virtual void draw() const = 0;
virtual ~Shape() {}
};

class Circle : public Shape {


public:
void draw() const override {
std::cout << "Drawing a Circle" << std::endl;
}
};

class Square : public Shape {


public:
void draw() const override {
std::cout << "Drawing a Square" << std::endl;
}
};

class Triangle : public Shape {


public:
void draw() const override {
std::cout << "Drawing a Triangle" << std::endl;
}
};

int main() {
Shape* shapes[3];
shapes[0] = new Circle();
shapes[1] = new Square();
shapes[2] = new Triangle();

for (int i = 0; i < 3; ++i) {


shapes[i]->draw();
}

for (int i = 0; i < 3; ++i) {


delete shapes[i];
}

return 0;
}
OUTPUT:
THANK YOU

You might also like