# Thread: "expected primary-expression before 'else'"

1. ## "expected primary-expression before 'else'"

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

I am tyring to write a simple program to display distance traveled. here are my instructions:

Write a program that asks the user for the speed of a vehicle (In miles per hour) and how many hours it has traveled. It should then use a loop to display the distance the vehicle has traveled for each hour of that time period. Her is an example of the output

What is the speed of the vehicle in mph? 40
How many hours has it traveled? 3

Hour Distance Traveled
--------------------------------------------------
1 40
2 80
3 120

Input validation:
Do not accept any negative number for speed and do not accept any value
less than one for time traveled.

The output should be formatted and aligned according to the above.

Here is my code so far:
Code:
```CPP / C++ / C Code:
#include <cstdio>
#include <iostream>
#include <cmath>
using namespace std;

int main ()
{
int speed, distance, time, a, b;
a=1;
b=a*speed;

cout << "Distance Program";
cout << "\n\n\nWhat is the speed of the vehicle in mph?\n";
cin >> speed;
cout << "\nHow many hours has it traveled?\n";
cin >> time;

if (time >1 && speed >0)

cout << "\n\nHour                  Distance Traveled";
cout << "\n--------------------------------------\n";

while (a<= time)
{
a++;
cout << "\n";
cout << a;
printf("                      ");
cout << b;
cout << "\n";

}
return 0;

else

{
cout << "\n\nYou have entered invalid data\n\n";
system("pause");
}
}```
I keep getting the "expected primary-expression before 'else'" error and the "expected ";" before 'else'" error. Am I missing something very simple? Imay not know much about programming, but I thought this was straight-forward

2. Include braces for the if statement. You're missing them.

And incidentally, if you use system(), include cstdlib.

3. first, you should use either C or C++ code. the majority youve used here looks like C++, so remove your 'printf' and use cout like you have been doing. also, the only header you need for the code to run is iostream, so you can remove the other two unless you explicitly require them.

it looks like your missing a pair of braces in your if block. your else block is fine, but you need them around your first if block too.

also, at the start of main, why do you do 'b = a*speed'? speed isnt even initialized so you dont know what value speed will have anyways. and whatever its value is, it wont change if you multiply it by 'a' which is 1 in this case.

also, if you set 'a' to 1, then in your while loop you check if a<= time. you know time > 1 because of the if statement. the only thing you do to a is increase it, so it starts at 1, then 2, etc. i think you need to rethink that.

hope it helps.

4. Thanks for the quick replies. I always forget something simple like braces.

Popular pages Recent additions