Lab 1 – Programming Practice
C Programming – 10 Unique Tasks
C Task 1: Grocery Store Shopping Bill
Question: Write a C program that calculates the total cost of purchasing apples at a grocery store. Prompt the user to enter the quantity of apples bought (integer) and the price per apple in dollars (float). Compute the total subtotal cost and display the result formatted to two decimal places.
Solution:
#include <stdio.h>
int main() {
int quantity;
float pricePerApple, totalCost;
printf("Enter quantity of apples purchased: ");
scanf("%d", &quantity);
printf("Enter price per apple ($): ");
scanf("%f", &pricePerApple);
totalCost = quantity * pricePerApple;
printf("
--- Grocery Checkout ---
");
printf("Apples Bought: %d
", quantity);
printf("Total Subtotal Cost: $%.2f
", totalCost);
return 0;
}
Concept Explanation:
This beginner program practices basic user input and output using scanf() and printf() alongside variable declarations from Lab 1. It reads integer and floating-point data types, applies a basic multiplication formula, and formats the output display to two decimal places.
C Task 2: Student Digital Id Card Printer
Question: Write a C program that generates a formatted digital ID card badge. Prompt the user to input their student ID number (integer), age (integer), and current GPA (float). Display the ID badge using horizontal tabs ( ) and newlines (
) for clean visual alignment.
Solution:
#include <stdio.h>
int main() {
int studentID, age;
float gpa;
printf("Enter Student ID Number: ");
scanf("%d", &studentID);
printf("Enter Age: ");
scanf("%d", &age);
printf("Enter GPA: ");
scanf("%f", &gpa);
printf("
========================================
");
printf(" ACADEMIC DIGITAL ID BADGE
");
printf("========================================
");
printf("ID Number: %d
", studentID);
printf("Age: %d years
", age);
printf("Current GPA: %.2f
", gpa);
printf("========================================
");
return 0;
}
Concept Explanation:
This beginner task demonstrates the use of escape sequences like (horizontal tab) and
(newline) covered in Lab 1. It combines user input with formatted specifiers %d and %f to render a structured ASCII badge layout on the console screen.
C Task 3: Square Perimeter and Area Calculator
Question: Write a C program to calculate the perimeter and area of a square. Prompt the user to enter the side length of the square as a float value. Calculate the perimeter using Perimeter = 4 * side and area using Area = side * side, and display both results.
Solution:
#include <stdio.h>
int main() {
float side, perimeter, area;
printf("Enter side length of the square (meters): ");
scanf("%f", &side);
perimeter = 4.0f * side;
area = side * side;
printf("
--- Square Geometric Properties ---
");
printf("Perimeter: %.2f meters
", perimeter);
printf("Area: %.2f square meters
", area);
return 0;
}
Concept Explanation:
This beginner task practices declaring floating-point variables and evaluating fundamental multiplication equations from Lab 1. It prompts the user via scanf() and outputs calculated square properties cleanly.
C Task 4: Simple Temperature Converter
Question: Write a C program that converts a temperature from Celsius to Kelvin. Prompt the user to enter the temperature in Celsius (float). Calculate the Kelvin temperature using Kelvin = Celsius + 273.15 and display the converted temperature.
Solution:
#include <stdio.h>
int main() {
float celsius, kelvin;
printf("Enter temperature in Celsius (°C): ");
scanf("%f", &celsius);
kelvin = celsius + 273.15f;
printf("
--- Temperature Conversion ---
");
printf("%.2f °C = %.2f K
", celsius, kelvin);
return 0;
}
Concept Explanation:
This beginner program reinforces simple variable addition and floating-point I/O formatting from Lab 1. It accepts user input for temperature and computes the corresponding Kelvin value.
C Task 5: Data Type Size Viewer
Question: Write a C program that demonstrates memory storage inspection. Declare one variable of each primitive type: char, int, float, and double. Print the exact storage memory size of each variable in bytes using the sizeof operator.
Solution:
#include <stdio.h>
int main() {
char letter = 'A';
int count = 100;
float score = 95.5f;
double balance = 12500.75;
printf("--- Memory Storage Sizes (sizeof) ---
");
printf("Size of char variable: %d byte
", (int)sizeof(letter));
printf("Size of int variable: %d bytes
", (int)sizeof(count));
printf("Size of float variable: %d bytes
", (int)sizeof(score));
printf("Size of double variable: %d bytes
", (int)sizeof(balance));
return 0;
}
Concept Explanation:
This beginner program introduces the sizeof operator taught in Lab 1. By outputting sizeof results, students observe how the compiler allocates memory space for standard primitive data types.
C Task 6: Currency Exchange Converter
Question: Write a C program to convert United States Dollars (USD) to Euros (EUR). Declare a constant exchange rate of 1 USD = 0.92 EUR using the const keyword. Prompt the user to enter an amount in USD, calculate the equivalent Euro amount, and display both values formatted to two decimal places.
Solution:
#include <stdio.h>
int main() {
const double USD_TO_EUR = 0.92;
double usdAmount, eurAmount;
printf("Enter currency amount in USD ($): ");
scanf("%lf", &usdAmount);
eurAmount = usdAmount * USD_TO_EUR;
printf("
--- Financial Exchange Result ---
");
printf("USD Amount: $%.2lf
", usdAmount);
printf("Conversion Rate: 1 USD = %.2lf EUR
", USD_TO_EUR);
printf("Equivalent EUR: %.2lf EUR
", eurAmount);
return 0;
}
Concept Explanation:
This medium task teaches constant variable declaration using the const modifier as outlined in Lab 1. It demonstrates safe programming by preventing modification of fixed exchange rates while performing floating-point multiplication.
C Task 7: Sales Tax and Discount Calculator
Question: Write a C program to calculate the final price of a store item after applying a promotional discount percentage followed by a sales tax percentage. Prompt the user for original item price ($), discount percentage (e.g., 15%), and tax percentage (e.g., 8%). Calculate the discounted subtotal, tax amount, and final net payable price.
Solution:
#include <stdio.h>
int main() {
double originalPrice, discountPercent, taxPercent;
double discountAmount, discountedSubtotal, taxAmount, finalPrice;
printf("Enter original item price ($): ");
scanf("%lf", &originalPrice);
printf("Enter promotional discount percentage (%%): ");
scanf("%lf", &discountPercent);
printf("Enter sales tax percentage (%%): ");
scanf("%lf", &taxPercent);
discountAmount = originalPrice * (discountPercent / 100.0);
discountedSubtotal = originalPrice - discountAmount;
taxAmount = discountedSubtotal * (taxPercent / 100.0);
finalPrice = discountedSubtotal + taxAmount;
printf("
--- Retail Sales Price Breakdown ---
");
printf("Original Price: $%.2lf
", originalPrice);
printf("Discount Amount: -$%.2lf
", discountAmount);
printf("Subtotal after Discount: $%.2lf
", discountedSubtotal);
printf("Sales Tax Amount: +$%.2lf
", taxAmount);
printf("Final Net Payable: $%.2lf
", finalPrice);
return 0;
}
Concept Explanation:
This medium program practices multi-step arithmetic expressions and percentage operations from Lab 1. It demonstrates intermediate variable storage to track subtotal calculations before producing a detailed financial summary.
C Task 8: Seconds to Hours, Minutes, and Seconds Converter
Question: Write a C program that converts a given duration in total seconds into hours, minutes, and remaining seconds. Prompt the user for an integer number of total seconds, and use integer division (/) and modulo operator (%) to compute the breakdown.
Solution:
#include <stdio.h>
int main() {
int totalSeconds, hours, minutes, seconds, remainder;
printf("Enter total time duration in seconds: ");
scanf("%d", &totalSeconds);
hours = totalSeconds / 3600;
remainder = totalSeconds % 3600;
minutes = remainder / 60;
seconds = remainder % 60;
printf("
--- Time Breakdown ---
");
printf("%d seconds = %d Hour(s), %d Minute(s), and %d Second(s)
",
totalSeconds, hours, minutes, seconds);
return 0;
}
Concept Explanation:
This medium problem practices integer arithmetic operations, specifically division (/) for quotient extraction and modulo (%) for remainder determination as taught in Lab 1. It converts a single scalar count into a multi-unit time breakdown.
C Task 9: Swap Two Registers Without Temporary Memory
Question: Write a C program that inputs two integer values into variables a and b. Swap their stored values using arithmetic addition and subtraction without creating any additional temporary variable. Display the values of a and b before and after performing the swap.
Solution:
#include <stdio.h>
int main() {
int a, b;
printf("Enter first integer (a): ");
scanf("%d", &a);
printf("Enter second integer (b): ");
scanf("%d", &b);
printf("
Before Swapping: a = %d, b = %d
", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("After Swapping: a = %d, b = %d
", a, b);
return 0;
}
Concept Explanation:
This difficult task enhances logical variable manipulation learned in Lab 1. Unlike basic swapping using a temporary variable, it challenges students to modify in-place memory values using algebraic arithmetic steps (a = a + b, b = a – b, a = a – b).
C Task 10: Final Velocity and Displacement Estimator
Question: Write a C program to calculate physical motion parameters. Prompt the user for initial velocity u (m/s), uniform acceleration a (m/s^2), and time elapsed t (seconds). Calculate the final velocity using v = u + a * t and displacement distance using s = u * t + 0.5 * a * t^2. Display both physics results.
Solution:
#include <stdio.h>
int main() {
double u, a, t, v, s;
printf("Enter initial velocity u (m/s): ");
scanf("%lf", &u);
printf("Enter uniform acceleration a (m/s^2): ");
scanf("%lf", &a);
printf("Enter time elapsed t (seconds): ");
scanf("%lf", &t);
v = u + (a * t);
s = (u * t) + (0.5 * a * t * t);
printf("
--- Physics Kinematic Calculations ---
");
printf("Final Velocity (v): %.2lf m/s
", v);
printf("Total Displacement (s): %.2lf meters
", s);
return 0;
}
Concept Explanation:
This challenging task applies algebraic formula translation using double variables and operator precedence rules from Lab 1. It translates real-world physics formulas into working C code expressions.
C++ Programming – 10 Unique Tasks
C++ Task 1: Rectangular Room Carpet Cost
Question: Write a C++ program to compute the area and carpet installation cost for a rectangular room. Prompt the user for room length (meters), width (meters), and carpet cost per square meter ($). Calculate room area = length * width and total cost = area * carpet cost, and display the result.
Solution:
#include <iostream>
using namespace std;
int main() {
double length, width, costPerSqMeter;
cout << "Enter room length in meters: ";
cin >> length;
cout << "Enter room width in meters: ";
cin >> width;
cout << "Enter carpet cost per square meter ($): ";
cin >> costPerSqMeter;
double area = length * width;
double totalCost = area * costPerSqMeter;
cout << "
--- Carpet Installation Summary ---" << endl;
cout << "Room Area: " << area << " sq meters" << endl;
cout << "Total Carpet Cost: $" << totalCost << endl;
return 0;
}
Concept Explanation:
This beginner program introduces standard C++ input and output streams using cin and cout from Lab 1 concepts. It declares floating-point variables, prompts the user for room dimensions, and computes basic area and cost equations.
C++ Task 2: Restaurant Menu Item Receipt Display
Question: Write a C++ program that formats a restaurant order item receipt. Prompt the user to enter an integer item code, item quantity (int), and unit price (double). Use stream insertion operators with escape sequences ( ,
) to present a clean formatted receipt block.
Solution:
#include <iostream>
using namespace std;
int main() {
int itemCode, quantity;
double unitPrice;
cout << "Enter 3-digit Item Code: ";
cin >> itemCode;
cout << "Enter Quantity Ordered: ";
cin >> quantity;
cout << "Enter Unit Price per Item ($): ";
cin >> unitPrice;
double totalPrice = quantity * unitPrice;
cout << "
----------------------------------------" << endl;
cout << " RESTAURANT ORDER RECEIPT" << endl;
cout << "----------------------------------------" << endl;
cout << "Item Code: " << itemCode << endl;
cout << "Quantity: " << quantity << endl;
cout << "Unit Price: $" << unitPrice << endl;
cout << "Total Cost: $" << totalPrice << endl;
cout << "----------------------------------------" << endl;
return 0;
}
Concept Explanation:
This beginner program practices C++ stream output formatting and escape sequence alignment ( and endl) matching Lab 1 topics. It accepts multi-type user input via cin and outputs a nicely aligned receipt block.
C++ Task 3: Circle Circumference Calculator
Question: Write a C++ program that computes the circumference of a circle. Prompt the user to enter the radius of the circle as a double value. Calculate the circumference using Circumference = 2 * PI * radius where PI = 3.14159, and display the result.
Solution:
#include <iostream>
using namespace std;
int main() {
double radius, circumference;
const double PI = 3.14159;
cout << "Enter circle radius (meters): ";
cin >> radius;
circumference = 2.0 * PI * radius;
cout << "
--- Circle Circumference Result ---" << endl;
cout << "Radius: " << radius << " meters" << endl;
cout << "Circumference: " << circumference << " meters" << endl;
return 0;
}
Concept Explanation:
This beginner task demonstrates declaring floating-point variables and constant modifiers in C++ from Lab 1. It reads the radius via cin and displays the computed circle perimeter.
C++ Task 4: Simple Speed Calculator
Question: Write a C++ program to calculate vehicle travel speed. Prompt the user to input distance traveled in kilometers (double) and time taken in hours (double). Calculate speed using Speed = Distance / Time and output the average speed in km/h.
Solution:
#include <iostream>
using namespace std;
int main() {
double distance, time, speed;
cout << "Enter distance traveled (km): ";
cin >> distance;
cout << "Enter time taken (hours): ";
cin >> time;
speed = distance / time;
cout << "
--- Speed Calculation ---" << endl;
cout << "Average Speed: " << speed << " km/h" << endl;
return 0;
}
Concept Explanation:
This beginner program practices basic division arithmetic and variable storage in C++ based on Lab 1 principles. It prompts for distance and time parameters to evaluate average speed.
C++ Task 5: Hardware Memory Footprint Evaluator
Question: Write a C++ program that evaluates data type memory allocation sizes on your machine. Declare variables of char, int, float, and double types, assign values to them, and output the size in bytes of each variable using the C++ sizeof operator.
Solution:
#include <iostream>
using namespace std;
int main() {
char letter = 'Z';
int count = 1000;
float frequency = 2.4f;
double memoryBytes = 8589934592.0;
cout << "--- Variable Values ---" << endl;
cout << "Letter: " << letter << endl;
cout << "Count: " << count << endl;
cout << "Frequency: " << frequency << " GHz" << endl;
cout << "Memory Bytes: " << memoryBytes << endl;
cout << "
--- Type Storage Sizes (sizeof) ---" << endl;
cout << "Size of char: " << sizeof(letter) << " byte" << endl;
cout << "Size of int: " << sizeof(count) << " bytes" << endl;
cout << "Size of float: " << sizeof(frequency) << " bytes" << endl;
cout << "Size of double: " << sizeof(memoryBytes) << " bytes" << endl;
return 0;
}
Concept Explanation:
This beginner program demonstrates data type memory footprints in C++ using the sizeof operator as explained in Lab 1. It shows how the compiler allocates memory for fundamental C++ primitive data types.
C++ Task 6: Distance Unit Converter
Question: Write a C++ program to convert distance measured in meters to feet. Define a constant conversion ratio METERS_TO_FEET = 3.28084 using const double. Input distance in meters from the user, compute equivalent feet, and print the result.
Solution:
#include <iostream>
using namespace std;
int main() {
const double METERS_TO_FEET = 3.28084;
double meters, feet;
cout << "Enter distance in meters: ";
cin >> meters;
feet = meters * METERS_TO_FEET;
cout << "
--- Unit Conversion Result ---" << endl;
cout << meters << " meters = " << feet << " feet" << endl;
return 0;
}
Concept Explanation:
This medium task practices constant variable creation using the const qualifier in C++ from Lab 1. It performs unit conversion arithmetic while preventing accidental modification of constant conversion factors.
C++ Task 7: Student Exam Percentage & Aggregate Calculator
Question: Write a C++ program to compute academic aggregate marks. Prompt the user for marks obtained in three subjects (each out of 100). Calculate the total obtained score out of 300 and compute overall score percentage. Output total marks and percentage score.
Solution:
#include <iostream>
using namespace std;
int main() {
double sub1, sub2, sub3;
cout << "Enter marks for Subject 1 (out of 100): ";
cin >> sub1;
cout << "Enter marks for Subject 2 (out of 100): ";
cin >> sub2;
cout << "Enter marks for Subject 3 (out of 100): ";
cin >> sub3;
double totalScore = sub1 + sub2 + sub3;
double percentage = (totalScore / 300.0) * 100.0;
cout << "
--- Student Marksheet Summary ---" << endl;
cout << "Total Obtained Score: " << totalScore << " / 300" << endl;
cout << "Overall Percentage: " << percentage << " %" << endl;
return 0;
}
Concept Explanation:
This medium program focuses on multi-variable summation and percentage equations in C++ following Lab 1 concepts. Using floating-point literal division (300.0) ensures accurate decimal score output.
C++ Task 8: Days to Years, Weeks, and Days Breakdown
Question: Write a C++ program that converts a given integer number of total days into equivalent years, weeks, and remaining days. Assume 1 year = 365 days and 1 week = 7 days. Display the parsed duration breakdown.
Solution:
#include <iostream>
using namespace std;
int main() {
int totalDays, years, weeks, days, remainder;
cout << "Enter total number of days: ";
cin >> totalDays;
years = totalDays / 365;
remainder = totalDays % 365;
weeks = remainder / 7;
days = remainder % 7;
cout << "
--- Calendar Conversion Summary ---" << endl;
cout << totalDays << " Days = " << years << " Year(s), "
<< weeks << " Week(s), and " << days << " Day(s)" << endl;
return 0;
}
Concept Explanation:
This medium task practices integer quotient division (/) and modulo remainder (%) arithmetic in C++ based on Lab 1. It extracts multi-level calendar components from a single total day count.
C++ Task 9: Coordinates Swap for Game Characters
Question: Write a C++ program that takes two 2D coordinate positions x and y for a game character and swaps their integer values without using a temporary third variable. Display coordinates before and after the swap.
Solution:
#include <iostream>
using namespace std;
int main() {
int x, y;
cout << "Enter X coordinate: ";
cin >> x;
cout << "Enter Y coordinate: ";
cin >> y;
cout << "
Before Swapping: X = " << x << ", Y = " << y << endl;
x = x + y;
y = x - y;
x = x - y;
cout << "After Swapping: X = " << x << ", Y = " << y << endl;
return 0;
}
Concept Explanation:
This difficult problem reinforces algebraic variable manipulation logic in C++ from Lab 1. It swaps integer values in-place using arithmetic addition and subtraction expressions without declaring extra memory variables.
C++ Task 10: Kinetic and Potential Energy Evaluator
Question: Write a C++ program to compute physical mechanical energy components. Prompt the user for object mass m (kg), velocity v (m/s), and height h (meters). Use gravity constant g = 9.8 to compute Kinetic Energy KE = 0.5 * m * v^2 and Potential Energy PE = m * g * h. Display energy outputs.
Solution:
#include <iostream>
using namespace std;
int main() {
double m, v, h, ke, pe;
const double g = 9.8;
cout << "Enter object mass m (kg): ";
cin >> m;
cout << "Enter velocity v (m/s): ";
cin >> v;
cout << "Enter height h (meters): ";
cin >> h;
ke = 0.5 * m * v * v;
pe = m * g * h;
cout << "
--- Mechanical Energy Calculation ---" << endl;
cout << "Kinetic Energy (KE): " << ke << " Joules" << endl;
cout << "Potential Energy (PE): " << pe << " Joules" << endl;
cout << "Total Mechanical Energy: " << (ke + pe) << " Joules" << endl;
return 0;
}
Concept Explanation:
This challenging task practices multi-term formula execution and floating-point computations in C++ from Lab 1. It computes kinetic and potential physical energy metrics using operator arithmetic rules.