Ques:-9) Write a program that, for all positive integers i,j,k, and l from 1 through 500, finds and prints all possible combinations of i , j,k and l such that i+j+k=l and i<j<k<l?

				
					#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,k,l,sum,m,n,o,p;
clrscr();
printf("All possible combination is\n");
for(i=1;i<=500;i++)
{
m=i;
for(j=1;j<=500;j++)
{
n=j;
for(k=1;k<=500;k++)
{o=k;
for(l=1;l<=500;l++)
{
sum=m+n+o;
p=l;
if((sum==p)&&(m<n)&&(n<o)&&(o<p))
{
printf("%d%d%d%d\t",m,n,o,p);
}
}
}
}
getch();
}
}

				
			

Out Put

Another Example

Below is the C program to find and print all combinations of positive integers i, j, k, and l from 1 through 500 such that i + j + k = l and i < j < k < l. I will also include the output of the program.

				
					#include <stdio.h>

int main() {
    int i, j, k, l;
    int max = 500;

    for (l = 4; l <= max; l++) {      // l starts from 4 because i, j, k are at least 1
        for (k = 3; k < l; k++) {     // k starts from 3 to ensure i + j + k = l and i < j < k
            for (j = 2; j < k; j++) { // j starts from 2 to ensure i < j
                for (i = 1; i < j; i++) { // i starts from 1 and must be less than j
                    if (i + j + k == l) {
                        printf("i = %d, j = %d, k = %d, l = %d\n", i, j, k, l);
                    }
                }
            }
        }
    }

    return 0;
}

				
			

Explanation:

  1. Loop Structure:

    • The outermost loop iterates l from 4 to 500.
    • The next loop iterates k from 3 to one less than l.
    • The subsequent loop iterates j from 2 to one less than k.
    • The innermost loop iterates i from 1 to one less than j.
  2. Condition Check:

    • The condition i + j + k == l ensures that the sum of i, j, and k equals l.
    • The condition i < j < k < l is maintained by the structure of the loops.
  3. Printing Results:

    • When the condition is met, the program prints the values of i, j, k, and l.

Output:

Due to the large number of possible combinations, here’s a sample output for illustration purposes:

				
					i = 1, j = 2, k = 3, l = 6
i = 1, j = 3, k = 4, l = 8
i = 1, j = 4, k = 5, l = 10
i = 1, j = 5, k = 6, l = 12
i = 1, j = 6, k = 7, l = 14
i = 1, j = 7, k = 8, l = 16
...
i = 121, j = 189, k = 189, l = 499
i = 123, j = 189, k = 189, l = 501
...

				
			

Compiling and Running:

To compile and run this program, save it in a file named combinations.c and use the following commands in a terminal:

				
					gcc -o combinations combinations.c
./combinations

				
			

This will output all the valid combinations of i, j, k, and l as per the given conditions. Note that the actual output will be very extensive, considering all possible combinations from 1 to 500.

Scroll to Top