User Input of Integers Infinite Loop Until User Inputs a Character (C) - c

i'm new to C - I have intended to make a program that shows whether the user input int is odd or even, until the user decides to quit by inputing a char 'x'. The loop kind of works by detecting odd numbers and terminating the program with 'x', however glitches with even numbers - why is that so? Would appreciate it if you could point out the flaws in the code. Thank you
#include <stdio.h>
int main(void)
{
int i=0;
char x = "x";
printf("Enter an integer to check whether your number is odd or even\n");
printf("Enter an ´x´ at any time to quit the program\n");
do
{
scanf("%d", &i);
if (i % 2 == 0)
{
printf("The number is even\n");
}
else if (i % 2 != 0)
{
printf("The number is odd\n");
}
else("%c ", &x);
{
scanf(" %c", &x);
getchar();
printf("The program will now terminate\n");
return 0;
}
}
while (i > 0);
i++;
return 0;
}

Very close but I've marked a couple of changes:
#include <stdio.h>
int main(void)
{
int i=0;
char x = 'x'; // Note: single quotes for char, double for string
printf("Enter an integer to check whether your number is odd or even\n");
printf("Enter an ´x´ at any time to quit the program\n");
do
{
int n = scanf("%d", &i); // Check if number was read
if (n == 1) {
if (i % 2 == 0)
{
printf("The number is even\n");
}
else // Only other possibility
{
printf("The number is odd\n");
}
} else // No number, see if there's an 'x'
{
scanf(" %c", &x);
if (x == 'x')
{
printf("The program will now terminate\n");
return 0;
} else
{
printf("Unknown input %c\n", x);
}
}
}
while (i > 0); // Will also end if user enters <= 0
return 0;
}

Related

using several different functions

For my assignment, my program needs to ask the user which of the five functions he wants to execute. The five functions include:
Summation of a number
Factorial of a number
Fibonacci value of the nth term.
gcd of two numbers
a to the power of b.
The user will be prompted repeatedly until he wishes to exit. All my functions work fine. However, i think i messed up on one of the loops because once i enter which function i want to execute and enter a value, it keeps displaying the answer in an infinite loop.
#include <stdio.h>
#include <math.h>
// function to find summation of a number
int summation(int k) {
int i;
for(i = k; i >= 0; i--) {
k = i + (i-1);
}
return k;
}
// function to find the factorail of a number
int factorial(int num) {
int i;
for(i = num - 1; i > 0; i--) {
num = num * i;
}
return num;
}
// dunxtion to find the fibonacci of the nth term
int fibonacci(int n){
int i, t1 = 0, t2 = 1, nextTerm;
for(i = 1; i <= n; i++) {
if(i == 1) {
printf("%d, ", t1);
continue;
}
if(i == 2) {
printf("%d, ", t2);
continue;
}
nextTerm = t1 + t2;
t1 = t2;
t2 = nextTerm;
printf("%d, ", nextTerm);
}
return nextTerm;
}
// function to find the gcd of two numbers
int gcd(int n, int m) {
int i, gcd;
for(i=1; i <= n && i <= m; i++) {
// Checks if i is a factor of both integers
if(n % i == 0 && m % i == 0)
gcd = i;
}
return gcd;
}
// function to find value of n to the power of m
int power(int n, int m) {
return pow(n, m);
}
int main(void) {;
int option ,n, m;
//Asks user for what they want to find
printf("If you would like to find the summation of a number, enter 1 \n");
printf("If you would like to find the factorial of a number, enter 2 \n");
printf("If you would like to find the fibonacci sequence of a number, enter 3 \n");
printf("If you would like to find the gcd of two numbers, enter 4 \n");
printf("If you would like to find the power of a number a to b, enter 5 \n");
printf("If you would like to exit, enter 0 \n");
scanf("%d", &option);
// Enables the program to prompt the user until they wish to exit
while(option != 0) {
switch(option) { //If user wishes to find the summation
case 1: if(option == 1) {
printf("Enter a number: ");
scanf("%d", &n);
while(n > 0) {
if(n < 1) { //message displayed if an invalid value is entered
printf("invalid value");
}
else {
printf("Summation of %d is %d", n, summation(n));
}
}
}
case 2: if(option == 2) { //if user wishes to find factorial of a number
printf("Enter a number: ");
scanf("%d", &n);
while(n >= 0) {//message displayed if an invalid value is entered
if(n < 0) {
printf("invalid value");
}
else {
printf("factorial of %d is %d", n, factorial(n));
}
}
}
case 3: if(option == 3) { //if user wishes to find the fibonacci value of the nth term
printf("Enter a number: ");
scanf("%d", &n);
while(n >= 0) {//message displayed if an invalid value is entered
if(n < 0) {
printf("invalid value");
}
else {
printf("fibonacci of %d is %d", n, fibonacci(n));
}
}
}
case 4: if(option == 4) {
printf("Enter a number: ");
scanf("%d %d", &n, &m);
while(n >= 0 && m >= 0) {
if(n < 0 || m < 0) {//message displayed if an invalid value is entered
printf("invalid value");
}
else {
printf("GCD of %d and %d is %d", n, m, gcd(n, m));
}
}
}
case 5: if(option == 5) {
printf("Enter a number: ");
scanf("%d %d", &n, &m);
while(n >= 0 && m >= 0) {
if(n <= 0 || m < 0) {
printf("invalid value");
}
else {
printf("%d to the power of %d is %d", n, m, power(n, m));
}
}
}
default: if(option == 0) {
break;
}
}
scanf("%d", &option);
}
}
First of all, C has unstructured switch statement.
You need to add a break; statement after each of your case body to limit the execution for a particular case to the body mentioned under that case.
Otherwise, by default, (with the absence of a break statement) all the case statements works in fall-through manner. You can read more about it here.
That said, regarding the repeated execution of a single function, there's a serious flaw in most (if not all) of the the logic. For example, let's take this
while(n > 0) {
if(n < 1) { //message displayed if an invalid value is entered
printf("invalid value");
}
else {
printf("Summation of %d is %d", n, summation(n));
}
}
here, you're replying on n becoming 0 at some point to break out of the loop, but you did not modify n, at all.
To elaborate, C uses pass-by-value for argument passing, so for the call, summation(n), inside the function, whatever change you make to the parameter receiving the value of n, is not reflected in the caller, and thus, the n in the caller remains unchanged.
You just need a break statement at the end of every case
like:
case 1: if(option == 1) {
printf("Enter a number: ");
scanf("%d", &n);
while(n > 0) {
if(n < 1) { //message displayed if an invalid value is entered
printf("invalid value");
}
else {
printf("Summation of %d is %d", n, summation(n));
}
}
}
break;
As the control will fall down to next case if no break statement is present.

