For starters, I don't see any #includes. You need to include "stdlib.h" for "abs".
Secondly, I don't think it's the "abs" that is the problem, but the logic. It would be more clear if the formatting were more consistent. I also removed the "system" calls as they aren't necessary.
Code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
//initialization statements
int Num1 = 0;
char dot = '.';
//Main menu options of program
printf("Choose a loop type to demonstrate\n");
printf(" 1 While loop\n");
printf(" 2 do-while loop\n");
printf(" 3 for loop\n");
printf(" 4 quit the program\n\n");
printf("Enter your choice: ");
//switch statment and data validation in do while statement
do
{
if(!(scanf("%d", &Num1)))
{
printf("\nPlease enter a valid menu choice");
return -1;
}
else if(Num1 <= 0 || Num1 >= 5)
{
printf("This is not a valid menu option");
return -2;
}
switch(Num1)
{
if(!(scanf("%d", &Num1)));
{
printf("\n Please enter a valid menu choice");
}
case 1:
printf("\nHow many dots should i print? ");
Num1 = abs(Num1);
scanf("%d",&Num1);
while(Num1 > 0)
{
printf("%c", dot);
--Num1;
}
printf("\n");
//system("pause");
//system("cls");
break;
case 2:
printf("\nHow many dots should i print? ");
scanf("\n%d", &Num1);
do
{
printf("%c", dot);
--Num1;
}
while(Num1 > 0);
printf("\n");
break;
case 3:
printf("\nHow many dots should i print? ");
scanf("\n%d", &Num1);
for( ; Num1 > 0; --Num1);
{
printf("%c", dot);
}
break;
case 4:
printf("\nThanks for playing! Bye!");
break;
default:
printf("THIS SHOULD NEVER HAPPEN");
//system("pause");
}
} while(Num1!= 4);
return 0;
}
Overall, not a bad attempt. But some things worth mentioning:
- On line 21, you read a menu option into "Num1" and exit if it's invalid.
- On line 26, you validate the input and exit if it's invalid.
Is this what you want to do, or do you want it to prompt the user again?
- After you enter the "switch" block, you scan in a value again (line 34). I'm not sure what kind of behavior that causes, but I know it's not necessary in your code. Go right to case 1 (you've already received and validated the menu choice, after all).
- In case 1, you prompt for input, take the absolute value, THEN read the input. This is backwards.
-
Furthermore, you're storing the read value into "Num1"! You should have separate variables for the menu selection input and the number of dots input. You need the value of "Num1" at the end of the loop, after all.
I didn't really check out the other cases - use the last two bits of advice for those cases, if necessary.
And if you're prompting for menu input each iteration of the loop, you might as well put the menu information in the loop.