201k views
3 votes
Write a program that reads in a positive integer N and prints out all combinations of 3 numbers that add up to N. by (C) language.

User Tulleb
by
5.5k points

1 Answer

2 votes

Answer:

// here is code in C.

#include <stdio.h>

void main()

{

//declare variables

int N,a,b,c;

printf("Enter a value for N: " );

// read the value from user

scanf("%d",&N);

// validate the input

while(N<=0)

{

// if the input is not positive

printf("wrong input!!");

printf("\\Please enter a positive number: ");

scanf("%d",&N);

}

printf("\\All the combinations of 3 numbers that give sum equal to %d:",N);

// find all the combinations that sum equal to N

for( a=1;a< N-1;a++)

{

for(b= 1;b< N-1; b++)

{

for(c=1; c< N-1;c++)

{

if(a+b+c==N)

{

// print the output

printf("\\%d+%d+%d=%d",a,b,c,N);

}

}

}

}

}

Step-by-step explanation:

Declare variables a,b,c to find the all combinations and N to store the input number from user.Read the input from user. If user enter a negative number Then it will again ask user to enter a positive number.Then it will find all combinations of three numbers that will give sum equal to N with the help of three for loops.

Output:

Enter a value for N: -4

wrong input!!

Please enter a positive number: 6

All the combinations of 3 numbers that give sum equal to 6:

1+1+4=6

1+2+3=6

1+3+2=6

1+4+1=6

2+1+3=6

2+2+2=6

2+3+1=6

3+1+2=6

3+2+1=6

4+1+1=6

User Abhinandan Khilari
by
6.3k points