Using arrays in c to find repeated digits in an number (C)

I need to make a program that checks to see if an entered value has any repeated digits. The user is asked to enter numbers until the entered value is 0. If there are any repeated digits, it displays "repeated digits" and then asks the user to enter another value. If there are no repeated digits, it displays "no repeated digits" and asks the user to enter another number. So far, this is what i have. It terminates the program when 0 is entered, but it always displays "no repeated digits" even if there are some.
#include <stdbool.h>
#include <stdio.h>
int main(void)
{
bool digit_seen[10] = {false};
int digit;
long int n = 0;
printf("Enter a number: ");
scanf("%ld", &n);
while(n >= 0){
if(n==0)
break;
while (n > 0){
digit = n % 10;
if (digit_seen[digit]){
digit_seen[digit] = true;
break;
}
n /= 10;
}
if (n > 0)
printf("Repeated digit: %d\n", digit);
else
printf("No repeated digit\n");
scanf("%ld", &n);
}
return 0;
}
A couple of things:
1: A bool only has two states: true and false. If you trying to build a frequency counter of each digit seen, for the presence of a digit more than once, then you should use a data type that can count to at least two, like a char or short or int, or your own enum.
2: This code:
if (digit_seen[digit]){
digit_seen[digit] = true;
break;
}
Is never going to be evaluated as true since you initialized digit_seen to be false at the start of your main function. What you should be doing is something like this:
#include <stdio.h>
int main(int argc, char *argv[])
{
int digit_seen[10] = {0};
int entry;
int i, flag = 0;
printf("Enter a number: ");
scanf("%ld", &entry);
while(entry > 0)
{
int digit = (entry%10);
digit_seen[digit]++;
if(digit_seen[digit]>=2)
{
printf("Repeated digit: %d\n", digit);
}
entry /= 10;
}
for(i = 0; i < 10; i++)
{
if(digit_seen[i]>1) flag=1;
}
if(!flag)
{
printf("No repeated digits\n");
}
return 0;
}
#include <stdio.h>
int main() {
int seen [10] ={0}; // we set every element for a number is just 0
int N,rem;
printf("Enter the number:");
scanf("%d", &N);
while(N>0){
rem = N%10;
seen[rem]+=1;
N = N/10;
}
int i;
for(i=0;i<10;i++){ // checking the number seen counts
if(seen[i]==0){
continue;
}
printf("%d seen %d times\n",i,seen[i]); // just returned the given numbers informations
}
return 0;
}

