C CPP Language Complete Practice Assignment
C CPP Language Complete Practice Assignment
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:
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:
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.
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
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;
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;
}
}
return 0;
}
OUTPUT:
CODE:
#include <stdio.h>
int main() {
float weight, height, bmi;
return 0;
}
OUTPUT:
int main() {
char 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;
if (temp < 0) {
printf("ICE\n");
} else if (temp >= 0 && temp <= 100) {
printf("WATER\n");
} else {
printf("STEAM\n");
}
return 0;
}
OUTPUT:
CODE:
#include <stdio.h>
int main() {
float totalAmount, finalPrice;
char isMember;
return 0;
}
OUTPUT:
ASSIGNMENT 3
DATE: 17-08-2024
int main() {
int num, temp, count = 0, revNum = 0, rem;
do {
rem = num % 10;
revNum = revNum * 10 + rem;
num /= 10;
count++;
} while (num != 0);
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;
}
return 0;
}
OUTPUT:
return 0;
}
OUTPUT:
CODE:
#include <stdio.h>
int main() {
char str[100], revstr[100];
int length = 0, i;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
return 0;
}OUTPUT:
#include <stdio.h>
int main() {
int n;
printf("Enter the size of the array: ");
scanf("%d", &n);
int arr[n];
return 0;
}
OUTPUT:
CODE:
#include <stdio.h>
int main() {
int n, angle;
int mat[n][n];
printf("Rotated matrix:\n");
printMatrix(n, mat);
return 0;
}
OUTPUT:
ASSIGNMENT 4
DATE: 24-08-2024
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:
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;
}
int main() {
float mat[2][2], invmat[2][2];
inverse(mat, invmat);
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);
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;
}
if (expo < 0) {
result = 1.0 / result;
}
return result;
}
int main() {
float x;
int n;
printf("Enter the base (x): ");
scanf("%f", &x);
return 0;
}
OUTPUT:
ASSIGNMENT 5
DATE: 13-09-2024
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>
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:
CODE:
#include <stdio.h>
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
CODE:
#include <stdio.h>
#include <stdlib.h>
int main() {
int size;
printf("Enter the number of elements: ");
scanf("%d", &size);
printf("Sorted array:\n");
for (int i = 0; i < size; i++) {
printf("%d ", *(arr + i));
}
printf("\n");
free(arr);
return 0;
}
OUTPUT:
CODE:
#include <stdio.h>
void analyzeText(char *line, int *vowels, int *consonants, int *digits, int
*whitespc, int *other) {
*vowels = *consonants = *digits = *whitespc = *other = 0;
int main() {
char line[80];
int vowels, consonants, digits, whitespc, other;
return 0;
}
OUTPUT:
Stock levels:
Item 1: 10
Item 2: 25
Item 3: 15
CODE:
#include <stdio.h>
#include <stdlib.h>
int main() {
int size;
printf("Enter the number of items in the inventory (up to 50): ");
scanf("%d", &size);
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);
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 main() {
struct Date date1, date2;
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;
};
int main() {
struct Complex complexNum1, complexNum2, sumResult,
productResult;
return 0;
}
OUTPUT:
struct Student {
char name[50];
int rollNumber;
int marks[3];
};
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>
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.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>
class Customer {
private:
int customerID;
string lastName;
string firstName;
double creditLimit;
public:
void setCustomerID(int id) {
customerID = id;
}
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>
class Customer {
private:
int customerID;
string lastName;
string firstName;
double creditLimit;
public:
void setCustomerID(int id) {
customerID = id;
}
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];
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);
}
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>
class Calculator {
public:
int add(int a, int b) {
return a + b;
}
int main() {
Calculator calc;
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) {}
public:
Student(const std::string& name, int age, const std::string& studentID)
: Person(name, age), studentID(studentID) {}
public:
Professor(const std::string& name, int age, const std::string& subject)
: Person(name, age), subject(subject) {}
int main() {
Student student("Shahid", 20, "S123");
Professor professor("Dr. Raj Vaishnav", 45, "Modern Physics");
student.introduce();
professor.introduce();
return 0;
}
OUTPUT:
protected:
double balance;
public:
Account(int accNum, double bal) : accountNumber(accNum), balance(bal)
{}
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() {}
};
int main() {
Shape* shapes[3];
shapes[0] = new Circle();
shapes[1] = new Square();
shapes[2] = new Triangle();
return 0;
}
OUTPUT:
THANK YOU