C uninitialized local variable error - c

New to C still learning.
The program should start the first time with out needing to be asked to do anything. Then it prompts the user to continue with a "Y/N". I keep errors could anyone tell me why it doesn't work I don't know what to do with the errors that I get from it.
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <ctype.h>
void theQnA(char charIn);
int main(void)
{
int answerint = 0;
char charIn;
char anwser;
printf("Enter a character to be examined: ");
scanf("%c", &charIn);
theQnA(charIn);
while (answerint == 0)
{
printf("Would you like to run it again? Y/N\n");
scanf("%c", &anwser);
if (anwser == 'y')
{
printf("Enter in another character buddy\n");
scanf("%c", &charIn);
theQnA(charIn);
}
else (anwser != 'y')
{
answerint = (answerint--);
}
}
printf("Goodbye\n");
return 0;
}
void theQnA(char charIn)
{
if (islower(charIn))
printf("You have entered in a lower case letter dude\n");
else if (isdigit(charIn))
printf("You enterd in a num man\n");
else if (isupper(charIn))
printf("Its upper case man\n");
else if (ispunct(charIn))
printf("You entered in a punctuation!\n");
else if (isspace(charIn))
printf("You enterd in a whitespace dude\n");
else
printf("control char/n");
return;
}

You have else (anwser != 'y'). It should be else if (anwser != 'y'), or better yet just else. The prompt Would you like to run it again? Y/N will also be printed twice because of how your loop is structured. You have quite a few mistakes, but here's some advice on your loop.
You can use your anwser variable in your while condition. answerint is unnecessary. Also, when you type a character and press enter, scanf (with %c) will extract the character but leave the newline in the buffer. That means the next call to scanf will return a newline, which will make it appear as if your program is skipping your input statements. To fix this, add a space before the %c in your call:
scanf(" %c", &charIn);
Your logic was also a bit out of place. Look at how this example is structured.
printf("Enter a character to be examined: ");
scanf(" %c", &charIn);
theQnA(charIn);
printf("Would you like to run it again? y/n\n");
scanf(" %c", &anwser);
while (anwser == 'y')
{
printf("Enter in another character buddy: ");
scanf(" %c", &charIn);
theQnA(charIn);
printf("Would you like to run it again? y/n\n");
scanf(" %c", &anwser);
}

Related

Do while loop with Character input

I have written this simple program, which is supposed to calculate the factorial of a number entered by the user. The program should ask the user to stop or continue the program in order to find the factorial of a new number.
since most of the time user don't pay attention to CapsLock the program should accept Y or y as an answer for yes. But every time I run this program and even though I enter Y/y , it gets terminated !
I googled and found out the problem could be due to new linecharacter getting accepted with my character input so, I modified the scanf code from scanf("%c", &choice); to scanf("%c ", &choice); in order to accommodate the new line character , but my program is still getting terminated after accepting Y/y as input.
Here is the code . Please if possible let me know the best practices and methods to deal with these kinds of issues along with the required correction.
#include<stdio.h>
#include"Disablewarning.h" // header file to disable s_secure warning in visual studio contains #pragma warning (disable : 4996)
void main() {
int factorial=1;//Stores the factorial value
int i; //Counter
char choice;//stores user choice to continue or terminte the program
do {//Makes sure the loop isn't terminated until the user decides
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
} while (i<0);
if (i == 0) //calculates 0!
factorial = 1;
else {//Calculates factorial for No greater than 1;
while (i > 0) {
factorial = factorial*i;
i--;
}
}
printf("\nThe factorialof entered no is :\t%d", factorial);//prints the final result
printf("\nDo you want to continue (Y/N)?");
scanf("%c ", &choice);
} while (choice =="y" || choice =="Y"); // Checks if user wants to continue
}
I'm a beginner in programming and I'm running this code in visual studio 2015.
Just modify your scanf like following:
printf("\nDo you want to continue (Y/N)? ");
scanf(" %c", &choice); //You should add the space before %c, not after
also you should use:
} while (choice == 'y' || choice == 'Y'); // Checks if user wants to continue
NOTE:
Simple quote ' is used for characters and double quote " is used for string
Your second-last line has a string literal "y", which should be a character literal i.e. 'y':
} while (choice =="y" || choice =="Y");
This should be:
} while (choice =='y' || choice =='Y');
Also, your scanf() doesn't consume whitespace. Add a space before %c to make it ignore newlines or other spaces:
scanf(" %c", &choice);
Try doing the following even after the correction there are still some bugs in the code
In your code if you type 'Y' and recalculate a factorial it gives wrong answer as
int factorial is already loaded with the previous value
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
using namespace System;
using namespace std;
int calculateFactorial(int i);
int main()
{
int i;
char choice;
do{
printf("Enter the no whose factorial you want to calculate:\t");
scanf("%d", &i);
printf("\n The factorial of entered no is :\t %d", calculateFactorial(i));
printf("\n Do you want to continue (Y/N)?");
scanf(" %c", &choice);
} while (choice == 'y' || choice == 'Y');
return 0;
}
int calculateFactorial(int i) {
int factorial = 1;
if (i == 0){
factorial = 1;
}else {
while (i > 0){
factorial = factorial*i;
i--;
}
}
return factorial;
}