count digit until you get number of digits you want

I'm new to coding. I'm now learning C programing. I'm having a problem with counting digits. My objective is to only accept a fixed number of digits in the input. For example I want user to input only 7 digits number, so when they input anything else than a 7 digits number, the program should ask them to input again until it gets 7 digits number. Here is my attempt:
int n, count = 0;
printf("Please enter number:");
scanf("%d", &n);
printf("\n");
while (n != 0)
{
n /= 10;
count++;
}
printf("%d", count);
if (count != 7)
{
printf("You can use only 7 digits numbers");
}
You can try this one:
#include <stdio.h>
#include <string.h>
int main()
{
char s[1000]; //Enter the maximum number of digits you expect as array size
printf("Please enter number: ");
scanf("%s", s);
while(strlen(s)!=7)
{
printf("%d\n", strlen(s));
printf("You can use only 7 digits numbers\n");
scanf("%s", s);
}
return 0;
}
After taking the input, you can easily convert it to int if you need to.
You can try this by creating a small function to check the number of digits in the number entered for you:
#include <stdio.h>
int count_digit(int n){
int count = 0;
if(n == 0) return 1;
while(n != 0)
{
n /= 10;
++count;
}
return count;
}
int main(void) {
int num;
printf("Please enter number:");
scanf("%d", &num);
while (count_digit(num) != 7){
printf("Please enter only 7digits number:\n ");
scanf("%d", &num);
}
printf("The 7digit number you entered is: %d",num);
return 0;
}

Two player guessing game in C programming

