0

The problems objective is to write a program that takes a number of data sets the user would like to enter and then within the data sets it counts how many miles you traveled. For example for the first sample input 20 mph for the first 2 hours, 30 for 2nd - 6th hour and 10 for the seventh hour. The input sequence is the n number of data sets and the the s (speed/mph) and t(time). -1 ends the sequence

Sample Input

3
20 2
30 6
10 7
2
60 1
30 5
4
15 1
25 2
30 3
10 5
-1

Sample output

170 miles
180 miles
90 miles
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    int n, s, t, timeDiff, newTime, sum, arrSum; //variables
    int arr[100]; //array
    int count = 0; //counter, which i haven't used yet but have been in the habit of doing

    while (n != -1){
        
        scanf("%d", &n);    //Number of data sets to be entered
    
        for(int i=0; i<n ;i++){
            
            timeDiff = t;     //saves last time value
            scanf("%d %d", &s, &t);
            newTime = t - timeDiff;  //subtracts last time value from the new
            
            if (timeDiff == 0){
                sum = s * t;  
                arr[i] = sum;  
            }
            else{
                sum = s * newTime;
                arr[i] = sum;}
            }
            for (int i = 0; i < n; i++){
            arrSum = arrSum + arr[i];
        }
        printf("You went %d miles \n", arrSum);
      
        sum = 0;
        timeDiff = 0;
        arrSum = 0;
        newTime = 0;
      
        for (int i = 0; i < n; i++){
            arr[i] = 0;
        }
        count++; 
    }

    return 0;
}

When I initially spotted the probelm I though it was because my array was filled so I had to empty it hence the for loop at the end (tbh im not even sure that's entirely correct). I'm a relatively new programmer to c and have been trying to adjust, but it's proved difficult to say the least.

6
  • 5
    while (n != -1) -- you never initialized n before this.
    – Barmar
    Commented Jun 26 at 19:44
  • 3
    You have arrSum = arrSum + arr[i]; but the local variable int arrsum was not initialised. Commented Jun 26 at 19:44
  • 3
    Hint: initialise variables just before you use them, not after. Those 'zeroing' lines just near the end of main() are in the wrong place. Commented Jun 26 at 19:47
  • 1
    You need to break out of the loop immediately if -1 is entered as the number of datasets. Your code will continue with the rest of the loop body, even though there's no more input to read.
    – Barmar
    Commented Jun 26 at 19:47
  • 2
    Your compiler should warn about using uninitialized variables. If not, turn warnings up.
    – Chris
    Commented Jun 26 at 20:14

1 Answer 1

1

In short, as others have pointed out, you have a ton of uninitialized and/or misused variables.

It looks like you're giving it a try, so I'm less concerned about doing your homework for you. That said, note how I 1) ensure variables have a usable value before using them; and 2) bail out if I don't get suitable input via scanf.

A couple of things to note about your code:

  1. Keep variables at the innermost scope that you can. This not only helps the compiler to optimize the machine code, it also helps the compiler flag errors and warnings.
  2. Depending on C version, you may need to declare variables at wider scopes than where they're used (not actually very relevant unless you're using a very old compiler or taking a course in K&R C). Still, don't initialize them before you need to, but DO initialize them IF you need to.
  3. Use descriptive variable names! n, s, and t are too easy to get confused. Trust me, the time you spend giving them intuitive names will be saved many times over when you're trying to fix your code.
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int totalMiles = 0;
    int totalHours = 0;
    int count = 0;
    int nrecs;
    while (scanf("%d", &nrecs) == 1)
    {
        int hours, miles;
        if (nrecs < 0)
            break;
        ++count;
        hours = miles = 0;
        for (int index = 0; index < nrecs; ++index)
        {
            int speed, duration;
            if (scanf("%d %d", &speed, &duration) != 2)
            {
                // bad input, report an error and exit
                fprintf(stderr, "invalid input\n");
                return EXIT_FAILURE;
            }
            miles += (speed * duration);
            hours += duration;
        }
        totalMiles += miles;
        totalHours += hours;
    }
    printf("You went %d miles in %d hours\n", totalMiles, totalHours);
    printf("%d blocks processed\n", count);
    
    return EXIT_SUCCESS;
}
9
  • What are you referring to in point 2? Do you mean declaring variables in the for() header?
    – Barmar
    Commented Jun 26 at 22:27
  • No, though that could be the case if you use a really ancient compiler ;) I was referring instead to the forward declarations of hours and miles, whose declarations could wait until initialization with any relatively modern compiler.
    – TedB
    Commented Jun 26 at 22:29
  • Why not just int hours = 0, miles = 0;? There's no real need to delay the initializations until after the if.
    – Barmar
    Commented Jun 26 at 22:32
  • If (nrecs < 0) is true and the compiler isn't smart enough to delay the initialization, you've executed instructions to store values that will never be used. In the overall scheme of things, it's inconsequential, but it's still wasted machine instructions and I try to avoid those.
    – TedB
    Commented Jun 26 at 22:35
  • Premature optimization is the root of all evil.
    – Barmar
    Commented Jun 26 at 22:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.