How to loop a whole codeblock in C?

So basically after the calculation the program prompts the user if they want to quit the program and the user inputs a character ('y' or 'n') and if the user puts a number or letter that is not 'y' or 'n' then the program will keep prompting the user until they input one of the characters.
The issue I'm running into is that the program will keep looping and prompting the user even if 'y' or 'n' is inputted. When I try fflush(stdin) it still doesn't work
I want to know how to loop the statement again if the user does not input one of the options and when they do input it properly, how to get the code inside the "do while" loop to repeat. Preferably without having to copy and paste the whole bloc again.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");
scanf("%f", &x);
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
scanf("%f", &t);
}
fflush(stdin);
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
scanf() will not throw away the newline character '\n' in the input buffer unless your format string is set to discard it. In your code, after entering input for your floats and pressing Enter, the newline is still in the buffer. So for the code that prompts Y\N, use this format string to ignore the newline
scanf(" %c",&d);
You can remove the fflush() calls if you do that. In your case, it looks like your loop conditionals are wrong though.
This line
while (d != 'y' || d != 'n')
is wrong.
Think of it like this:
The loop runs if d is NOT 'y' OR d is NOT 'n'
Now imagine you put in 'y'
d is 'y'. The loop runs if d is NOT 'y' OR d is NOT 'n'. Is d != 'y'? No. Is d != 'n'? Yes. Therefore the loop must run.
You need to use &&
while (d != 'y' && d != 'n')
Also, scanf doesn't throw away the newline so add a space for all your scanfs.
scanf("%c", &d); //change to scanf(" %c", &d);
Look in this part-
while (d != 'y' || d != 'n')
{
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
}
} while (d == 'n');
you are using whiletwice, i think you will wish to have a single while condition over here.. also if you are terminating while, then be sure there is a doinvolved.
Here is code which I think is right since you have many problems so i just have changed a lot :
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>
int main()
{
float x, t, term = 1 , sum = 1;
int i;
char d;
printf("This program will compute the value of cos x, where x is user input\n\n");
do {
printf("Please input the value of x: ");
while (scanf("%f", &x) != 1)
{
fflush(stdin);
printf("Please input the value of x: ");//delete the repeat scanf
}
fflush(stdin);
printf("\nPlease input the number of terms: ");
while (scanf("%f", &t) != 1)
{
fflush(stdin);
printf("\nPlease input the number of terms: ");
}
fflush(stdin);
sum=0;//no initalization
for (i=1; i<t+1; i++)
{
term = -term *((x*x)/((2*i)*(2*i-1)));
sum = sum+term;
}
printf("\nThe value of the series is %f", sum);
printf("\n****************************************");
printf("\nDo you wish to quit? (y/n): ");
scanf("%c", &d);
while ((d != 'y' )&& (d != 'n'))//this logical expression is the right way
{
scanf("%c", &d);
fflush(stdin);
printf("\n****************************************");//I change the pos of print to avoid double printing
printf("\nDo you wish to quit? (y/n): ");
}
} while (d == 'n');
if (d == 'y')
{
printf("terminating program");
exit(0);
}
return (0);
}
ps:for your calculate part of cos I'm not sure about the correctness while runing:)

switch statement creating infinite loop

