Introduction
In this lab, we will learn how to find the largest and smallest numbers among two input numbers using global declaration in C programming. Unlike local variables, global variables can be accessed and modified by any function within the program. We will use global variables to store the input numbers and solve the problem.
Note: You need to create the file
~/project/main.cyourself to practice coding and learn how to compile and run it using gcc.
cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main
Declare global variables
First, we need to declare two global variables a and b outside of the main function. We will store the input numbers in these variables.
#include <stdio.h>
int a, b;
Take input values from the user
In this step, we will take two integer values from the user and store them in the a and b variables using the scanf() function.
int main()
{
printf("Enter two numbers to find the largest and smallest numbers: ");
scanf("%d %d", &a, &b);
}
Find the largest and smallest numbers
To find the largest and smallest numbers, we will use an if...else statement to compare the values of a and b. If a is greater than b, then a is the largest and b is the smallest, and vice versa. If a and b are equal, then both are the same.
if(a > b)
{
printf("The largest number is %d\n", a);
printf("The smallest number is %d\n", b);
}
else if(a < b)
{
printf("The largest number is %d\n", b);
printf("The smallest number is %d\n", a);
}
else
{
printf("Both numbers are equal\n");
}
Complete the program
Finally, we will add some print statements to display the output messages and return 0 to indicate that the program executed successfully.
#include <stdio.h>
int a, b;
int main()
{
printf("Enter two numbers to find the largest and smallest numbers: ");
scanf("%d %d", &a, &b);
if(a > b)
{
printf("The largest number is %d\n", a);
printf("The smallest number is %d\n", b);
}
else if(a < b)
{
printf("The largest number is %d\n", b);
printf("The smallest number is %d\n", a);
}
else
{
printf("Both numbers are equal\n");
}
return 0;
}
Summary
In this lab, we learned how to find the largest and smallest numbers among two input numbers using global declaration in C programming. We declared two global variables a and b to store the input numbers and compared their values to determine the largest and smallest numbers. By practicing with this program, students can learn how to declare global variables and use basic conditional statements in C programming.