I have a two player guess random number game; player number (1 0r 2) with turn is randomly generated as the game begins and it's prompted to enter the player number. If the player number entered does not match the random player number then it should print "You have to wait your turn" and return to the enter Player number prompt. My program goes directly to the randome number that is to be guessed by the player instead of going back to asking for player number first and then moving onto asking for entering the random number that's to be guessed by player with his/her turn. How do I get it to go back to asking for the correct player number before moving forward.
Also one correct player number is entered; each player can choose to pass by entering "PASS" twice consecutively and thrice throughout the life of the game. How do I make these conditions work in the game. Thanks in advance to all.
Here is the code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <malloc.h>
int main(void) {
int player_num = 0; int number = 0; int player_input = 0;
int guess = 0; char input; char str[6] = {0}; int Player_1 = 1;
int Player_2 = 2; int Pass_1 = 3; int Pass_2 = 3; int i = 1;
int player_turn = 0; int turn = 0;
srand(time(NULL)); player_num = 1 + rand() % 2; /* Random number is generated */
srand(time(NULL)); number = 0 + rand() % 100; /* Random number is generated */
while(number != guess) {
printf("\nIt's player's %d turn\n", player_num);
printf("Player Number?\n");
scanf("%d", &player_input);
while (player_num != player_input) {
printf("You Have to wait your turn.\nPlayer number?\n");
}
if (Player_1 != player_num)
Player_2 = player_num;
if (i%2 == 1) {
player_num = Player_1;
} else {
player_num = Player_2;
}
i = i+1;
printf("Enter Your Guess, 0 - 100 or Pass: ");
scanf("%s", str);
if (strcmp(str, "pass") == 0){
if (player_num == Player_1){
Pass_2 = Pass_2 -1;
printf("Player 2 has %d more 'Pass' left!\n", Pass_2);
}
else {
Pass_1 = Pass_1 -1;
printf("Player 1 has %d more 'Pass' left!\n", Pass_1);
}
} else {
guess = atoi(str);
if(guess < number) /* if the guess is lower, output: the guess is too low */
printf("Your guess was to low.\n ");
else if(guess > number) /* if the guess is higher, output: the guess is too high */
printf("Your guess was to high.\n ");
else /* if the guess is equal to the random number: Success!! */
printf("Yes!! you got it!\n");
}
}
return 0;
}
First, srand needs to be invoked only once and at the start of the program.
Second, scanf was moved inside the second while loop to force user to enter the correct player number or keep asking until he/she gets it right.
The following code fixes all of the above. Please read the comments in the code to see the reasons for the changes:
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
#include <malloc.h>
int main(void) {
int player_num = 0; int number = 0; int player_input = 0;
int guess = 0; char input; char str[15] = {0}; // size was increased to compensate for pass pass input
int Player_1 = 1;
int Player_2 = 2; int Pass_1 = 3; int Pass_2 = 3; int i = 1;
int player_turn = 0; int turn = 0; int alternate=0;
int player1Flag=0,player2Flag=0;
int lastPlayer=0;
srand(time(NULL));
player_num = 1 + rand() % 2; /* Random number is generated */
lastPlayer = player_num;
number = 0 + rand() % 100; /* Random number is generated */
while(number != guess) {
while (player_num != player_input) {
printf("\nIt's player's %d turn\n", player_num);
printf("Player Number?\n");
scanf("%d", &player_input);
getchar();// to get rid of \n after the input
if(player_input!=player_num){
printf("You Have to wait your turn.\n");
}
}
if (Player_1 != player_num) Player_2 = player_num;
printf("Enter Your Guess, 0 - 100 or Pass: ");
scanf("%s",str);
if (strcmp(str, "pass") == 0){
if (player_num == Player_1){
player1Flag = player1Flag+1; // flag to detect if last input was a pass
if(player1Flag>1){
printf("Dude you passed in your last attempt .. dont be a pus*y\nEnter a guess : ");
scanf("%s",&str);
guess = atoi(str);
if(guess < number){ /* if the guess is lower, output: the guess is too low */
printf("Your guess was to low.\n ");
}else if(guess > number){ /* if the guess is higher, output: the guess is too high */
printf("Your guess was to high.\n ");
}else{ /* if the guess is equal to the random number: Success!! */
printf("Yes!! you got it!\n");
}
player1Flag = 0; // reset the pass flag = 1 as this pass isn't counted
}else{
Pass_2 = Pass_2 -1;
if(Pass_2<0){
printf("You have already passed Thrice\nEnter a guess: ");
scanf("%s",&str);
guess = atoi(str);
if(guess < number){ /* if the guess is lower, output: the guess is too low */
printf("Your guess was to low.\n ");
}else if(guess > number){ /* if the guess is higher, output: the guess is too high */
printf("Your guess was to high.\n ");
}else{ /* if the guess is equal to the random number: Success!! */
printf("Yes!! you got it!\n");
}
}else{
printf("Player 1 has %d more 'Pass' left!\n", Pass_2);
}
}
}
else{
player2Flag = player2Flag + 1;
if(player2Flag>1){
printf("Dude you passed in your last attempt .. dont be a pus*y\nEnter a guess : ");
scanf("%s",&str);
guess = atoi(str);
if(guess < number){ /* if the guess is lower, output: the guess is too low */
printf("Your guess was to low.\n ");
}else if(guess > number){ /* if the guess is higher, output: the guess is too high */
printf("Your guess was to high.\n ");
}else{ /* if the guess is equal to the random number: Success!! */
printf("Yes!! you got it!\n");
}
player2Flag=0;// reset the player2Flag = 1 as this pass isn't counted
}else{
Pass_1 = Pass_1 -1;
if(Pass_2<0){
printf("You have already passed Thrice\nEnter a guess: ");
scanf("%s",&str);
guess = atoi(str);
if(guess < number){ /* if the guess is lower, output: the guess is too low */
printf("Your guess was to low.\n ");
}else if(guess > number){ /* if the guess is higher, output: the guess is too high */
printf("Your guess was to high.\n ");
}else{ /* if the guess is equal to the random number: Success!! */
printf("Yes!! you got it!\n");
}
}else{
printf("Player 2 has %d more 'Pass' left!\n", Pass_2);
}
}
}
}else {
if (player_num == Player_1){
player1Flag = 0;//reset pass flag as this player enetered a guess
}else{
player2Flag = 0;
}
guess = atoi(str);
if(guess < number){ /* if the guess is lower, output: the guess is too low */
printf("Your guess was to low.\n ");
}else if(guess > number){ /* if the guess is higher, output: the guess is too high */
printf("Your guess was to high.\n ");
}else{ /* if the guess is equal to the random number: Success!! */
printf("Yes!! you got it!\n");
}
}
if(lastPlayer==1){
player_num = 2;
lastPlayer = 2;
}else if(lastPlayer==2){
player_num = 1;
lastPlayer = 1;
}
}
return 0;
}
You need to add an input within your while. In other words, instead of:
while (player_num != player_input) {
printf("You Have to wait your turn.\nPlayer number?\n");
}
try this:
while (player_num != player_input) {
printf("You Have to wait your turn.\nPlayer number?\n");
scanf("%d", &player_input);
}

How to use a loop function with user input in C?

