How to use a loop function with user input in C? - 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;
}

Related

User Input of Integers Infinite Loop Until User Inputs a Character (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;
}

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;
}

Program is terminating without recognizing scanf

I don't know why my program terminates before confirmStats(); is called. I included everything related in main() in case the issue is ocurring somewhere else in my program.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int str, intel, charis;
int totalPts =5;
/* Returns a number.
User must input an integer.
*/
int getNumber(int number){
while(scanf("%d", &number) != 1){
printf("You did not enter a valid number\n");
scanf("%*s");
}
return number;
}
/* Individual stat points */
int stat(int number){
number = getNumber(number);
while(number > totalPts){
printf("You only have %d stat points left\n", totalPts);
printf("Enter a number less than or equal to %d:\t", totalPts);
number = getNumber(number);
}
totalPts -= number;
printf("Points remaining:\t%d\n", totalPts);
return number;
}
/* Player stat points */
void getStats(){
printf("You're alotted %d stat points to spend in Strength, Intellect, and Charisma\n", totalPts);
printf("Intellect:\t");
intel = stat(intel);
printf("Strength:\t");
str = stat(str);
printf("Charisma:\t");
charis = stat(charis);
printf("\nIntellect: %d\t Strength: %d\t Charisma: %d\n", intel, str, charis);
}
void confirmStats(){
char ans;
scanf("%c", &ans);
while(ans == 'n'){
str = 0;
intel = 0;
charis = 0;
getStats();
printf("Are these correct?:\ty/n: ");
scanf("%c", &ans);
}
}
void main(){
printf("\nSafe choice...");
printf("\n");
printf("Alright, how old are you?\n");
// int age, str, intel, charis;
int age;
// int totalPts = 5;
age = getNumber(age);
getStats();
printf("Are these correct? ");
printf("\n");
printf("y/n:\t");
printf("\n");
confirmStats();
}
The problem is that scanf("%c", &ans); scans the newline character left over by the previous scanf.
The fix is easy. Simply add a space before %c in the two scanfs in confirmStats. The space is a whitespace character and a whitespace character in the format string of scanf tells scanf to scan any number of whitespace characters, if any, until the first non-whitespace character.
Improved code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int str, intel, charis;
int totalPts = 5;
/*
Returns a number.
User must input an integer.
*/
int getNumber(){
int number;
while(scanf("%d", &number) != 1){
printf("You did not enter a valid number\n");
scanf("%*s");
}
return number;
}
/* Individual stat points */
int stat(){
int number;
number = getNumber();
while(number > totalPts){
printf("You only have %d stat points left\n", totalPts);
printf("Enter a number less than or equal to %d:\t", totalPts);
number = getNumber();
}
totalPts -= number;
printf("Points remaining:\t%d\n", totalPts);
return number;
}
/* Player stat points */
void getStats(){
printf("You're alotted %d stat points to spend in Strength, Intellect, and Charisma\n", totalPts);
printf("Intellect:\t");
intel = stat();
printf("Strength:\t");
str = stat();
printf("Charisma:\t");
charis = stat();
printf("\nIntellect: %d\t Strength: %d\t Charisma: %d\n", intel, str, charis);
}
void confirmStats(){
char ans;
scanf(" %c", &ans);
while(ans == 'n'){
str = 0;
intel = 0;
charis = 0;
getStats();
printf("Are these correct?:\ty/n: ");
scanf(" %c", &ans);
}
}
int main(void){
printf("\nSafe choice...");
printf("\n");
printf("Alright, how old are you?\n");
age = getNumber();
getStats();
printf("Are these correct? ");
printf("\n");
printf("y/n:\t");
printf("\n");
confirmStats();
return 0;
}
int getNumber(int number){
int ok = 0;
while (!ok){
if(scanf("%d", &number) != 1){
printf("You did not enter a valid number\n");
while(getchar()!='\n');
}
else {
getchar();
ok=1;
}
}
return number;
}
Sir ,do u have checked the syntax is scant("%d",&variable);
Not. scant("%d",variable);

How to read multiple integers from a single line?

Input is some integers separeted by spaces in one line, like this:
enter numbers: 12 41 2
program should get each integers and show the sum:
sum: 55
how can i do that?
edit:I tried this but it is unable to detect enter key. It should stop and show sum when enter is pressed.
printf("\nEnter numbers: ");
int sum =0;
int temp;
while( scanf("%d",&temp))
{
sum+=temp;
}
printf("Sum: %d",sum);
#include <stdio.h>
int main(){
printf("\nEnter numbers: ");
int sum =0, temp;
char ch;
while(2 == scanf("%d%c", &temp, &ch)){
sum+=temp;
if(ch == '\n')
break;
else if(ch != ' '){
fprintf(stderr, "Invalid input.\n");
return -1;
}
}
printf("Sum: %d\n", sum);
return 0;
}
#include <stdio.h>
int main(void){
char line[128], *p=line;
int sum = 0, len, n;
printf("enter numbers: ");
scanf("%127[^\n]", line);
while (sscanf(p, "%d%n", &n, &len)==1){
sum += n;
p += len;
}
printf("sum: %d\n", sum);
return 0;
}

Why this function is giving unexpected result?

I was trying to co
So, I don't understand the reason why my compiler is not letting me take input when the convhex() is called from the main. It's directly printing some result.. I don't understand this.
Here's the code..
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <String.h>
void convhex();
void convert(int no, int base);
int checkValid(int base,int no);
// function prototyping done here
void convhex()
{
char ch[10];
int dec=0;
int i, res;
printf("Enter the hexadecimal number \n");
scanf("%[^\n]", ch);
// print in decimal
for(i=strlen(ch)-1;i>=0;i--)
{
if(ch[i]>65)
res=ch[i]-65+10;
else
res=ch[i]-48;
//printf("%d", res);
dec=dec+pow(16,strlen(ch)-(i+1))*res;
}
printf("\nThe number in decimal is %d \n", dec);
}
int checkValid(int base,int no)
{
int rem;
//flag;
// flag=0;
while(no>0)
{
rem=no%10;
if(rem>base)
{
//flag=1;
//break;
return 0;
}
no/=10;
}
return 1;
/*
if(flag==1)
printf("Invalid Input");
else
printf("Valid Input");
*/
}
void convert(int no, int base)
{
int temp, mod, sum=0, i=0;
temp=no;
while(temp>0)
{
mod=temp%10;
temp=temp/10;
sum=sum+pow(base,i)*mod;
i++;
}
printf("\n The number in base 10 is %d", sum);
}
int main()
{
int base, no;
printf("Enter the base \n");
scanf("%d", &base);
if(base==16)
convhex();
else
{
printf("Enter the number \n");
scanf("%d", &no);
printf("You have entered %d", no);
if(checkValid(base, no))
convert(no, base);
}
return 0;
}
// up until now our program can work with any base from 0-10 but not hexadecimal
// in case of hex, we have A-F
scanf in convhex is reading the \n left by the scanf in main.
Try this
scanf(" %[^\n]", ch);
^ An extra space will eat any number of white-spaces.
you can just remove the %[^\n] from scanf in connhex to change it to:
scanf("%s", ch)
or you could do what haccks suggested in the above post.

Resources