while looping in c language iteration - c

I don't know where is my mistake, please I need your help. When I enter a wrong data in my username and password and it will ask if YES or NO to try again. If I type Y as a YES I can't type in username anymore.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int main() {
printf ("\n\t\t Welcome To Your Payroll Account!");
printf ("\n\t\t Please Enter Your Username & Password To Proceed.");
printf ("\n\t ********************************************************* \n \n \n");
char password [10], username [10], ch;
char name [10] = "username";
char pass[10] = "password";
char month, ename, address;
float regpay,regov,RD,RDOT,meal;
float SSS,PH,PI,Union,other,SSSsal,Loan,Hloan,ULoan,ELoan,TD;
float TE,Netpay;
int n,day,year,i;
char input;
char again = 'Y';
while (again == 'Y' || again =='y') {
printf("Username: ");
gets (username);
printf("Password: ");
for (i = 0; i<8; i++){
ch = getch();
password[i] = ch;
printf ("*");
}
password[i] = 0;
printf("\n Your password is: ");
for (i =0; i<8; i++) {
printf("%c", password[i]);
}
if(strcmp(pass,password) == 0 && strcmp(name,username) == 0) {
printf("\n \n You are logged in! \n");
printf("Enter # to proceed \n");
scanf("%c", &input);
} else {
printf("\n \n Incorrect username or password");
printf("\n\n Do you want to try again? YES(Y) / NO(N) \n");
printf("Continue? ");
scanf("%c", &again);
again;
if (again == 'N' || again == 'n') {
system ("pause");
return 0;
} else {
again;
}
}
}
system ("pause");
return 0;
}

printf("Continue? ");
scanf("%c", &again);
again;
if (again == 'N' || again == 'n') {
system ("pause");
return 0;
} else {
again;
}
Here while taking char input you are using scanf()
so will give character input plus enter.
again will get the input character, but enter will remains in buffer.
When while loop iterates, gets which is waiting for username input will get enter character automatically from the buffer, so the username input will be skipped.
solution is to add getch() after
scanf("%c", &again);
Hope this will hep you.

Related

scanf() not detecting whitespace as user input

May I need help in sorting this out? Basically, I'm tasked to play around with ctype header files. I get input from the user and then I give the output depending on the input provided.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(void)
{
char savedPassword[] = "123456";
char username[100], password[100], charInput, decision;
printf("Username: ");
fgets(username, sizeof(username)/sizeof(username[0]), stdin);
printf("Password: ");
scanf(" %s", &password);
if (strcmp(savedPassword, password) == 0)
{
printf("Welcome, %s\n", username);
do
{
printf("Enter any character: ");
scanf(" %c", &charInput);
if(isalpha(charInput))
{
if(isupper(charInput))
{
printf("%c is a capital letter.\n", charInput);
} else {
printf("%c is a small letter.\n", charInput);
}
} else if (isdigit(charInput))
{
printf("%c is a digit.\n", charInput);
} else if (ispunct(charInput))
{
printf("%c is a punctuation.\n", charInput);
} else if (isspace(charInput))
{
printf("%c is a space.\n", charInput);
}
printf("Do you want to exit (Y/N)? ");
scanf(" %c", &decision);
if (toupper(decision) != 'Y' && toupper(decision) != 'N')
{
printf("Please re-enter the correct response.\n");
printf("Do you want to exit (Y/N)? ");
scanf(" %c", &decision);
}
}while(toupper(decision) != 'Y');
printf("Thank you for using the app!");
} else {
printf("Wrong password! Try again!");
}
return 0;
}
I couldn't make isspace() work because it seems like scanf() doesn't detect the whitespace anymore as I have used one before the placeholder.
Thank you!

Making a school management system and getting errors

