Thread: Sum of steps

  1. #1
    Registered User Melon's Avatar
    Join Date
    Jan 2003
    Posts
    13

    Sum of steps

    I want to build a program so that it will sum integers from any "start" to "finish" spaced by a "step". Negative step values are allowed. For invalid combinations, i.e. “step” = 0, start less than finish with a negative step, or start bigger than finish with a positive step; I want the program to terminate and print an error message.
    Code:
    /* Sum of Spaced Integers */
    /* Ian Richardson */
    /* 02/14/2003 */
    #include <stdio.h>
    
    int main (void)		
    {
    	/* intialization phase */
    int count, start, step, end, sum = 0;
    	printf("What is your starting number?\n");
    	scanf("%d", &start);
    	
    	printf("What is your ending number?\n");
    	scanf("%d", &end);
    	
    	printf("What interval step would you like to use?\n");
    	scanf("%d", &step);
    	
    	if ( step > 0 )
    	else if ( step < 0 )
    	else if ( start < end && step > 0 )
    	else if ( start > end && step < 0 ) {
    	
    	for ( count = start; count <= end; count += step ) {
    	sum += count;
    	}
    	printf("The start number is: %d\n", start );
    	printf("The end number is: %d\n", end );
    	printf("The sum of the spaced integers is: %d\n", sum );
    	}
    	else
    	printf("Error: Invalid step entered.\n");
    	
    	return 0;
    }
    Ten out of ten people die, so don't take life so seriously.

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    if step < 0 error
    if start >= end error

    Otherwise, just process as normal. Done in a single line:
    Code:
    if( step < 0 || start >= end )
    {
        error
    }
    else
    {
        do valid steps here
    }
    You basicly had the logic worked out already, you just didn't make it do anything.

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Minor Problem
    By stewie1986 in forum C Programming
    Replies: 6
    Last Post: 11-30-2007, 08:40 AM
  2. a sum equal to or in excess of 100
    By lyoncourt in forum C Programming
    Replies: 6
    Last Post: 10-07-2007, 05:43 PM
  3. Logical errors with seach function
    By Taka in forum C Programming
    Replies: 4
    Last Post: 09-18-2006, 05:20 AM
  4. Folding@Home Cboard team?
    By jverkoey in forum A Brief History of Cprogramming.com
    Replies: 398
    Last Post: 10-11-2005, 08:44 AM
  5. string to int conversion not using atoi()
    By linucksrox in forum C Programming
    Replies: 2
    Last Post: 05-19-2004, 12:17 AM