HC Fall 2024
Additional Resources
In this lab, you will install Visual Studio Code (VS Code), set up MinGW (Minimalist GNU for Windows), and configure the system environment variables to allow seamless C programming.
Step 1: Install VS Code
Go to the official Visual Studio Code website.
Download the appropriate installer for your operating system (Windows).
Follow the installation prompts to install VS Code on your computer.
Step 2: Install MinGW
Visit the MinGW SourceForge page.
Download the latest MinGW installation file.
Once downloaded, run the MinGW setup.
In the installation manager, select the packages mingw-developer-toolkit and mingw32-base to ensure you have the compilers needed for C.
Click "Apply Changes" and wait for the installation to complete.
Step 2 (for Mac users): Install GCC on macOS
Open the Terminal app.
Install the Xcode Command Line Tools by running the following command. Then, follow the prompts to complete the installation. This will install GCC (GNU Compiler Collection) as part of the command-line tools.
xcode-select --install
Step 3: Configure Environment Variables
On your Windows system, open the Start Menu and type Environment.
Select Edit the System Environment Variables.
In the System Properties window, go to the Advanced tab and click on Environment Variables.
Under System Variables, scroll down to find the Path variable, and click on Edit....
In the Edit Environment Variables window, click New, and add the path to the MinGW bin folder. Click OK to save changes and close all windows.
C:\MinGW\bin
Step 3: Configure Environment Variables for macOS
1. Open the Terminal.
2. To ensure the path to GCC is recognized, you need to modify the .bash_profile or .zshrc file (depending on your shell).
3. In your terminal, run:
nano ~/.bash_profile
(If you're using zsh, use nano ~/.zshrc).
4. Add the following line to the file:
export PATH=/usr/local/bin:$PATH
5. Save the file (Ctrl + O, then Enter) and exit (Ctrl + X).
6. Run:
source ~/.bash_profile
(or source ~/.zshrc for zsh users) to apply the changes.
Step 4: Configure VS Code for C Programming
Open Visual Studio Code.
Install the C/C++ Extension:
Go to the Extensions tab (left sidebar or use Ctrl+Shift+X).
Search for C/C++ and install the extension by Microsoft.
Step 5: Fixing the scanf Issue in VS Code
Open VS Code and click on the Settings Gear icon at the bottom left corner.
In the search bar, type Run In Terminal.
Locate the setting Code Runner: Run in Terminal and check the box to enable it. This will ensure that your program executes in the integrated terminal, allowing for input operations like scanf to work properly.
Step 6: Testing the Setup
1. Open VS Code and create a new file named hello.c.
2. Write the following C program:
#include <stdio.h>
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
printf("You entered: %d\n", number);
return 0;
}
3. Save the file and open the integrated terminal (Ctrl + ~).
4. Compile the program by typing:
gcc hello.c -o hello
5. Run the compiled program by typing:
./hello
Ensure the program runs successfully and accepts input. Submit a screenshot of your screen showing the code and the output.
Exercise 1: Writing Your First C Program
Understand how a basic C program works, including the use of #include, main(), and printf().
Write a simple C program that prints the following to the console:
“Hello, World!”
“This is my first C program.”
Use #include <stdio.h> to import the necessary header files.
Inside main(), use printf() to output the above text to the console.
#include <stdio.h>
int main(void) {
printf("Hello, World!\n");
printf("This is my first C program.\n");
return 0;
}
Exercise 2: Working with Variables and Data Types
Learn to declare variables, assign values, and use them in expressions.
Declare variables of the following types: int, float, and char.Declare one variable for each of the following: an integer, a floating-point number, and a character.
Assign values to these variables and print them using printf().
#include <stdio.h>
int main(void) {
int num = 5;
float pi = 3.14;
char letter = 'A';
printf("Integer: %d\n", num);
printf("Float: %.2f\n", pi);
printf("Character: %c\n", letter);
return 0;
}
Exercise 3: Input/Output with scanf() and printf()
Getting user input using scanf() and displaying it with printf().
Write a program that prompts the user to enter an integer and a floating-point number. Then, print the entered values back to the console.
Use scanf() to capture the user’s input and then use printf() to print the values entered by the user.
#include <stdio.h>
int main(void) {
int num;
float decimal;
printf("Enter an integer: ");
scanf("%d", &num);
printf("Enter a floating-point number: ");
scanf("%f", &decimal);
printf("You entered: %d and %.2f\n", num, decimal);
return 0;
}
Exercise 4: Arithmetic Operations
Performing arithmetic operations in C using different data types.
Write a program that takes two integers from the user using scanf(). Then perform addition, subtraction, multiplication, and division on these integers and display the results using printf().
#include <stdio.h>
int main(void) {
int num1, num2;
printf("Enter two integers: ");
scanf("%d %d", &num1, &num2);
printf("Sum: %d\n", num1 + num2);
printf("Difference: %d\n", num1 - num2);
printf("Product: %d\n", num1 * num2);
if (num2 != 0) {
printf("Division: %d\n", num1 / num2);
} else {
printf("Cannot divide by zero!\n");
}
return 0;
}
Exercise 5: Understanding Constants and Preprocessor Directives
Learn how to use constants and preprocessor directives in C.
Write a program that defines a constant PI = 3.1416 using #define. Use the #define directive to declare PI.
The program should ask the user for the radius of a circle and then calculate and print the circumference using the formula C = 2 * PI * r.
#include <stdio.h>
#define PI 3.1416
int main(void) {
float radius, circumference;
printf("Enter the radius of the circle: ");
scanf("%f", &radius);
circumference = 2 * PI * radius;
printf("The circumference of the circle is: %.2f\n", circumference);
return 0;
}
The purpose of this lab is to test and reinforce your understanding of C expressions, including the use of operators, operator precedence, type casting, and assignment operations. You will write several small programs and answer related questions.
Create a New C Project:
Set up your project in VS Code using MinGW.
Create a new C file named w3_lab.c
Part 1: Arithmetic and Mixed Expressions
Write a program that performs the following operations on two integers and two doubles:
int a = 10, b = 3;
double x = 12.5, y = 4.2;
Compute and display the results of the following expressions:
a + b
a - b
a * b
a / b
a % b
x + y
x - y
x / y
a / x
b * y
Include print statements to show the results of each operation.
Part 2: Type Casting and Mixed Expressions
Continue your program to cast one of the integers to a double when performing mixed operations. Specifically:
Use type casting for the following:
(double)a / b
a / (double)b
Part 3: Operator Precedence
Add code to evaluate the following expressions. Use parentheses to ensure the correct order of operations where needed:
int result;
result = a + b * a - b;
result = (a + b) * (a - b);
result = a + (b - a) * (b + a);
Print the results of each expression.
Part 4: Compound Assignment and Increment/Decrement Operators
Write a program that uses compound assignment operators (+=, -=, *=, /=, %=) to modify the value of an integer variable. For example:
int value = 5;
value += 10;
value -= 2;
value *= 3;
value /= 2;
value %= 3;
Also, demonstrate the use of the increment (++) and decrement (--) operators in both prefix and postfix forms.
Part 5: Calculate the Perimeter and Area of a Rectangle
Write a C program that prompts the user to enter the width and length of a rectangle.
Use the following formulas to calculate the perimeter and area:
Perimeter = 2 * (width + length)
Area = width * length
Output the calculated perimeter and area.
Submission Requirements:
Submit your w3_lab.c file with comments explaining each section.
Submit screenshots showing the output as a PDF file
Here are some simple C examples. These examples cover various simple programming concepts, such as loops, conditionals, and mathematical operations, in C:
Check if a number is even or odd
#include <stdio.h>
int main() {
int num = 5;
if (num % 2 == 0) {
printf("Even\n");
} else {
printf("Odd\n");
}
return 0;
}
Find the maximum of two numbers
#include <stdio.h>
int main() {
int a = 10, b = 20;
if (a > b) {
printf("Max is %d\n", a);
} else {
printf("Max is %d\n", b);
}
return 0;
}
Check if a number is positive, negative, or zero
#include <stdio.h>
int main() {
int x = -3;
if (x > 0) {
printf("Positive\n");
} else if (x < 0) {
printf("Negative\n");
} else {
printf("Zero\n");
}
return 0;
}
Simple switch statement for grade evaluation
#include <stdio.h>
int main() {
char grade = 'A';
switch (grade) {
case 'A': printf("Excellent!\n"); break;
case 'B': printf("Good!\n"); break;
default: printf("Needs Improvement\n");
}
return 0;
}
Check if a number is divisible by 3
#include <stdio.h>
int main() {
int num = 9;
if (num % 3 == 0) {
printf("Divisible by 3\n");
} else {
printf("Not divisible by 3\n");
}
return 0;
}
Check if a character is a vowel
#include <stdio.h>
int main() {
char ch = 'a';
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
printf("Vowel\n");
} else {
printf("Consonant\n");
}
return 0;
}
Check for traffic light color
#include <stdio.h>
int main() {
char light = 'R'; // Change this to 'R', 'Y', or 'G'
switch (light) {
case 'R':
printf("Stop\n");
break;
case 'Y':
printf("Caution\n");
break;
case 'G':
printf("Go\n");
break;
default:
printf("Invalid color\n");
}
return 0;
}
Menu selection
#include <stdio.h>
int main() {
int choice;
printf("Enter 1, 2, or 3: ");
scanf("%d", &choice);
switch (choice) {
case 1: printf("Start\n"); break;
case 2: printf("Settings\n"); break;
case 3: printf("Exit\n"); break;
default: printf("Invalid choice\n");
}
return 0;
}
The goal of this lab exercise is to help you understand how to implement decision-making in C programs using if-else-if-else and switch statements. You will practice writing C programs that take user inputs and make decisions based on the conditions provided. You are required to write C programs for both exercises and compare the suitability of each conditional structure for different scenarios.
Exercise 1: If-Else-If-Else Decision Making
Write a C program that takes the marks obtained by a student in an exam as input and outputs the corresponding grade based on the following criteria:
Marks >= 90: Grade A+
Marks >= 80 and < 90: Grade A
Marks >= 70 and < 80: Grade B
Marks >= 60 and < 70: Grade C
Marks >= 50 and < 60: Grade D
Marks < 50: Fail
Create a new C file named grade_calculator_ifelse.c.
Use an if-else-if-else structure to decide the grade based on the student's marks.
Accept the student's marks as an integer input.
Display the corresponding grade as output.
If the user enters marks outside the range of 0 to 100, display an error message.
Include comments explaining your code.
Sample Output:
Enter marks obtained: 85
Grade: A
Exercise 2: Switch Statement for Day of the Week
Write a C program that takes an integer input (1–7) representing a day of the week and displays the name of the day. Use a switch statement to make the decision. The mapping is as follows:
1: Sunday
2: Monday
3: Tuesday
4: Wednesday
5: Thursday
6: Friday
7: Saturday
If the input is outside the range of 1 to 7, display an error message.
Create a new C file named day_of_week_switch.c.
Use a switch statement to determine the day of the week based on the integer input.
Include default cases for invalid input (values not between 1 and 7).
Ensure that your program outputs the correct day or an appropriate error message.
Include comments to explain the logic of your program.
Sample Output:
Enter a number (1-7): 3
Day of the Week: Tuesday
Exercise 3: Simple Calculator Using Switch
Create a simple calculator program that allows the user to choose a mathematical operation (+, -, *, /, %) and performs that operation on two user-provided numbers. Implement the decision logic using a switch statement.
Instructions:
Create a new C file named simple_calculator_switch.c.
Use a switch statement to handle the user's choice of operation.
Accept two numbers from the user.
Display the result of the operation.
Handle division by zero with an appropriate error message.
Sample Output:
Enter first number: 10
Enter second number: 2
Enter operation (+, -, *, /, %): /
Result: 5
Submission Requirements:
Submit your w4lab.c file with comments explaining each section.
Submit screenshots showing the output as a PDF file
Introduction to Loops
In C programming, loops allow us to execute a block of code repeatedly, either a known or unknown number of times, based on a condition. Loops are essential in programming, allowing you to automate repetitive tasks.
There are three primary types of loops in C: for, while, and do-while loops. These loops provide the mechanism for performing iterative tasks like calculations, input/output handling, and more. Whether you're summing numbers, printing tables, or balancing checkbooks, loops are invaluable tools for efficient code execution. Mastering the for, while, and do-while loops will enable you to handle various scenarios where iterations are needed.
The for Loop
The for loop is used when the number of iterations is known beforehand. It is especially useful in counting loops where you need to iterate a fixed number of times. The loop consists of three parts:
Initialization: This is executed once at the start.
Condition: Checked before each iteration; the loop continues as long as this is true.
Update: Executes after each iteration.
Syntax:
for (initialization; condition; update) {
// Loop body
}
Example:
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
printf("%d\n", i);
}
return 0;
}
In this example, the loop prints numbers from 1 to 10.
The while Loop
The while loop is used when the number of iterations is not known in advance, but the loop must continue until a certain condition is met. The condition is checked at the beginning of each iteration, and the loop will run as long as the condition remains true.
Syntax:
while (condition) {
// Loop body
}
Example:
#include <stdio.h>
int main() {
int i = 1;
while (i <= 10) {
printf("%d\n", i);
i++;
}
return 0;
}
In this example, the loop prints numbers from 1 to 10 using a while loop.
The do-while Loop
The do-while loop is similar to the while loop, but with one key difference: the body of the loop is executed at least once, even if the condition is false, because the condition is checked after the loop body.
Syntax:
do {
// Loop body
} while (condition);
Example:
#include <stdio.h>
int main() {
int i = 1;
do {
printf("%d\n", i);
i++;
} while (i <= 10);
return 0;
}
In this example, the loop will print numbers from 1 to 10, and the loop body is guaranteed to execute at least once.
Comparing Loops
For Loop: Best used when the number of iterations is known.
While Loop: Used when the number of iterations is unknown and based on a condition.
Do-While Loop: Useful when the loop body must execute at least once, regardless of the condition.
Break and Continue Statements
break: Terminates the loop prematurely.
continue: Skips the current iteration and proceeds with the next iteration of the loop.
Example of break:
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
printf("%d\n", i);
}
return 0;
}
This loop stops execution when i equals 5.
Example of continue:
#include <stdio.h>
int main() {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
continue;
}
printf("%d\n", i);
}
return 0;
}
This loop skips the iteration when i equals 5, but continues with the remaining iterations.
Practical Examples of Loops
Example 1: Summing a Series of Numbers
This program continuously reads integers from the user and adds them until the user enters 0.
#include <stdio.h>
int main() {
int n, sum = 0;
printf("Enter integers (0 to terminate): ");
scanf("%d", &n);
while (n != 0) {
sum += n;
scanf("%d", &n);
}
printf("The sum is: %d\n", sum);
return 0;
}
In this example, a while loop keeps reading and summing numbers until the user enters 0, terminating the loop(sum).
Example 2: Printing a Table of Squares
This program prints the squares of numbers up to a user-specified limit using a while loop.
#include <stdio.h>
int main() {
int i, n;
printf("Enter number of entries in table: ");
scanf("%d", &n);
i = 1;
while (i <= n) {
printf("%10d%10d\n", i, i * i);
i++;
}
return 0;
}
The program prompts the user to input a number, and then prints the square of each number from 1 to the input(square).
Example 3: Checking the Balance of a Checkbook
This program simulates a checkbook balance by allowing the user to input credits and debits and view the balance.
#include <stdio.h>
int main() {
int cmd;
float balance = 0.0f, credit, debit;
printf("*** Checkbook-balancing program ***\n");
printf("Commands: 0=clear, 1=credit, 2=debit, 3=balance, 4=exit\n\n");
for (;;) {
printf("Enter command: ");
scanf("%d", &cmd);
switch (cmd) {
case 0:
balance = 0.0f;
break;
case 1:
printf("Enter amount of credit: ");
scanf("%f", &credit);
balance += credit;
break;
case 2:
printf("Enter amount of debit: ");
scanf("%f", &debit);
balance -= debit;
break;
case 3:
printf("Current balance: $%.2f\n", balance);
break;
case 4:
return 0;
default:
printf("Invalid command.\n");
}
}
}
This program continually accepts commands from the user to modify and display the balance of a checkbook(checking).
Example 4: Calculating the Number of Digits in an Integer
This program calculates the number of digits in a given integer using a do-while loop.
#include <stdio.h>
int main() {
int digits = 0, n;
printf("Enter a nonnegative integer: ");
scanf("%d", &n);
do {
n /= 10;
digits++;
} while (n > 0);
printf("The number has %d digit(s).\n", digits);
return 0;
}
In this program, the do-while loop ensures that the loop body executes at least once, making it suitable for calculating the number of digits(numdigits).
Key Takeaways:
Use for loops when the number of iterations is known.
Use while loops for indefinite iterations until a condition is met.
Use do-while loops when the loop body must execute at least once.
Understanding and implementing loops correctly is fundamental to writing effective C programs.
Lab Exercise: Loops and Control Structures in C
In this lab, you will practice using loops in C by implementing a series of small programs that utilize the for, while, and do-while loops. By the end of this lab, you will be able to apply loops to solve different problems and understand how control structures such as break and continue work.
Task 1: Sum of Numbers Using a while Loop
Instructions:
Write a program that sums a series of numbers entered by the user. The program will stop reading numbers when the user enters 0.
Steps:
Declare variables n (to store user input) and sum (to store the running total).
Use a while loop to repeatedly read numbers and add them to sum.
The loop should terminate when the user enters 0.
Display the total sum at the end.
Expected Output:
Enter integers (0 to terminate): 5 3 8 0
The sum is: 16
Task 2: Print a Table of Squares Using a while Loop
Instructions:
Write a program that prints a table of squares for numbers from 1 to a user-specified value using a while loop.
Steps:
Declare variables i (loop counter) and n (user input for the number of entries).
Use a while loop to print the squares of each number from 1 to n.
Display the table in a formatted way, with two columns: one for the number and the other for its square.
Expected Output:
Enter the number of entries: 5
1 1
2 4
3 9
4 16
5 25
Task 3: Checkbook Balancing Program Using for and switch
Instructions:
Write a checkbook balancing program that allows the user to add credits, subtract debits, and check the balance. The program should continuously prompt the user for commands until they choose to exit.
Steps:
Use a for loop with an infinite condition (for(;;)), and inside the loop:
Prompt the user for a command (0=clear, 1=credit, 2=debit, 3=balance, 4=exit).
Use a switch statement to handle the different commands:
0 should reset the balance to 0.
1 should add a credit amount to the balance.
2 should subtract a debit amount from the balance.
3 should display the current balance.
4 should terminate the program.
Use break statements appropriately to exit the loop or terminate the program.
Expected Output:
*** Checkbook Balancing Program ***
Commands: 0=clear, 1=credit, 2=debit, 3=balance, 4=exit
Enter command: 1
Enter amount of credit: 500
Enter command: 2
Enter amount of debit: 200
Enter command: 3
Current balance: $300.00
Enter command: 4
Task 4: Count the Number of Digits in an Integer Using a do-while Loop
Instructions:
Write a program that counts the number of digits in a user-entered integer using a do-while loop.
Steps:
Prompt the user to input an integer.
Use a do-while loop to count the number of digits in the integer.
Ensure that the loop executes at least once to handle single-digit numbers.
Expected Output:
Enter a nonnegative integer: 12345
The number has 5 digit(s).
Task 5: Multiples of 3 Using a for Loop
Instructions:
Write a program that prints all multiples of 3 from 1 to 99 in a matrix format with 5 columns.
Steps:
Use a for loop to iterate through the numbers from 1 to 99.
Print only the multiples of 3.
Ensure that 5 multiples are printed per line using formatting.
Expected Output:
3 6 9 12 15
18 21 24 27 30
33 36 39 42 45
48 51 54 57 60
63 66 69 72 75
78 81 84 87 90
93 96 99
Submission Requirements:
You are required to submit two files, .c file (source code) and a .pdf (screenshots) file
Submit ONE source code file named w6lab.c with comments explaining each section.
Submit ONE pdf file with screenshots showing the output of each exercise. T
Here are some examples focused on functions in C programming that you can use as references while completing the exercises in the lab. These examples will help you understand how to define, call, and work with functions, but they don't directly solve the tasks in the lab.
Example 1: Function to Add Two Numbers
This example demonstrates a simple function that adds two numbers and returns the result.
#include <stdio.h>
// Function to add two integers
int add_numbers(int a, int b) {
return a + b; // Return the sum of a and b
}
int main() {
int num1 = 5, num2 = 10;
int result = add_numbers(num1, num2); // Function call
printf("Sum: %d\n", result); // Output the result
return 0;
}
Example 2: Function with No Return Value (void Function)
This example shows how to create a function that doesn’t return a value. The function simply prints a greeting message.
#include <stdio.h>
// Function that prints a greeting message
void print_greeting(void) {
printf("Hello, welcome to the C programming course!\n");
}
int main() {
print_greeting(); // Call the function
return 0;
}
Example 3: Function to Check if a Number is Positive or Negative
This example demonstrates a function that checks if a given number is positive, negative, or zero and prints the result.
#include <stdio.h>
// Function to check if a number is positive, negative, or zero
void check_number(int n) {
if (n > 0) {
printf("The number is positive.\n");
} else if (n < 0) {
printf("The number is negative.\n");
} else {
printf("The number is zero.\n");
}
}
int main() {
int num = -5;
check_number(num); // Function call
return 0;
}
Example 4: Function to Multiply Two Numbers
This example shows how to create a function that multiplies two numbers and returns the result.
#include <stdio.h>
// Function to multiply two integers
int multiply(int a, int b) {
return a * b;
}
int main() {
int num1 = 4, num2 = 7;
int result = multiply(num1, num2); // Function call
printf("Multiplication Result: %d\n", result); // Output the result
return 0;
}
Example 5: Recursive Function to Calculate Factorial
This example introduces recursion, where a function calls itself to calculate the factorial of a number.
#include <stdio.h>
// Recursive function to calculate the factorial of a number
int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case: factorial of 0 or 1 is 1
}
return n * factorial(n - 1); // Recursive call
}
int main() {
int num = 5;
int result = factorial(num); // Function call
printf("Factorial of %d is %d\n", num, result); // Output the result
return 0;
}
Example 6: Function with Multiple Return Values using Pointers
This example demonstrates how you can use pointers to return multiple values from a function by modifying values passed by reference.
#include <stdio.h>
// Function to calculate the square and cube of a number
void square_and_cube(int n, int *square, int *cube) {
*square = n * n; // Calculate square
*cube = n * n * n; // Calculate cube
}
int main() {
int num = 3;
int square_result, cube_result;
square_and_cube(num, &square_result, &cube_result); // Function call with pointers
printf("Square of %d is %d\n", num, square_result); // Output square
printf("Cube of %d is %d\n", num, cube_result); // Output cube
return 0;
}
Example 7: Function to Print a Custom Message a Specified Number of Times
This example demonstrates a function that prints a message multiple times. It introduces the concept of loops within functions.
#include <stdio.h>
// Function to print a message n times
void print_message(int n) {
for (int i = 0; i < n; i++) {
printf("This is a custom message!\n");
}
}
int main() {
int times = 3;
print_message(times); // Function call
return 0;
}
Example 8: Using bool in a Function to Return True/False
This example introduces the bool type and how to return true or false based on a condition (whether a number is divisible by 3).
#include <stdio.h>
#include <stdbool.h> // For using bool, true, false
// Function to check if a number is divisible by 3
bool is_divisible_by_three(int n) {
return n % 3 == 0; // Returns true if divisible by 3, otherwise false
}
int main() {
int num = 9;
if (is_divisible_by_three(num)) {
printf("%d is divisible by 3.\n", num);
} else {
printf("%d is not divisible by 3.\n", num);
}
return 0;
}
Task 1: Countdown Timer
Create a recursive function to print a countdown from a specified number down to 1.
Steps:
Write a function called countdown that takes an integer n as a parameter.
The function should print "Countdown: n" and then call itself with n - 1 until n reaches 1.
In the main() function, call the countdown function with an argument of 10.
Expected Output:
Countdown: 10
Countdown: 9
Countdown: 8
...
Countdown: 1
Task 2: Display a Motivational Quote
Objective: Create a function to print an inspirational quote.
Steps:
Write a function called print_quote that takes no parameters and prints a motivational quote of your choice.
In the main() function, call print_quote to display the quote.
Expected Output:
The only way to do great work is to love what you do. – Steve Jobs
Task 3: Checking Even or Odd
Objective: Create a function to check if a number is even or odd.
Steps:
Write a function is_even that takes an integer as an argument and returns true if the number is even, and false otherwise.
In the main() function, prompt the user to enter a number.
Call the is_even function and display whether the number is even or odd.
Expected Output:
Enter a number: 24
The number is even.
Enter a number: 13
The number is odd.
Task 4: Sum of Two Numbers
Objective: Create a function that returns the sum of two numbers.
Steps:
Write a function sum that takes two integers as arguments and returns their sum.
In the main() function, prompt the user to enter two numbers.
Call the sum function with the two numbers and display the result.
Expected Output:
Enter two numbers: 12 8
Sum of the numbers: 20
Task 5: Recursive Fibonacci Sequence
Objective: Create a recursive function to calculate the Fibonacci sequence.
Steps:
Write a recursive function fibonacci that takes an integer n and returns the n-th Fibonacci number.
In the main() function, prompt the user to enter a number.
Call the fibonacci function and display the result.
Expected Output:
Enter a number: 6
The 6th Fibonacci number is 8
Task 6: Find Maximum of Two Numbers
Objective: Create a function that finds the maximum of two numbers.
Steps:
Write a function max that takes two integers as arguments and returns the larger of the two.
In the main() function, prompt the user to enter two numbers.
Call the max function and display the larger number.
Expected Output:
Enter two numbers: 45 32
The larger number is: 45
Submission Requirements:
You are required to submit two files, .c file (source code) and a .pdf (screenshots) file
Submit ONE source code file named w7lab.c with comments explaining each section.
Submit ONE pdf file with screenshots showing the output of each exercise.
Example 1: Basic Dice Roller Simulation - Simulates rolling a 6-sided die multiple times, storing the result in an external variable.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int dice_roll;
void roll_dice(void) {
dice_roll = (rand() % 6) + 1;
}
int main(void) {
srand(time(NULL));
char choice;
do {
roll_dice();
printf("You rolled a %d!\n", dice_roll);
printf("Roll again? (Y/N): ");
scanf(" %c", &choice);
} while (choice == 'Y' || choice == 'y');
return 0;
}
Example 2: Simple Age Categorizer - Categorizes a given age into a predefined age range.
#include <stdio.h>
void categorize_age(int age) {
if (age < 13)
printf("Child\n");
else if (age <= 19)
printf("Teenager\n");
else if (age <= 65)
printf("Adult\n");
else
printf("Senior\n");
}
int main(void) {
int age;
printf("Enter your age: ");
scanf("%d", &age);
categorize_age(age);
return 0;
}
Example 3: Shopping Discount Calculator - Determines if a purchase qualifies for a discount based on a spending threshold.
#include <stdio.h>
void apply_discount(double purchase) {
if (purchase > 100.0)
printf("Discount Applied! Your new total: $%.2f\n", purchase * 0.9);
else
printf("No discount applied. Total: $%.2f\n", purchase);
}
int main(void) {
double amount;
printf("Enter purchase amount: ");
scanf("%lf", &amount);
apply_discount(amount);
return 0;
}
Example 4: Temperature Conversion - Converts a given Celsius temperature to Fahrenheit and vice versa.
#include <stdio.h>
void convert_temperature(char type, double temp) {
if (type == 'C' || type == 'c')
printf("Fahrenheit: %.2f\n", temp * 9 / 5 + 32);
else
printf("Celsius: %.2f\n", (temp - 32) * 5 / 9);
}
int main(void) {
double temperature;
char scale;
printf("Enter temperature and scale (C/F): ");
scanf("%lf %c", &temperature, &scale);
convert_temperature(scale, temperature);
return 0;
}
Example 5: Simple Multiplication Quiz - Generates random numbers for a multiplication quiz.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void multiplication_quiz(void) {
int num1 = rand() % 10;
int num2 = rand() % 10;
int answer;
printf("What is %d * %d? ", num1, num2);
scanf("%d", &answer);
if (answer == num1 * num2)
printf("Correct!\n");
else
printf("Incorrect. The answer is %d.\n", num1 * num2);
}
int main(void) {
srand(time(NULL));
multiplication_quiz();
return 0;
}
Example 6 : Prime Number Checker - Checks if a given number is prime.
#include <stdio.h>
#include <stdbool.h>
bool is_prime(int num) {
if (num <= 1) return false;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0)
return false;
}
return true;
}
int main(void) {
int number;
printf("Enter a number to check if it's prime: ");
scanf("%d", &number);
if (is_prime(number))
printf("%d is a prime number.\n", number);
else
printf("%d is not a prime number.\n", number);
return 0;
}
Lab Exercise 1: Counter with Static and Global Variables
Create a program where the user inputs numbers that add to a cumulative total.
Use a static variable within a function to count how many times the function has been called.
Use a global variable to store the cumulative total.
Display the cumulative sum and the function call count after each input.
Expected Output:
Enter a number to add to the cumulative total: 5
Cumulative total: 5, Function called 1 times.
Enter a number to add to the cumulative total: 10
Cumulative total: 15, Function called 2 times.
Enter a number to add to the cumulative total: 3
Cumulative total: 18, Function called 3 times.
Do you want to add another number? (Y/N): N
Lab Exercise 2: Range Guessing Game
Write a program where the user guesses the range of a randomly generated number between 1 and 100.
Inform the user if their guessed range is correct or if they should guess higher or lower.
Display the number of attempts once the correct range is guessed.
Expected Output:
Guess the range for the secret number between 1 and 100.
Enter your guess (e.g., 20 50): 10 30
Too low; try a higher range.
Enter your guess (e.g., 20 50): 40 60
Correct! The secret number is within 40 to 60.
You found the correct range in 2 attempts.
Lab Exercise 3: Function-Based Calculator
Write a calculator program with options for addition, subtraction, multiplication, and division, each implemented in a separate function.
Use a main() menu to select an operation, enter two numbers, and call the relevant function.
Organize the program by placing function prototypes at the beginning and all function definitions after main.
Expected Output:
Select an operation:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter your choice: 1
Enter two numbers: 10 5
Result: 15.00
Select an operation:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter your choice: 3
Enter two numbers: 3 7
Result: 21.00
Select an operation:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter your choice: 5
Lab Exercise 4: Password Validator
Write a program that prompts the user for a password.
Check if the password meets the criteria: minimum length of 8 characters, contains uppercase and lowercase letters, and includes at least one number.
Provide feedback if the password is invalid and prompt the user to re-enter until it meets all criteria.
Expected Output:
Enter a password: abc123
Password must be at least 8 characters long.
Password must contain an uppercase letter.
Enter a password: Abc12345
Password is valid.
Lab Exercise 5: Function Scope Demonstration
Write a program with a global variable and two nested functions, each containing a local variable with the same name as the global variable.
Assign and print values for the local and global variables in each function to show how scope affects variable access.
Expected Output:
In main: global_var = 10
In outer_function: global_var = 10, local_var = 20
In inner_function: global_var = 10, local_var = 30
Find Longest Word in a Sentence
Program to find and print the longest word in a sentence provided by the user.
#include <stdio.h>
#include <string.h>
int main() {
char str[100], word[100], longest[100] = "";
int max_len = 0;
printf("Enter a sentence: ");
fgets(str, sizeof(str), stdin);
int i = 0, j = 0;
while (str[i] != '\0') {
if (str[i] != ' ' && str[i] != '\n') {
word[j++] = str[i];
} else {
word[j] = '\0';
if (strlen(word) > max_len) {
max_len = strlen(word);
strcpy(longest, word);
}
j = 0;
}
i++;
}
printf("Longest word: %s\n", longest);
return 0;
}
Count Word Frequency in a Sentence
Program to count the frequency of each word in a sentence.
#include <stdio.h>
#include <string.h>
int main() {
char str[100], word[20][20];
int i, j = 0, k = 0, count[20] = {0};
printf("Enter a sentence: ");
fgets(str, sizeof(str), stdin);
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == ' ' || str[i] == '\n') {
word[k][j] = '\0';
k++;
j = 0;
} else {
word[k][j++] = str[i];
}
}
for (i = 0; i < k; i++) {
count[i] = 1;
for (j = i + 1; j <= k; j++) {
if (strcmp(word[i], word[j]) == 0) {
count[i]++;
for (int temp = j; temp < k; temp++) {
strcpy(word[temp], word[temp + 1]);
}
k--;
}
}
}
for (i = 0; i <= k; i++) {
printf("'%s' appears %d times\n", word[i], count[i]);
}
return 0;
}
String Rotation
Program to rotate a string to the left by a specified number of characters.
#include <stdio.h>
#include <string.h>
void rotate_string(char str[], int n) {
int len = strlen(str);
char temp[100];
strcpy(temp, str + n);
strncat(temp, str, n);
temp[len] = '\0';
printf("Rotated string: %s\n", temp);
}
int main() {
char str[100];
int n;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
str[strlen(str) - 1] = '\0'; // Remove newline character
printf("Enter number of positions to rotate: ");
scanf("%d", &n);
rotate_string(str, n);
return 0;
}
Palindrome Checker
Program to check if a user-input string is a palindrome
#include <stdio.h>
#include <string.h>
int main() {
char str[100], reversed[100];
int len, isPalindrome = 1;
printf("Enter a string: ");
scanf("%s", str);
len = strlen(str);
for (int i = 0; i < len; i++) {
reversed[i] = str[len - i - 1];
}
reversed[len] = '\0';
for (int i = 0; i < len; i++) {
if (str[i] != reversed[i]) {
isPalindrome = 0;
break;
}
}
if (isPalindrome) {
printf("The string is a palindrome.\n");
} else {
printf("The string is not a palindrome.\n");
}
return 0;
}
Remove Spaces from a String
program that removes all spaces from a string provided by the user
#include <stdio.h>
#include <string.h>
int main() {
char str[100], noSpaceStr[100];
int j = 0;
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
for (int i = 0; i < strlen(str); i++) {
if (str[i] != ' ') {
noSpaceStr[j++] = str[i];
}
}
noSpaceStr[j] = '\0';
printf("String without spaces: %s\n", noSpaceStr);
return 0;
}
Exercise 1: Reverse a String
Write a program that takes a user-input string and outputs the string in reverse order. Use character arrays, and loop through the string to reverse it manually.
Sample Output:
Enter a string: hello
Reversed string: olleh
Exercise 2: Count Vowels and Consonants
Create a program that counts the number of vowels and consonants in a user-provided string. Use strlen to iterate through each character and count vowels (a, e, i, o, u) and consonants.
Sample Output:
Enter a string: programming
Vowels: 3
Consonants: 8
Exercise 3: Substring Finder
Write a program that checks if a substring exists within a given string. Prompt the user for both the main string and the substring, then use strstr to determine if the substring is present.
Sample Output:
Enter a main string: helloworld
Enter a substring: world
Substring found!
Exercise 4: Character Frequency Counter
Write a program that counts the frequency of each character in a given string. Use an array to keep track of the frequency of characters (only letters, ignoring case).
Sample Output:
Enter a string: hello
Character frequency:
h: 1
e: 1
l: 2
o: 1
Exercise 5: String Concatenation without strcat
Manually concatenate two strings without using strcat. Prompt the user for two strings, then use a loop to append each character from the second string to the end of the first string.
Sample Output:
Enter first string: good
Enter second string: morning
Concatenated string: goodmorning
Lab Exercise Questions
Exercise 1: Reverse Array Elements
Write a program that reads a series of integers into an array and then prints them in reverse order. Use a loop to read 10 integers from the user, store them in an array, and print the array elements in reverse order.
Sample Output:
Enter 10 numbers: 1 2 3 4 5 6 7 8 9 10
In reverse order: 10 9 8 7 6 5 4 3 2 1
Exercise 2: Compound Interest Table
Implement a program that calculates compound interest for different rates over a specified number of years. Prompt the user to enter the initial interest rate and the number of years. Calculate the compounded amount for five incremental interest rates.
Sample Output:
Enter interest rate: 5
Enter number of years: 3
Years 5% 6% 7% 8% 9%
1 105.00 106.00 107.00 108.00 109.00
2 110.25 112.36 114.49 116.64 118.81
3 115.76 119.10 122.50 125.97 129.50
Exercise 3: Calculate the Average of Array Elements
Write a program that reads a set of integers into an array and calculates their average. Prompt the user to enter 5 integers. Store them in an array, calculate their average, and print the result.
Sample Output:
Enter 5 numbers: 10 20 30 40 50
Average of entered numbers: 30.00
Lab 1: Copying Arrays with a Loop
Demonstrate how to copy one array into another using a loop.
Create two arrays, source and destination, each of size 5.
Initialize the source array with values [10, 20, 30, 40, 50].
Use a loop to copy the elements from source into destination.
Print the contents of both arrays to verify that the copy was successful.
Sample Output:
Source array: 10 20 30 40 50
Destination array: 10 20 30 40 50
Lab 2: Copying Arrays with memcpy
Demonstrate how to copy an array using the memcpy function.
Create two arrays, source and destination, each of size 5.
Initialize the source array with values [5, 10, 15, 20, 25].
Use memcpy to copy source into destination.
Print both arrays to verify the copy.
Sample Output:
Source array: 5 10 15 20 25
Destination array: 5 10 15 20 25
Lab 3: Initializing a Two-Dimensional Array
Demonstrate how to initialize and print a two-dimensional array.
Create a 2x3 matrix.
Initialize it with the values:
Use nested loops to print the matrix in row-major order.
1 2 3
4 5 6
Sample Output:
Matrix:
1 2 3
4 5 6
Lab 4: Variable-Length Arrays (VLAs)
Demonstrate the use of variable-length arrays in C.
Prompt the user to enter the number of rows and columns for a matrix.
Create a variable-length array with the specified dimensions.
Populate the array with the product of its indices (value = row * column).
Print the matrix.
Sample Output:
Enter the number of rows: 3
Enter the number of columns: 4
Matrix:
0 0 0 0
0 1 2 3
0 2 4 6
Lab 5: Constant Multidimensional Arrays
Demonstrate the use of a constant multidimensional array.
Declare a 2x2 constant array.
Initialize it with the values:
Attempt to modify an element and observe the compiler error.
1 0
0 1
Sample Output:
Matrix:
1 0
0 1
Exercise 1: Calculate the Average of Integers in a Given Range
Write a program to take A integers as input, calculate the average of numbers within a specified range [B, C], and display the result.
Sample Output:
How many numbers should the user input? 5
Please define the interval (B and C): 10 20
Please enter an integer: 12
Please enter an integer: 8
Please enter an integer: 15
Please enter an integer: 25
Please enter an integer: 19
The average is 15.33.
Exercise 2: Swap Corner Elements of a 2D Array
Write a function to swap the corners of a 2D array and calculate the sum of the corner values.
Sample Output:
Original Array:
1 2 3
4 5 6
7 8 9
Modified Array:
9 2 7
4 5 6
3 8 1
Sum of corners: 20
Exercise 3: Increment and Decrement Operators
Demonstrate and observe the behavior of pre-increment and post-increment operators.
Sample Output:
After pre-increment: num1 = 11, num2 = 11
After post-increment: num1 = 12, num2 = 11
After pre-decrement: num1 = 11, num2 = 11
After post-decrement: num1 = 10, num2 = 11
Exercise 4: String Manipulation
Write a function to replace 'a' with 'A' and "to" with "TO" in a string.
Sample Output:
Enter a string: this is a test to transform
Transformed string: this is A test TO trAnsform
Exercise 1: Library Management System
Objective: Create a basic library management system that allows users to add, search, and display book details.
Requirements:
1. Use a structure to store book details:
Title (string), Author (string), ISBN (integer), Copies Available (integer).
2. Provide options in a menu:
Add a book.
Search for a book by ISBN.
Display all books.
3. Use functions to handle each menu option.
4. Use an array to store up to 100 books.
5. Ensure input validation and error handling.
Expected Output:
Library Management System
1. Add a Book
2. Search a Book by ISBN
3. Display All Books
4. Exit
Enter your choice: 1
Enter Title: C Programming
Enter Author: Dennis Ritchie
Enter ISBN: 12345
Enter Copies Available: 10
Book added successfully!
Library Management System
1. Add a Book
2. Search a Book by ISBN
3. Display All Books
4. Exit
Enter your choice: 3
Books in Library:
Title: C Programming, Author: Dennis Ritchie, ISBN: 12345, Copies Available: 10
Exercise 2: Employee Payroll System
Objective: Build an employee payroll system that calculates salaries based on hours worked and hourly rate.
Requirements:
1. Use a structure to store employee details:
Employee ID (integer), Name (string), Hours Worked (float), Hourly Rate (float), Salary (float).
2. Provide a menu:
Add Employee.
Calculate Salary (update salary based on hours worked × hourly rate).
Display Payroll (show details of all employees).
3. Use functions to modularize tasks.
4. Limit the system to handle up to 50 employees.
Expected Output:
Employee Payroll System
1. Add Employee
2. Calculate Salary
3. Display Payroll
4. Exit
Enter your choice: 1
Enter Employee ID: 101
Enter Name: John Doe
Enter Hours Worked: 40
Enter Hourly Rate: 20
Employee added successfully!
Employee Payroll System
1. Add Employee
2. Calculate Salary
3. Display Payroll
4. Exit
Enter your choice: 2
Salaries updated!
Employee Payroll System
1. Add Employee
2. Calculate Salary
3. Display Payroll
4. Exit
Enter your choice: 3
Employee Payroll:
ID: 101, Name: John Doe, Hours Worked: 40, Hourly Rate: 20, Salary: 800.00