Write a C program to find largest / maximum difference between two elements of an array, such that larger element or number appears after the smaller number in the array.
Note: I’m not considering time complexity in this video tutorial intentionally. We’ll have a completely dedicated video teaching about time complexity from basic. My intention in this video is to make the logic as simple and understandable as possible.
Source Code: C Program To Find Largest Difference Between Two Elements of Array
#include<stdio.h>
#define N 6
int main()
{
int num[N], i, big, small;
printf("Enter %d integer numbers\n", N);
for(i = 0; i < N; i++)
scanf("%d", &num[i]);
big = small = num[0];
for(i = 1; i < N; i++)
{
if(num[i] > big)
big = num[i];
if(num[i] < small)
small = num[i];
}
printf("The largest difference is %d, ", (big - small));
printf("and its between %d and %d.\n", big, small);
return 0;
}
Output: Enter 6 integer numbers 7 9 5 6 13 2 The largest difference is 11, and its between 13 and 2.
Here we find biggest element in the array and smallest element in the array. Next we subtract smallest element from biggest element to get the largest different between two array elements.
Find Largest Difference, where Largest Element Appears After Smallest Number in Array
#include<stdio.h>
#define N 6
int main()
{
int num[N], i, big, small, pos = 0;
printf("Enter %d integer numbers\n", N);
for(i = 0; i < N; i++)
scanf("%d", &num[i]);
big = small = num[0];
for(i = 1; i < N; i++)
{
if(num[i] > big)
{
big = num[i];
pos = i;
}
}
for(i = 1; i < pos; i++)
{
if(num[i] < small)
small = num[i];
}
printf("The largest difference is %d, ", (big - small));
printf("and its between %d and %d.\n", big, small);
return 0;
}
Output: Enter 6 integer numbers 7 9 5 6 13 2 The largest difference is 8, and its between 13 and 5.
Logic To Find Largest Difference b/w Two Elements of Array, where biggest number appears after the smallest number
As per the problem statement, the smallest number in the array must be chosen from index 0 to the position where the biggest number of the array is present.
For Example: Assume that we’ve an array {1, 2, 5, 3, 0}. Here biggest element in the array is 5 and its position in the array is 2. Now we need to select smallest number in the array between the index range 0 to 2. So the smallest number will be 1.
Step 1: First we iterate through the array using a for loop and find the biggest element in the array and we also determine the index position at which this biggest number is present.
Step 2: We write another for loop and iterate from index 1 to the position where the biggest number is present. And inside for loop we select the smallest element between the range.
Step 3: Now we subtract the smallest element from step 2 with the biggest element from step 1, and we get the largest difference between two elements of an array, where biggest number appears after the smaller number in the array.
Note: 1. We initialize variables big and small to the first element of the array, because we need to have some value to compare it with other elements of the array. 2. In both the for loops we initialize i to 1, as both variables big and small is assigned with value present at index 0. So there is no point in comparing with itself, so we start the comparison from index 1. That’s the reason we initialize i to 1 in both the for loops.
Enter 5 unique integer numbers 5 2 6 4 3 First Big: 6 Second Big: 5
Important Note: This code only works for inputs which has unique integer numbers. If there are duplicate integer numbers which is biggest in the array, then it’ll show the same number for both first and second biggest element. We can fix it, but it’s out of scope of this problem statement. Just know the limitation of this code.
Ex: a[5] = {2, 4, 5, 3, 5}; In this case, both first big and second big will have value 5.
Video Tutorial: C Program To Find First and Second Biggest Element In An Array
In both the cases the logic is same. If a[0] is greater than a[1], then value present at a[0] will be assigned to fbig, and a[1] will be assigned to sbig. If a[0] is not greater than a[1], then a[1] will be assigned to fbig and a[0] will be assigned to sbig.
for loop Since both a[0] and a[1] are already sorted out, the comparison must start from a[2]. So we initialize the loop counter variable i to 2 and loop through until i < N and for each iteration we increment the value of i by 1.
Inside for loop If value of fbig is less than the fetched element of the array, then we transfer the value of fbig to sbig and assign the new array element value to fbig.
Else if, the fetched element of the array is less than fbig but greater than sbig, then we assign the value of the array element to sbig.
Lets write a C program to find biggest or the largest element in an array, without sorting the elements. And also print the position at which the biggest number is present in the array.
Source Code: C Program To Find Biggest Element of An Array
Method 1
#include<stdio.h>
#define N 5
int main()
{
int a[N], i, big, pos;
printf("Enter %d integer numbers\n", N);
for(i = 0; i < N; i++)
{
scanf("%d", &a[i]);
if(i == 0 || big < a[i])
{
big = a[i];
pos = i + 1;
}
}
printf("\nBiggest of %d numbers is %d, at position %d.\n", N, big, pos);
return 0;
}
Output 1: Enter 5 integer numbers 1 3 2 5 8
Biggest of 5 numbers is 8, at position 5.
Output 2: Enter 5 integer numbers 10 2 5 9 3
Biggest of 5 numbers is 10, at position 1.
Logic To Find Biggest Element In An Array
We ask the user to input N integer numbers. N being a Macro. In above source code N is 5. So user enters 5 integer numbers. While the user inputs numbers we check if it’s the first number input by the user. If its the first number, then we assign that first number entered by the user to variable big and assign 1 to variable pos, indicating that its the first element in the array.
Next, for each consecutive iteration of the for loop we check if the new value entered by the user is greater than the value present in variable big. If it’s true, then we assign the new value entered by the user to variable big and also update the value of pos accordingly.
Once i < N condition is false, control exits for loop and we print the value present inside variable big and pos which will have biggest of N numbers or the biggest element of the array and position of that element in the array.
Explanation With Example
If int a[5] = {2, 4, 3, 4, 5};
for(i = 0; i < N; i++)
{
scanf("%d", &a[i]);
if(i == 0 || big < a[i])
{
big = a[i];
pos = i + 1;
}
}
index
a[index]
big
pos = index + 1
0
a[0] = 2
2
1
1
a[1] = 4
4
2
2
a[2] = 3
3
a[3] = 4
4
a[4] = 5
5
5
5
a[5] = {2, 4, 3, 4, 5} big = 5; pos = 5;
Source Code: C Program To Find Biggest Element of An Array
Method 2
#include<stdio.h>
#define N 5
int main()
{
int a[N], i, big, pos;
printf("Enter %d integer numbers\n", N);
for(i = 0; i < N; i++)
{
scanf("%d", &a[i]);
}
big = a[0];
pos = 1;
for(i = 1; i < N; i++)
{
if(big < a[i])
{
big = a[i];
pos = i + 1;
}
}
printf("\nBiggest of %d numbers is %d, at position %d.\n", N, big, pos);
return 0;
}
Output 1: Enter 5 integer numbers 1 5 6 3 0
Biggest of 5 numbers is 6, at position 3.
Output 2: Enter 5 integer numbers 2 4 3 4 5
Biggest of 5 numbers is 5, at position 5
Method 2: LOGIC
Here we accept N integer numbers from the user. Next we assign the first element of the array to big and 1 to pos. Now we use another for loop to loop through the array. Inside for loop we check if the value present inside variable big is less than the value present at a[i]. If it’s true, then we assign the value of a[i] to big and value of (i+1) to variable pos.
At the end of for loop, variable big and pos will have biggest element of the array and the position at which this number is present in the array.
Note: Since we assign the value of first element of the array(which is present at location a[0]) to variable big, while comparing with other elements of the array, we start comparing from a[1] till a[N-1]. That’s the reason we’ve assigned initial value of i to 1 in the second for loop.
Since a[0] is assigned to variable big, there is no point in comparing big with a[0]. So we start comparison from a[1].
Problem State: Write down macro definitions for the following: 1. To test whether a character is a small case letter or not. 2. To test whether a character is an upper case letter or not. 3. To test whether a character is an alphabet or not. Make use of the macros you defined in 1 and 2 above. 4. To obtain the bigger of two numbers.
1. We need to write 4 Macro definitions. 2. We must write macros to find upper and lower case, and then make use of these two macros to find if user entered character is alphabet or not. 3. We can find biggest of 2 numbers by using Ternary / conditional operator in macro expansion.
Video Tutorial: Using Macros Check For Uppercase / Lowercase and Alphabet or Not and Biggest of 2 Numbers: C Program
Source Code: Using Macros Check For Uppercase / Lowercase and Alphabet or Not and Biggest of 2 Numbers: C Program
#include<stdio.h>
#define isUPPER(ch) ( ch >= 'A' && ch <= 'Z' )
#define isLOWER(ch) ( ch >= 'a' && ch <= 'z' )
#define isALPHABET(ch) ( isUPPER(ch) || isLOWER(ch) )
#define BIGGEST(a, b) ( ( a > b ) ? \
printf("%d is the biggest\n", a) : \
printf("%d is the biggest\n", b) )
int main()
{
int a, b, repeat;
char ch, choice;
do
{
printf("1. Check if entered character is upper or lower case\n");
printf("2. Check if entered character is alphabet or not\n");
printf("3. Find biggest of 2 numbers\n");
printf("\nEnter your choice\n");
scanf(" %c", &choice);
switch(choice)
{
case '1': printf("\nEnter a character\n");
scanf(" %c", &ch);
if( isUPPER(ch) )
{
printf("Entered character is upper case letter\n");
}
else if( isLOWER(ch) )
{
printf("Entered character is lower case letter\n");
}
else
{
printf("Please enter a valid alphabet\n");
}
break;
case '2': printf("\nEnter a character\n");
scanf(" %c", &ch);
if( isALPHABET(ch) )
{
printf("Entered character is an alphabet\n");
}
else
{
printf("Entered character is not an alphabet\n");
}
break;
case '3': printf("\nEnter 2 numbers\n");
scanf("%d%d", &a, &b);
BIGGEST(a, b);
break;
default: printf("\nPlease enter valid choice\n");
}
printf("\n\nDo you want to continue? Ans: 0 or 1\n");
scanf("%d", &repeat);
printf("\n");
fflush(stdin);
}while(repeat);
return 0;
}
Output: 1. Check if entered character is upper or lower case 2. Check if entered character is alphabet or not 3. Find biggest of 2 numbers
Enter your choice 1
Enter a character S Entered character is upper case letter
Do you want to continue? Ans: 0 or 1 1
1. Check if entered character is upper or lower case 2. Check if entered character is alphabet or not 3. Find biggest of 2 numbers
Enter your choice 1
Enter a character s Entered character is lower case letter
Do you want to continue? Ans: 0 or 1 1
1. Check if entered character is upper or lower case 2. Check if entered character is alphabet or not 3. Find biggest of 2 numbers
Enter your choice 1
Enter a character $ Please enter a valid alphabet
Do you want to continue? Ans: 0 or 1 1
1. Check if entered character is upper or lower case 2. Check if entered character is alphabet or not 3. Find biggest of 2 numbers
Enter your choice 2
Enter a character A Entered character is an alphabet
Do you want to continue? Ans: 0 or 1 1
1. Check if entered character is upper or lower case 2. Check if entered character is alphabet or not 3. Find biggest of 2 numbers
Enter your choice 2
Enter a character & Entered character is not an alphabet
Do you want to continue? Ans: 0 or 1 1
1. Check if entered character is upper or lower case 2. Check if entered character is alphabet or not 3. Find biggest of 2 numbers
Enter your choice 3
Enter 2 numbers 14 50 50 is the biggest
Do you want to continue? Ans: 0 or 1 0
Here we are using do-while loop to repeatedly show the user choices: If user enters 1, the choices are shown once again. If the user enters 0, then control exits the do-while loop.
Choice 1: Upper or Lower Case Alphabet
All the characters have ASCII value associated with it in C programming. So internally it checks the ASCII value of user entered character against the ASCII values of “A” to “Z”.
ASCII value range of upper case alphabets: ASCII value of A is 65. ASCII value of B is 66. ASCII value of C is 67.
and so on till Z ..
ASCII value of Z is 90.
So all the ASCII values between 65 and 90 (including 65 and 90) are Capital letter alphabets.
Similarly, below we’ve listed the ASCII values of lower case alphabets.
ASCII value range of lower case alphabets: ASCII value of a is 97. ASCII value of b is 98. ASCII value of c is 99.
and so on till z ..
ASCII value of z is 122.
So all the ASCII values between 97 and 122 (including 97 and 122) are Lower case letter alphabets.
According to our problem statement we need to use the macros we defined for “Choice 1” to evaluate if the user entered character is alphabet or not. So if the user entered character is upper or lower case latter than its alphabet or else its not an alphabet.
When you input some data via console window and hit enter key, the enter key or the new line character gets stored inside input buffer. If you’re accepting a single character from keyboard via scanf() function, often times it gets confused with the input buffer and thinks that the user has pressed the enter key as the input character. We can avoid it in 3 ways:
1. Use double scanf() function, as illustrated in above video tutorial. 2. Use a space before %c inside scanf() method. 3. Use fflush(stdin) before every scanf() method which accepts a single character value.
Note: Since we might start to input information from the keyboard repeatedly inside do-while block, scanf() method keeps checking the input buffer. And often times it gets confused with the input buffer and thinks that the user has pressed the enter key. To avoid that we flush out the previous buffer present in input device(ex: keyboard) using function fflush(). fflush takes stdin as argument, so that it can clear the buffer of standard input device. fflush(stdin);
#include<stdio.h>
#define isUPPER(ch) ( ch >= 'A' && ch <= 'Z' )
#define isLOWER(ch) ( ch >= 'a' && ch <= 'z' )
#define isALPHABET(ch) ( isUPPER(ch) || isLOWER(ch) )
#define BIGGEST(a, b) ( ( a > b ) ? \
printf("%d is the biggest\n", a) : \
printf("%d is the biggest\n", b) )
int main()
{
int a, b, repeat;
char ch, choice;
do
{
printf("1. Check if entered character is upper or lower case\n");
printf("2. Check if entered character is alphabet or not\n");
printf("3. Find biggest of 2 numbers\n");
printf("\nEnter your choice\n");
scanf("%c", &choice);
switch(choice)
{
case '1': printf("\nEnter a character\n");
fflush(stdin);
scanf("%c", &ch);
if( isUPPER(ch) )
{
printf("Entered character is upper case letter\n");
}
else if( isLOWER(ch) )
{
printf("Entered character is lower case letter\n");
}
else
{
printf("Please enter a valid alphabet\n");
}
break;
case '2': printf("\nEnter a character\n");
fflush(stdin);
scanf("%c", &ch);
if( isALPHABET(ch) )
{
printf("Entered character is an alphabet\n");
}
else
{
printf("Entered character is not an alphabet\n");
}
break;
case '3': printf("\nEnter 2 numbers\n");
scanf("%d%d", &a, &b);
BIGGEST(a, b);
break;
default: printf("\nPlease enter valid choice\n");
}
printf("\n\nDo you want to continue? Ans: 0 or 1\n");
scanf("%d", &repeat);
printf("\n");
fflush(stdin);
}while(repeat);
return 0;
}
In above source code we’re making use of fflush(stdin) before every scanf() method which accepts single character. fflush(stdin) flushes out the previous buffer present in input device(ex: Keyboard).
Note: We can continue writing macro expansion in next line by making use of macro continuation operator(\). You can see that we’ve broken the line and written the code in next line inside macro expansion to find biggest of 2 numbers.
Source Code: C Program To Find Biggest of Three Numbers using Function
#include<stdio.h>
int biggest(int, int, int); // function prototype
int main()
{
int a, b, c;
printf("Enter 3 integer numbers\n");
scanf("%d%d%d", &a, &b, &c);
//function call biggest(a, b, c)
printf("Biggest of %d, %d and %d is %d\n", a, b, c, biggest(a, b, c));
return 0;
}
// function definition
int biggest(int x, int y, int z)
{
if(x > y && x > z)
{
return x;
}
else
{
if(y > z)
return y;
else
return z;
}
}
Output Enter 3 integer numbers 50 40 60 Biggest of 50, 40 and 60 is 60
Source Code: C Program To Find Biggest of Three Numbers using Function, Using Ternary Operator
#include<stdio.h>
int biggest(int, int, int); // function prototype
int main()
{
int a, b, c;
printf("Enter 3 integer numbers\n");
scanf("%d%d%d", &a, &b, &c);
//function call biggest(a, b, c)
printf("Biggest of %d, %d and %d is %d\n", a, b, c, biggest(a, b, c));
return 0;
}
// function definition
int biggest(int x, int y, int z)
{
return( (x>y && x>z)?x:(y>z)?y:z );
}
Logic To Find Biggest of 3 Numbers using Function
We ask the user to enter 3 integer numbers. We pass those 3 integer numbers to user defined function biggest. Inside function biggest we use ternary operator to determine the biggest of those 3 numbers. Function biggest returns the biggest of the 3 numbers back to the calling method/function – in above progam its main() method.
Note: Function biggest returns integer type data. And it takes 3 arguments of type integer. We’re calling function biggest from inside printf() function.