SeqSum: Sum of Consecutive Ints Equal to n

  • Thread starter Thread starter Dr.Brain
  • Start date Start date
  • Tags Tags
    Sum
Click For Summary
SUMMARY

The discussion revolves around the implementation of a C program named seqsum, designed to find sequences of consecutive integers that sum to a given integer n. The initial code provided by the user compiles without errors but fails to produce output upon execution. Key issues identified include the incorrect use of the %f format specifier in printf for integer values and the suggestion to verify the return value of scanf to ensure valid input. The corrected approach emphasizes proper data types and input validation.

PREREQUISITES
  • Proficiency in C programming language
  • Understanding of loops and conditional statements
  • Familiarity with input/output functions in C, specifically scanf and printf
  • Knowledge of integer data types and format specifiers
NEXT STEPS
  • Review C programming documentation on format specifiers in printf
  • Learn about input validation techniques in C, focusing on scanf
  • Explore algorithms for finding consecutive integer sequences
  • Implement error handling in C programs to manage user input effectively
USEFUL FOR

C programmers, software developers, and computer science students interested in algorithm design and debugging techniques in C.

Dr.Brain
Messages
539
Reaction score
2
Write a program called seqsum (source code: seqsum.c) that reads an integer n from the keyboard, and that prints all sequences of consecutive integers whose sum is equal to n. For example, if the input was 30, the program should print out
4,5,6,7,8
6,7,8,9
9,10,11

--------------------------------------------------------

This is the code i wrote...and it gives no errors...but after running it when i input the number 'n' and press enter..it does nothing... :(

main()
{
int i,j,k,m,n;
printf("Input number : \n");
scanf("%d" , &n);
for(i=1;i<=(n/2);i++)
{ k=0;
for(j=i;j<=(n/2+1);j++)
{ k+=j;
if(k==n)
{ for(m=i;m<=j;m++)
printf("%f \t ",m); }
printf("\n");
}
}
}
 
Technology news on Phys.org
The code tag is your friend...
Code:
main() {
   int i,j,k,m,n;
   printf("Input number : \n");
   scanf("%d" , &n);
   for(i=1;i<=(n/2);i++) {
      k=0;
      for(j=i;j<=(n/2+1);j++) {
         k+=j;
         if(k==n) {  
            for(m=i;m<=j;m++)
               printf("%f \t ",m);
         }
         printf("\n");
      }
   }
}

Just for fun, you might want to check whether scanf is returning 0.
Why are you using %f in printf when m is an integer?
 

Similar threads

  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 25 ·
Replies
25
Views
3K
Replies
7
Views
2K
Replies
47
Views
6K
  • · Replies 2 ·
Replies
2
Views
3K
Replies
14
Views
4K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 17 ·
Replies
17
Views
3K