I am new to programming and learning the C language and was practising structures and was trying to make basic school management system by using structures, but I am getting
too many errors (by using pointers in structures). So, can you please tell me what are the errors and how can I avoid these types of mistakes. Because, according to my understanding this should have been working.
Here is my code:
#include <stdio.h>
struct student {
int rollno;
char name[20];
float marks;
};
int main() {
again:;
while (1 == 1) {
struct student array[60];
char input;
int roll;
printf("What you would like to do:\n");
printf("Enter 'R' to fill the details again of all the student\n Enter 'U' to edit the
details of a single student\n");
printf("Enter 'S' to see the details of a particular student\n Enter 'A' to see the
details of every student\n");
scanf("%c", &input);
if (input == 'A' || 'a') {
for (int i = 0; i < 60; i++) {
printf("Roll no. : %d\n Name : %s\n Marks : %f\n", array[i].rollno, array[i].name,
array[i].marks);
}
}
else if (input == 'R' || 'r') {
for (int i = 0; i < 60; i++) {
printf("Roll no. os student is : %d\n", (i + 1));
printf("Enter students name :\n");
gets(array[i].name);
printf("Enter students marks :\n");
scanf("%f", &array[i].marks);
}
}
else if (input == 'S' || 's') {
printf("Enter the roll no. of the student of whom you want to see the details :\n");
scanf("%d", &roll);
printf("Roll no. :\n %d\n", roll);
printf("Name : \n");
puts(array[(roll - 1)].name);
printf("Marks : \n %f \n", (*(array + (roll - 1))->marks));
}
else if (input == 'U' || 'u') {
printf("Enter the roll no. of the student of whom you want to see the details :\n");
scanf("%d", &roll);
printf("Enter the name :\n");
gets((*(array + (roll - 1))->name));
printf("Enter the marks :\n");
scanf("%f", &(*(array + (roll + 1))->marks));
} else {
printf("Error Occured!!! \n");
printf("Re-enter your input\n");
goto again;
}
}
return 0;
}
There are many problems in your code:
there is no need for a goto again;, you already have an infinite loop while (1 == 1), which is usually written for (;;) in C. Don't use goto.
the definition struct student array[60]; should be moved outside the scope of the loop body. As posted, the array is discarded after each iteration and its contents become indeterminate.
array should be initialized to avoid undefined behavior when printing the contents before reading it from the user.
string literals cannot span multiple lines in a C source file. You can split them this way for readability:
printf("What you would like to do:\n"
"Enter 'R' to fill the details again of all the student\n"
"Enter 'U' to edit the details of a single student\n"
"Enter 'S' to see the details of a particular student\n"
"Enter 'A' to see the details of every student\n");
you should have a menu option to quit the program
reading a single character with scanf("%c", &input) is tricky: scanf() will read the pending newline from a previous call. You should use scanf(" %c", &input) where the space will cause pending whitespace to be read and discarded.
if (input == 'A' || 'a') does not test for A or a, it compares input to 'A' and if different compares 'a' to zero, hence the test is always true. You should write:
if (input == 'A' || input == 'a')
gets(array[i].name); is a NO NO. Don't use gets(), throw away the book that tells you to use it. For consistency with the other inputs, you can use
scanf("%19[^\n]", array[i].name);
Note that 19 tells scanf() the maximum number of characters to store into array[i].name before the null terminator, preventing undefined behavior for longer user input, and [^\n] causes scanf() to read and store characters up to and not including the newline character. %19s would stop at any white space, preventing the input of multiple words such as James Bond.
scanf("%f", &(*(array + (roll + 1))->marks)); is a very contorted way to write:
scanf("%f", &array[roll + 1].marks);
you should check the return value of scanf() to detect invalid input and flush the pending input on error.
Here is a modified version:
#include <stdio.h>
struct student {
int rollno;
char name[20];
float marks;
};
int main() {
struct student array[60] = { 0 };
int len = sizeof(array) / sizeof(*array);
int c, i, roll;
char input;
for (;;) {
printf("What you would like to do:\n"
"Enter 'R' to fill the details of all the student\n"
"Enter 'U' to edit the details of a single student\n"
"Enter 'S' to see the details of a particular student\n"
"Enter 'A' to see the details of every student\n"
"Enter 'Q' to quit the program\n");
if (scanf(" %c", &input) != 1)
break;
if (input == 'A' || input == 'a') {
for (i = 0; i < len; i++) {
printf("Roll no.: %d\nName: %s\nMarks: %f\n",
array[i].rollno, array[i].name, array[i].marks);
}
} else
if (input == 'R' || input == 'r') {
for (i = 0; i < len; i++) {
printf("Roll no. os student is: %d\n", i + 1);
printf("Enter student's name:\n");
if (scanf("%19[^\n]", array[i].name) != 1)
break;
printf("Enter students marks:\n");
if (scanf("%f", &array[i].marks) != 1)
break;
}
if (i < len) {
printf("Invalid input\n");
}
} else
if (input == 'S' || input == 's') {
printf("Enter the roll no. of the student of whom you want to see the details:\n");
if (scanf("%d", &roll) == 1 && roll >= 1 && roll <= len) {
printf("Roll no.: %d\nName: %s\nMarks: %f\n",
roll, array[roll - 1].name, array[roll - 1].marks);
} else {
printf("Invalid Roll no\n");
}
} else
if (input == 'U' || input == 'u') {
printf("Enter the roll no. of the student of whom you want to see the details:\n");
if (scanf("%d", &roll) == 1 && roll >= 1 && roll <= len) {
printf("Enter the name:\n");
scanf("%19[^\n]", array[roll - 1].name);
printf("Enter the marks:\n");
scanf("%f", &array[roll - 1].marks);
} else {
printf("Invalid Roll no\n");
}
} else
if (input == 'Q' || input == 'q') {
return 0;
} else {
printf("Invalid entry\n");
printf("Re-enter your input\n");
}
/* read and discard the rest of the input line */
while ((c = getchar()) != EOF && c != '\n')
continue;
}
printf("Premature end of file\n");
return 0;
}

How can I modify program to set array range from 0 to 100 in program below

I need the code below to recognize if the grades entered is below 1 or greater than 100. If it is not within the parameters, I want to let the user know and allow them to enter another grade without exiting the program or losing grades they have already entered. I don't want the program to quit until the user enters q and I want to ensure all of the valid grades entered print at that time. I have tried numerous methods and am not getting the right results. I think I probably need some other else if statement, but I haven't been able to find the right one to work. Any information you can share to get me on the right track would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection in Parenthesis******\n Add grades(a)\n Quit(q) \n");
scanf("%c",&choice);
if(choice == 'a' || 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
if(choice == 'q') //if the user choice is q, then exit the loop
{
break;
}
}
printf("Grades are:\n");
for(i=0; i<gCount; i++)
{
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}
You can do a while loop to verify the user input. With a while you'll be able to force the user to enter the right grade.
if(choice == 'A' || choice == 'a'){
printf("Enter grade:");
scanf("%d", &grades);
getchar();
while(grade < 1 || grade > 100){
printf("You entered a wrong number\n");
printf("Enter a grade between 1 and 100: ");
scanf("%d", &grades);
getchar();
}
gradeArray[gCount] = grades;
}
your solution is almost aligned with what you had in mind. Here is how you can do it differently.
#include <stdio.h>
int main()
{
char choice;
int arraySize = 100; //change this to any number you wish
int gradeScore = 0;
int gradeArray[arraySize];
int gCount = 0;
int showCount = 0;
while(choice != 'q')
{
//to ask for user's input every time
printf("What do you want to do? Enter\n");
printf("'a' to add grades\n");
printf("'q' to quit\n");
scanf(" %c", &choice); //space is entered to ensure the compiler does not read whitespaces
//your implementation should check for user input before proceeding
if(choice != 'a')
{
//in this condition, 'q' is technically an incorrect input but your design states that 'q' is for quitting
//thus, do not alert the user here if 'q' is entered
if(choice != 'q')
{
//a condition to warn the user for incorrect input
printf("Incorrect input. Please enter only 'a' or 'q'\n");
}
}
else if(choice == 'a')
{
printf("Enter grade: \n");
scanf(" %d", &gradeScore);
//to check for user input if the grades entered are less than 1 or more than 100
if(gradeScore < 1 || gradeScore >100)
{
//print a warning message
printf("The grade you entered is invalid. Please enter a grade from 1 - 100\n");
}
//for all correct inputs, store them in an array
else
{
printf("Grade entered\n");
gradeArray[gCount] = gradeScore;
gCount++;
}
}
}
//prints grade when 'q' is entered
if(choice == 'q')
{
printf("Grades are: \n");
for(showCount = 0; showCount < gCount ; showCount++)
{
printf("%d\n", gradeArray[showCount]);
}
}
}
To sum up the important parts, be sure to check for the user grade input to be in range of 1 - 100. Store the grade in the array if it is within range and be sure to increase the array counter, otherwise it will always store it in gradeArray[0] for the subsequent grades. Hope this helps
Use a do-while loop to keep the program looping back to get another choice unless a valid choice has been entered. Use fgetc to read a single character - fewer problems. Only print grades if at least one grade has been entered.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char choice;
int gradeArray[100];
int grades;
int gCount=0,i;
for(gCount=0; gCount<100; gCount++)
{
//for loop to read the grades till array size
printf("******Enter Choice Selection******\n Add grades(a)\n Quit(q) \n");
do
{
choice = fgetc(stdin);
if(choice == 'a' || choice == 'A')
{
//if user choice is a, then read the grade
printf( "Enter grade: ");
scanf("%d", &grades);
getchar();
gradeArray[gCount] = grades; //add the grade to array
}
else if(choice != 'q')
printf("Invalid choice - try again\n");
} while (choice != 'a' && choice != 'A' && choice != 'q');
if(choice == 'q') //if the user choice is q, then exit the loop
break;
}
if(gCount > 0)
{
printf("Grades are:\n");
for(i=0; i<gCount; i++)
printf(" %d%%\n", gradeArray[i]); //print grades
}
return 0;
}

While loop doesnt work on the first time when accessing it for the second time

Okay so I have run a function 4 times. It runs perfectly the first time but when i have to run that function again the 3 other time, i get the "* INVALID ENTRY * : " printf that i made when the user doesnt input a 'y' or 'Y' or 'n' or 'N'
Also, I am trying to make it so that whenever a user enters "Yes or No" it will prompt the "error message" but currently the way i wrote my program it takes only the first Character from the user" Ex: Inputs "Yes" the program will take only "Y" which makes the program think the user entered 'Y' which skips the error stage.
This is what is in my main
printf("Please enter 'Y' > ");
printf(" Result: %d\n", yes() );
printf("Please enter 'y' > ");
printf(" Result: %d\n", yes());
printf("Please enter 'N' > ");
printf(" Result: %d\n", yes());
printf("Please enter 'yes', then 'no', then 'n' > ");
printf(" Result: %d\n", yes());
And this is my part im trying to access.
int yes(void) {
char singleLetter;
int theResults = 0;
scanf("%c", &singleLetter);
while ((singleLetter != 'y') && (singleLetter != 'Y') && (singleLetter != 'n') && (singleLetter != 'N')) {
clearKeyboard();
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
scanf("%c", &singleLetter);
}
if ((singleLetter == 'y') || (singleLetter == 'Y')) {
theResults = theResults++;
}
if ((singleLetter == 'n') || (singleLetter == 'N')) {
theResults = 0;
}
//printf("%c",singleLetter);
return theResults;
}
The results are:
Please enter 'Y' > Y
Result: 1
Please enter 'y' > y
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: y
Result: 1
Please enter 'N' > N
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: N
Result: 0
Please enter 'yes', then 'no', then 'n' > yes
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: no
Result: 0
EDIT::
I fixed the above code so it works fine
However when I call yes() from a different function i get this error:
This is the code im trying to call from:
void getName(struct Name *contactName) {
printf("Please enter the contact's first name: ");
scanf("%s", (*contactName).firstName);
printf("Do you want to enter a middle intial(s)? (y or n): ");
yes();
if (yes() == 1) {
printf("Please enter the contact's middle intial(s): ");
scanf("%s", (*contactName).middleInitial);
}
printf("Please enter the contact's last name: ");
scanf("%s", (*contactName).lastName);
}
I fixed the yes() code with
int yes(void) {
char singleLetter;
int theResults = 0;
scanf("%c", &singleLetter);
clearKeyboard();
while ((singleLetter != 'y') && (singleLetter != 'Y') && (singleLetter != 'n') && (singleLetter != 'N')) {
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
scanf("%c", &singleLetter);
clearKeyboard();
}
if ((singleLetter == 'y') || (singleLetter == 'Y')) {
theResults = theResults + 1;
}
if ((singleLetter == 'n') || (singleLetter == 'N')) {
theResults = 0;
}
return theResults;
}
i get this error. Literally makes me enter y 3 times, and i get a invalid entry code for no reason.
Do you want to enter a middle intial(s)? (y or n): y
*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: y
y
Please enter the contact's middle intial(s):
EDIT PART 2
I fixed my function yes() by doing this:
int yes(void) {
char singleLetter = ' ';
int finalValue = -1;
int theResult = 0;
scanf(" %c", &singleLetter);
clearKeyboard();
do
{
switch (singleLetter)
{
case 'Y':
case 'y':
finalValue = 1;
theResult = 1;
break;
case 'N':
case 'n':
finalValue = 0;
theResult = 1;
break;
default:
theResult = 0;
printf("Only (Y)es or (N)o are acceptable: ");
scanf("%c", &singleLetter);
clearKeyboard();
}
} while (!theResult);
return finalValue;
}
And this is the code im not sure with NEAR THE END OF THE CODE:
void getName(struct Name *contactName) {
printf("Please enter the contact's first name: ");
scanf("%s", (*contactName).firstName);
printf("Do you want to enter a middle intial(s)? (y or n): ");
if (yes() == 1) {
printf("Please enter the contact's middle intial(s): ");
scanf("%s", (*contactName).middleInitial);
}
printf("Please enter the contact's last name: ");
scanf("%s", (*contactName).lastName);
}
// getAddress:
void getAddress(struct Address *
contactAddress) {
printf("Please enter the contact's street number: ");
(*contactAddress).streetNumber == getInt();
printf("Please enter the contact's street name: ");
scanf(" %[^\n]", (*contactAddress).street);
printf("Do you want to enter an apartment number? (y or n): ");
if (yes() == 1) {
printf("Please enter the contact's apartment number: ");
scanf("%d", (*contactAddress).apartmentNumber);
}
printf("Please enter the contact's postal code: ");
scanf(" %[^\n]", (*contactAddress).postalCode);
printf("Please enter the contact's city: ");
scanf("%s", (*contactAddress).city);
}
// getNumbers:
// getNumbers:
// NOTE: Also modify this function so the cell number is
// mandatory (don't ask to enter the cell number)
void getNumbers(struct Numbers *contactNumber) {
printf("Please enter the contact's cell phone number: ");
scanf(" %s", (*contactNumber).cell);
printf("Do you want to enter a home phone number? (y or n) ");
if (yes() == 1) {
printf("Please enter the contact's home phone number: ");
scanf("%s", (*contactNumber).home);
}
printf("Do you want to enter a business number? (y or n) ");
if (yes() == 1) {
printf("Please enter the contact's business phone number: ");
scanf("%s", (*contactNumber).business);
}
printf("\n");
}
AND BELOW THAT I HAVE THIS AND DONT KNOW WHAT TO DO. AS I STATED IN THE COMMENT:
The purpose of this function is to set the values for a Contact using
the pointer parameter variable (set the Contact it points to).
Use the pointer parameter received to this function to supply the appropriate
Contact member to the “get” functions (getName, getAddress, and getNumbers) to set the values for the Contact.
void getContact(struct Contact *contact) {
getName(contact);
getAddress(contact);
getNumbers(contact);
}
THE BELLOW IS WHATS BEING ACCESSED/PRINTED. Whatever i enter, it doesnt show up because of void getContact(struct Contact *contact){ }
getContact(&contact);
printf("\nValues Entered:\n");
printf("Name: %s %s %s\n", contact.name.firstName, contact.name.middleInitial, contact.name.lastName);
printf("Address: %d|%s|%d|%s|%s\n", contact.address.streetNumber, contact.address.street,
contact.address.apartmentNumber, contact.address.postalCode, contact.address.city);
printf("Numbers: %s|%s|%s\n", contact.numbers.cell, contact.numbers.home, contact.numbers.business);
scanf retains the newline \n in the buffer, the next time scanf is executed, the newline is read instead. Consider this program:
#include <stdio.h>
int main(void)
{
char x;
scanf("%c", &x);
printf("%d: '%c'\n", x, x);
scanf("%c", &x);
printf("%d: '%c'\n", x, x);
return 0;
}
The output for the input w<ENTER>s<ENTER>
w
119: 'w'
10: '
'
In ASCII 119 is 'w' and 10 is '\n'.
If you add a getchar() after the scanf, then getchar() reads the newline
and then nothing is in the buffer left, then the next scanf waits for the user input again:
#include <stdio.h>
int main(void)
{
char x;
scanf("%c", &x);
getchar(); // <-- look here
printf("%d: '%c'\n", x, x);
scanf("%c", &x);
printf("%d: '%c'\n", x, x);
return 0;
}
with the same input I get
w
119: 'w'
s
115: 's'
So, to solve your problem, you can add a getchar() after every scanf.
The best way to clear the buffer after using scanf:
int c;
while((c = getchar() !='\n') && c !=EOF );
EDIT
How to use fgets
man fgets
#include <stdio.h>
char *fgets(char *s, int size, FILE *stream);
fgets() reads in at most one less than size characters from stream and stores them into the buffer
pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into
the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
Simply to get a line, you do:
char line[1024];
fgets(line, sizeof line, stdin);
fgets will returns NULL when there is no more lines to read or there is an
error. Either way when that happens, you usually stop reading the file. That's
why to read all lines from a file (or multiple lines from the user), you do
this:
char line[1024];
while(fgets(lines, sizeof line, stdin))
{
// do the work here
}
Bear in mind, that sizeof line in fgets is only correct, when line is an
array. If you for example allocate memory with malloc, you cannot use
sizeof line. If you get a pointer, then you have to know in advance how much
you can read.
size_t n = <some value>; // the value is not imporant,
// could be 100, could be 985
char *line = malloc(n);
if(line == NULL)
{
// error handling, for example return error value
}
// only if line is not NULL
fgets(line, n, stdin); // here I know the size in advance
// or as argument
void foo(char *buffer, size_t size)
{
fgets(buffer, size, stdin);
...
}
If the length of the line is lesser than the size (minus 1) of the buffer, the
newline character will be stored in the buffer. If you don't need it, you can
set it to 0 in order to get rid of the newline:
char line[1024];
fgets(line, sizeof line, stdin);
int len = strlen(line);
if(line[len - 1] == '\n')
line[len - 1] = 0;
But if you don't mind having the newline, then you don't have to do that.
So you could write your yes function with fgets. Get the whole line, even
if you are only interested in the first character, you can ignore the rest of
the characters in the line.
#include <ctype.h>
int yes(void) {
int theResults = 0;
char line[1024];
if(fgets(line, sizeof line, stdin) == NULL)
{
fprintf(stderr, "could not get line, aborting\n");
return -1; // error value
}
while(toupper(line[0]) != 'Y' && toupper(line[0]) != 'N') {
printf("*** INVALID ENTRY *** <Only (Y)es or (N)o are acceptable>: ");
if(fgets(line, sizeof line, stdin) == NULL)
{
fprintf(stderr, "could not get line, aborting\n");
return -1; // error value
}
}
if(toupper(line[0]) == 'Y')
theResults++;
else
theResults = 0;
return theResults;
}

How to make a function in 'C' to go to start of program

I am a beginner in C...
I have made a made a calculator type program which uses four basic functions in C using if-else loop.
I want when the program comes to end(after the user has added, subtracted etc. etc. then there is a option "Y/N" so that the program can be restarted???"
Here is the sample of the code
#include<stdio.h>
int main()
{
int choi;
printf("*****Interactive Calculator*****");
printf("\n\nChoose an option...");
printf("\n\n1. Addition\n");
printf("\n2. Subtraction");
printf("\n\n3. Multiplication");
printf("\n\n4. Division");
printf("\n\nPlease Enter your Choice : ");
scanf("%d",&choi);
if(choi==4)
{
float a=0,b=0,c=0;
printf("\nEnter Divident :");
scanf("%d",&a);
printf("\nEnter the Divisor :");
scanf("%d", &b);
c=a/b;
printf("\nThe Quotient is : %d\n\n",c);
char choice;
printf("Do you want to try it again?(Y/N) ");
scanf("%c", &choice);
// I want a code here so that the program can be restarted
getch();
return 0;
}
else
{
printf("\nErr#404-Invalid Character! Please Enter 1,2 or 3 !\n\n");
}
end:
getch();
return 0;
}
The best way would be to do some sort of a while loop.
int goAgain=1;
while (goAgain==1) {
... //Normal code here
printf("Again?")
scanf("%c",&again)
if (again=='N') {
goAgain=0;
}
}
Or you could use a do-while loop as well
do {
... //Normal code here
printf("Again?")
scanf("%c",&again)
} while (again=='Y')
Basically, this will keep looping over the bit of code over and over until the person types N to end it.
A do-while loop would be most suitable for this purpose.
int main() {
char choice;
do {
// Calculator stuff here...
printf("Do you want to try it again? (Y/N) ");
scanf("%c", &choice);
} while (choice == 'Y');
}
Edit: As it turns out, there is another problem with the program above, which is that scanf() reads a character but leaves a Newline character in the buffer. Therefore, if the user types YEnter, the program will repeat once (choice == 'Y' the first time), then exit (choice == '\n' the second time).
It is therefore necessary to keep reading until the Newline has been consumed.
int main() {
char choice;
do {
// Calculator stuff here...
printf("Do you want to try it again? (Y/N) ");
choice = getchar();
while (choice != '\n' && getchar() != '\n') {};
} while (choice == 'Y' || choice == 'y');
}
char continue = 'Y'
while (continue == 'Y') {
... //Normal code here
printf("Again?")
scanf("%c",&continue)
}
you can try like this, avoid go to
#include<stdio.h>
int main()
{
int choi;
while(true)
{
printf("*****Interactive Calculator*****");
printf("\n\nChoose an option...");
printf("\n\n1. Addition\n");
printf("\n2. Subtraction");
printf("\n\n3. Multiplication");
printf("\n\n4. Division");
printf("\n\n5. Exit");
printf("\n\nPlease Enter your Choice : ");
scanf("%d",&choi);
if(choi==1)
{
}
else if(choi==2)
{
}
else if(choi==3)
{
}
else if(choi==4)
{
}
else if(choi==5)
{
return 0; //exit(0);
}
else
{
printf("\nErr#404-Invalid Character! Please Enter 1,2,3,4 or 5 !\n\n");
}
}
return 0;
}
By using do-while loop, which is generally used for menu-driven programs.
#include<stdio.h>
int main()
{
int choi;
char choice;
do{
printf("*****Interactive Calculator*****");
printf("\n\nChoose an option...");
printf("\n\n1. Addition\n");
printf("\n2. Subtraction");
printf("\n\n3. Multiplication");
printf("\n\n4. Division");
printf("\n\nPlease Enter your Choice : ");
scanf("%d",&choi);
if(choi==4)
{
float a=0,b=0,c=0;
printf("\nEnter Divident :");
scanf("%d",&a);
printf("\nEnter the Divisor :");
scanf("%d", &b);
c=a/b;
printf("\nThe Quotient is : %d\n\n",c);
char choice;
printf("Do you want to try it again?(Y/N) ");
scanf("%c", &choice);
// I want a code here so that the program can be restarted
getch();
return 0;
}
else
{
printf("\nErr#404-Invalid Character! Please Enter 1,2 or 3 !\n\n");
}
printf("Want to continue (y/n)?");
scanf("%d", &choice); // Enter the character
}while (choice == 'y' || choice == 'Y');
end:
getch();
return 0;
P.S.: I would suggest you to use switch case, instead of if-else statements to do the job.
You can also use a goto:
int main() {
...
if (c=='y') {
main();
} else {
goto end;
}
end:
...
}

Resources