I am writing a piece of code and in one part of my code I am using a switch statement in C language. if I press n it exits correctly if I press y it will infinite loop the default statement until I press control c. what am I doing wrong here. been changing the while statement but can't find the right one.
int main()
{
char ans;
printf("DO you want to continue?");
scanf("%c", &ans);
do
{
switch(ans)
{
case 'y':
some stuff...
printf("DO you want to continue?");
scanf("%c", &ans);
break;
case'n':
printf("BYE");
break;
default:
printf("error, you must enter y or n");
continue;
}
}
while (ans!='n');
return 0;
}
When you press enter, the linefeed character \n is added to the input stream. Your code does not anticipate this, because switch(ans) only handles y, n or “everything else” (which includes the linefeed character).
To fix this, allow scanf to ignore any preceding whitespace by changing your format string to " %c" instead, e.g.
scanf(" %c", &ans);
// ^ space character inserted here
I think it would make more sense to move the scanf call to inside the loop, like this:
int main()
{
char ans;
do
{
printf("DO you want to continue?");
if (scanf(" %c", &ans) != 1)
break;
switch(ans)
{
case 'y':
// some stuff...
break;
case 'n':
printf("BYE");
break;
default:
printf("error, you must enter y or n");
continue;
}
}
while (ans!='n');
}
Don't forget to always check the result of scanf(). It will return the number of items successfully scanned (in your case, you want it to return 1). If it returns 0 or a negative number, then another problem has occurred.

My code repeats more than requried while loop

The problem is that when i type any character except for y or n it display this message two times instead to one)
This program is 'Calculator'
Do you want to continue?
Type 'y' for yes or 'n' for no
invalid input
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main ()
{
//program
//first to get two numbers
//second to get choice
int x=0,y=0,n=0;
char choice;
//clrscr(); does no work in devc++
system("cls"); //you may also use system("clear");
while(x==0)
{
puts("\t\tThis program is 'Calculator'\n\n");
puts("Do you want to continue?");
puts("Type 'y' for yes or 'n' for no ");
scanf("%c",&choice);
x++;
if(choice=='y')
{
y++;
puts("if this worked then we would continue to calculate the 2 no");
}
else if(choice=='n')
exit(0);
else
{
puts("invalid input");
x=0;
}
}
getch();
}
`
it looping twice because enter(\n) character is stored in buffer use scanf like this(add space before %c)
scanf(" %c",&choice);
That is because of the trailing new line after you enter y or n and hit enter key.
Try this out:
scanf("%c",&choice);
while(getchar()!='\n'); // Eats up the trailing newlines
If you input any character other than 'y' or 'n', control enters the :
else
{
puts("invalid input");
x=0;
}
block, which resets x to 0, Now the loop condition :
while(x == 0)
is true and hence it enters the loop again.
Also you may want to skip the trailing newline character while reading like :
scanf(" %c", &choice );

Yes/No loop in C

I just don't understand why this Yes/No loop will not work. Any suggestions? Given the input is "Y". I just want it to run the loop, then ask for Y or N again. If Y, print success, if N, print a good bye statement. What's the reason?
int main(){
char answer;
printf("\nWould you like to play? Enter Y or N: \n", answer);
scanf("%c", &answer);
printf("\n answer is %c");
while (answer == 'Y'){
printf("Success!");
printf("\nDo you want to play again? Y or N: \n");
scanf("%c", &answer);
}
printf("GoodBye!");
return 0;
}
Change the second scanf to:
scanf(" %c", &answer);
// ^
The problem is, when you enter Y and press ENTER, the new line is still in the input buffer, adding a space before %c could consume it.
fixed the various issues
#include <stdio.h>
int main(){
char answer;
printf("\nWould you like to play? Enter Y or N: \n");
scanf(" %c", &answer);
printf("\n answer is %c\n", answer);
while (answer == 'Y'){
printf("Success!");
printf("\nDo you want to play again? Y or N: \n");
scanf(" %c", &answer);
printf("\n answer is %c\n", answer);
}
printf("GoodBye!");
return 0;
}
You can reduce the repetition in your code a bit, and check the result of scanf() (as you should) by writing:
int main(void)
{
char answer;
printf("Would you like to play? Enter Y or N: ");
while (scanf(" %c", &answer) == 1 && answer == 'Y')
{
printf("Answer is %c\n", answer);
printf("Success!\n");
printf("Do you want to play again? Y or N: ");
}
printf("GoodBye!\n");
return 0;
}
The first printf() lost the unused argument answer; the second printf() collected the necessary second argument, answer. Except for prompts, it is generally best to end printing operations with a newline (rather than use a newline at the start). Prompts will generally be flushed by the C library before the input from stdin is read, so you don't need the newline at the end of those.
Since printf() returns the number of characters it prints, you can use it in conditions too:
int main(void)
{
char answer;
printf("Would you like to play? Enter Y or N: ");
while (scanf(" %c", &answer) == 1 &&
printf("Answer is %c\n", answer) > 0 &&
answer == 'Y')
{
printf("Success!\n");
printf("Do you want to play again? Y or N: ");
}
printf("GoodBye!\n");
return 0;
}
This always echoes the answer, even if the answer was not Y and the loop exits.

Resources