Here is the average program I created.
#include <stdio.h>
#include <stdlib.h>
int main()
{
float f1,f2,f3;
/* Program to calculate averages. */
/*Asks for the numbers.*/
printf(" Please enter three numbers.\n");
printf ("\t" "First number please.\n");
scanf("%f", &f1);
printf ("\t" "Second number please.\n");
scanf ("%f", &f2);
printf("\t" "Third number please.\n");
scanf("%f", &f3);
/* Now it averages it.*/
printf(" Thank you, wait one.\n");
printf(" Excellent, your sum is.\n");
printf("%f""\n", f1+f2+f3);
printf("Your average of the sum is now!!!!\n");
printf("%f", (f1+f2+f3)/3);
return 0;
}
Now would I turn this into a do-while? Or an if else?
If you want to repeat the whole entry and averaging process, you can wrap a loop around the code:
#include <stdio.h>
int main(void)
{
float f1,f2,f3;
while (1)
{
printf("Please enter three numbers.\n");
printf("\tFirst number please.\n");
if (scanf("%f", &f1) != 1)
break;
printf("\tSecond number please.\n");
if (scanf("%f", &f2) != 1)
break;
printf("\tThird number please.\n");
if (scanf("%f", &f3) != 1)
break;
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
}
return 0;
}
Note that this code checks the return value from scanf() each time it is used, breaking the loop if there's a problem. There's no need for string concatenation, and a single printf() can certainly print a string and a value.
That's a simple first stage; there are more elaborate techniques that could be used. For example, you could create a function to prompt for and read the number:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
int main(void)
{
float f1,f2,f3;
while (printf("Please enter three numbers.\n") > 0 &&
prompt_and_read("\tFirst number please.\n", &f1) == 0 &&
prompt_and_read("\tSecond number please.\n", &f2) == 0 &&
prompt_and_read("\tThird number please.\n", &f3) == 0)
{
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
}
return 0;
}
If you want to get away from a fixed set of three values, then you can iterate until you encounter EOF or an error:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
int main(void)
{
float value;
float sum = 0.0;
int num = 0;
printf("Please enter numbers.\n");
while (prompt_and_read("\tNext number please.\n", &value) == 0)
{
sum += value;
num++;
}
if (num > 0)
{
printf("You entered %d numbers\n", num);
printf("Your sum is %f\n", sum);
printf("Your average is %f\n", sum / num);
}
return 0;
}
You might also decide to replace the newline at the ends of the prompt strings with a space so that the value is typed on the same line as the prompt.
If you want to check whether to repeat the calculation, you can use a minor variant on the first or second versions of the code:
#include <stdio.h>
static int prompt_and_read(const char *prompt, float *value)
{
printf("%s", prompt);
if (scanf("%f", value) != 1)
return -1;
return 0;
}
static int prompt_continue(const char *prompt)
{
printf("%s", prompt);
char answer[2];
if (scanf("%1s", answer) != 1)
return 0;
if (answer[0] == 'y' || answer[0] == 'Y')
{
int c;
while ((c = getchar()) != EOF && c != '\n') // Gobble to newline
;
return 1;
}
return 0;
}
int main(void)
{
float f1,f2,f3;
while (printf("Please enter three numbers.\n") > 0 &&
prompt_and_read("\tFirst number please.\n", &f1) == 0 &&
prompt_and_read("\tSecond number please.\n", &f2) == 0 &&
prompt_and_read("\tThird number please.\n", &f3) == 0)
{
printf("Your sum is %f\n", f1+f2+f3);
printf("Your average is %f\n", (f1+f2+f3)/3);
if (prompt_continue("Do you want to try again?") == 0)
break;
}
return 0;
}
You can do this:
int main()
{
float number, sum=0.0f;
int index=0;
do
{
printf ("\t" "Enter number please.\n"); //Asking for a number from user
scanf("%f", &number); //Getting a number from a user
sum+=number; //Add number entered to the sum
i++;
} while (i < 3);
printf("Excellent, your average is %f\n", sum/3);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
float f1,f2,f3;
char c='Y';
/* Program to calculate averages. */
/*Asks for the numbers.*/
do
{
printf(" Please enter three numbers.\n");
printf ("\t" "First number please.\n");
scanf("%f", &f1);
printf ("\t" "Second number please.\n");
scanf ("%f", &f2);
printf("\t" "Third number please.\n");
scanf("%f", &f3);
/* Now it averages it.*/
printf(" Thank you, wait one.\n");
printf(" Excellent, your sum is.\n");
printf("%f""\n", f1+f2+f3);
printf("Your average of the sum is now!!!!\n");
printf("%f", (f1+f2+f3)/3);
printf ("Do you wana continue [Y/N]...\n");
scanf("%c", &c);
}while(c!='N'&&c!='n');
return 0;
}

Resources