Hello I am new to C and trying to make a program that asks for the user to input a whole bunch of numbers. I want to loop scanf so that it keeps asking and when the user inputs "0", it stops, reads off the even and odd numbers inputted, and counts them seperatly. Right now I have it to keep asking for new numbers after user presses "Enter" but when i type "0" is just keeps asking for more numbers and doesn't stop. What am I doing wrong? Like I said before, I am very new so baby words are best.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void) {
int number_of_integers, sum = 0, i, integer;
char user_name[128];
printf("What is your name?\n");
scanf("%s", user_name);
printf("\nEnter any real numbers followed by ENTER.\n");
while (integer != 0) {
scanf("%s", &integer);
if (integer == 0)
break;
}
printf("%s, the numbers you entered are broken down as follows:\n", user_name);
return 0;
}
As a commenter indicated, we aren't a homework or tutoring service, but I'm doing you a favor by producing an actual working example that I just made up. It's up to you now to tailor it exactly to your needs.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void) {
int max=100;
int integer;
int even[max];
int odd[max];
int index=0;
int evencount=0;
int oddcount=0;
char user_name[128];
printf("What is your name?\n");
scanf("%s", user_name);
printf("\nEnter any real numbers followed by ENTER.\n");
while (index < max){
scanf("%d", &integer);
if (integer == 0)
break;
if ((integer % 2) == 0){
evencount++;
even[evencount]=integer;
}else{
oddcount++;
odd[oddcount]=integer;
}
index++;
}
printf("%s, the %d numbers you entered are broken down as follows:\n", user_name,index);
printf("%d odd integer(s):\n",oddcount);
while (oddcount > 0){
printf("%d\n",odd[oddcount]);
oddcount--;
}
printf("%d even integer(s):\n",evencount);
while (evencount > 0){
printf("%d\n",even[evencount]);
evencount--;
}
return 0;
}
Related
This question already has answers here:
How do I properly compare strings in C?
(10 answers)
Closed 4 months ago.
I'm trying to build a word guesser where you guess a word from the given choice. The words are stored in an array. The player is losing even though they must win.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void guess(int N) {
int number, guess, numberofguess = 0;
int myval[] = {"R22", "B3", "R33", "B232", "R12",
"B45", "R2", "B12", "R45", "B32"};
srand(time(NULL));
number = rand() % N;
printf("choose a number "
"{'R22','B3','R33','B232','R12','B45','R2','B12','R45','B32'}\n");
char str[20];
gets(str);
printf("your guess is %s\n", str);
if (str == myval[number]) {
printf("you win\n");
} else
printf("you lose\n");
printf("the number is %s", myval[number]);
}
main() {
int N = 9;
guess(N);
return 0;
}
I want to make the code in such a way when the player enters the code and it matches with the random output the if statement works.
Use strcmp while comparing the strings in C.
When creating an array from strings, you should create it as char*.
Using gets is not good practice
You should specify the return type of all functions, including main(), which should return an int.
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
void guess(int N) {
int number, guess, numberofguess = 0;
const char* myval[] = {"R22", "B3", "R33", "B232", "R12",
"B45", "R2", "B12", "R45", "B32"};
srand(time(NULL));
number = rand() % N;
printf("choose a number "
"{'R22','B3','R33','B232','R12','B45','R2','B12','R45','B32'}\n");
char str[20];
gets(str);
printf("your guess is %s\n", str);
if (strcmp(str,myval[number]) == 0) {
printf("you win\n");
} else
printf("you lose\n");
printf("the number is %s", myval[number]);
}
int main() {
int N = 9;
guess(N);
return 0;
}
#include <stdio.h>
int main(int argc, char** argv)
{
int n;
int numbers;
int i=0;
int sum=0;
double average;
printf("\nPlease Enter the elements one by one\n");
while(i<n)
{
scanf("%d",&numbers);
sum = sum +numbers;
i++;
}
average = sum/n;
printf("\nSum of the %d Numbers = %d",n, sum);
printf("\nAverage of the %d Numbers = %.2f",n, average);
return 0;
}
i get the output "exited, floating point exception"
im not sure how to fix it.
i found online to add before the while loop
printf("\nPlease Enter How many Number you want?\n");
scanf("%d",&n);
but i dont want that there
Hint: you want the user to be able to signal to your application that they finished entering the elements. So you'd start with n=0 and then increment it each time the user provides a new element, and exit the loop when the user does "something" that you can detect.
For starters, let's say that the user closes the input by pressing Ctrl-Z on Windows, or Ctrl-D on Unix. The input will fail with EOF then - scanf() won't return 1 anymore. So you can check for this:
#include <stdio.h>
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf("%d", &number);
if (result == 1) break;
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
But this also ends the input when anything non-numeric is entered. Due to how scanf() is designed, you need to do something else to skip invalid input - usually by consuming input character-by-character until an end of line is reached. Thus, the variant that would not stop with invalid input, but allow the user another chance, needs to differentiate between scanf() returning EOF vs it returning 0 (invalid input):
#include <stdio.h>
void skip_input_till_next_line(void)
{
for (;;) {
char c;
if (scanf("%c", &c) != 1) break;
if (c == '\n') break;
}
}
int main(int argc, char** argv)
{
int n = 0;
int sum = 0;
printf("\nPlease Enter the elements one by one. ");
#ifdef _WIN32
printf("Press Ctrl-Z to finish.\n");
#else
printf("Press Ctrl-D to finish.\n");
#endif
for (;;)
{
int number;
int result = scanf(" %d", &number);
if (result == EOF) break;
if (result != 1) {
// We've got something that is not a number
fprintf(stderr, "Invalid input. Please try again.\n");
skip_input_till_next_line();
continue;
}
sum = sum + number;
n ++;
}
double average = (double)sum / n;
printf("\nSum of %d number(s) = %d\n",n, sum);
printf("Average of %d number(s) = %.2f\n",n, average);
return 0;
}
As a learner I'd recommend you to think about the pseudo code rather than the actual code.
Answers above are really good. I just want to add few things:
As a programmer you've to teach the hardware what you want it to do. Think:
Have you told your program how many numbers it takes as input? Is it limited or unlimited?
How will your program knows when to stop taking inputs?
I hope you agree that (sum n)/n would throw an error if user
doesn't enter anything or only enters 0?
What will happen if User enters characters instead?
Another important thing is that you need to clearly specify why you don't want to do certain thing in your code? This might help us understand better what are the limitations.
If you think about these things before and ask questions you'll learn better. Community is here to help you.
I've trying to do it for about an hour, but I can't seem to get it right. How is it done?
The code I have at the moment is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
The original specification (before code was added) was a little vague but, in terms of the process to follow, that's irrelevant. Let's assume they're as follows:
get two numbers from the user.
if their product is greater than a thousand, print it and stop.
otherwise, print product and go back to first bullet point.
(if that's not quite what you're after, the process is still the same, you just have to adjust the individual steps).
Translating that in to pseudo-code is often a first good step when developing. That would give you something like:
def program:
set product to -1
while product <= 1000:
print prompt asking for numbers
get num1 and num2 from user
set product to num1 * num2
print product
print "target reached"
From that point, it's a matter of converting the pseudo-code into a formal computer language, which is generally close to a one-to-one mapping operation.
A good first attempt would be along the lines of:
#include <stdio.h>
int main (void) {
int num1, num2, product = -1;
while (product < 1000) {
printf ("Please enter two whole numbers, separated by a space: ");
scanf ("%d %d", &num1, &num2);
product = num1 * num2;
printf ("Product is %d\n", product);
}
puts ("Target reached");
return 0;
}
although there will no doubt be problems with this since it doesn't robustly handle invalid input. However, at the level you're operating, it would be a good start.
In terms of the code you've supplied (which probably should have been in the original question, though I've added it now):
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
int j=-1;
while(j<0){
printf("Enter a number: \n");
scanf("%d", &j);
}
int i=j;
for(i=j; i<=100; i++){
printf("%d \n", i);
}
return 0;
}
a better way to do the final loop would be along the lines of:
int i = 1;
while (i < 1000) {
i = i * j;
printf ("%n\n", i);
}
This uses the correct terminating condition of the multiplied number being a thousand or more rather than what you had, a fixed number of multiplications.
You may also want to catch the possibility that the user enters one, which would result in an infinite loop.
A (relatively) professional program to do this would be similar to:
#include <stdio.h>
int main (void) {
// Get starting point, two or more.
int start = 0;
while (start < 2) {
printf("Enter a number greater than one: ");
if (scanf("%d", &start) != 1) {
// No integer available, clear to end of input line.
for (int ch = 0; ch != '\n'; ch = getchar());
}
}
// Start with one, continue while less than a thousand.
int curr = 1;
while (curr < 1000) {
// Multiply then print.
curr *= start;
printf ("%d\n", curr);
}
return 0;
}
This has the following features:
more suitable variable names.
detection and repair of most invalid input.
comments.
That code is included just as an educational example showing how to do a reasonably good job. If you use it as-is for your classwork, don't be surprised if your educators fail you for plagiarism. I'm pretty certain most of them would be using web-search tools to detect that sort of stuff.
I'm not 100% clear on what you are asking for so I'm assuming the following that you want to get user to keep on entering numbers (I've assumed positive integers) until the all of them multiplied together is greater than or equal to 1000).
The code here starts with the value 1 (because starting with 0 will mean it will never get to anything other than 0) and multiples positive integers to it while the product of all of them remains under 1000. Finally it prints the total (which may be over 1000) and also the number of values entered by the user.
I hope this helps.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char input[10];
unsigned currentTotal = 1;
unsigned value;
unsigned numEntered = 0;
while( currentTotal < 1000 )
{
printf( "Enter a number: \n" );
fgets( input, sizeof(input), stdin );
value = atoi( input );
if( value > 0 )
{
currentTotal *= value;
numEntered += 1;
}
else
{
printf( "Please enter a positive integer value\n" );
}
}
printf( "You entered %u numbers which when multiplied together equal %u\n", numEntered, currentTotal );
return 0;
}
Try this one:
#include <stdio.h>
int main()
{
int input,output=1;
while(1)
{
scanf("%d",&input);
if(input<=0)
printf("Please enter a positive integer not less than 1 :\n");
else if(input>0)
output*=input;
if(output>1000)
{
printf("\nThe result is: %d",output);
break;
}
}
return 0;
}
Hi I'm just starting programming in C and am struggling to write a program designed to take a string of integers and then output if the value being checked is smaller than the one before it. But I cannot get the program to repeat over the data and it seems to only be checking the first value. I have tried using loops but this further confused me. Sorry to ask such a basic question. Here is my code so far:
#include <stdio.h>
#include <stdlib.h>
int
main(int argc, char *argv[]) {
int num;
int smaller=0;
printf("Input integers: ");
scanf("%d", &num);
if (num<smaller) {
printf("*** value %d is smaller than %d \n", num, smaller);
}
smaller=num;
return 0;
}
You could use a do-while loop to ask the user for values over and over again until they type something invalid, like 0:
int smaller=0;
int num=0;
do {
printf("Input an integer (0 to stop): ");
scanf("%d", &num);
if (num<smaller) {
printf("*** value %d is smaller than %d \n", num, smaller);
}
smaller=num;
} while (num != 0);
This is a program that gets numbers input. From the numbers given or inputted, store in an array those numbers only that are even. Input will stop/terminates once 5 even numbers are already stored in the array. So here's my code:
#include <stdio.h>
#include <conio.h>
int main()
{
int num[5];
int x, counter, even[5], numEven=0;
for(counter=0; counter<5; counter++){ //loop for getting the numbers from the user
printf("Enter number: ");
scanf("%d", &num[counter]);
if(num[counter]%2==0){ //storing the even numbers
even[numEven] = num[counter];
numEven++;
}
}
printf("\n\nEven numbers: "); //printing even numbers
for(counter=0; counter<numEven; counter++){
printf("%d, ", even[counter]);
}
getch();
return 0;
}
I have confusion in the part where will I stop the inputting when there's already 5 even numbers stored. Is there something missing? Or am I doing the wrong way? I hope I can get help and suggestions with the code. Thank you very much.
#include <stdio.h>
#include <conio.h>
int main()
{
int x, even[5], numEven = 0;
while (numEven < 5)
{
scanf("%d", &x);
if (x % 2 == 0)
{
even[numEven++] = x;
}
}
printf("\n\nEven numbers: "); //printing even numbers
for(x=0; x<numEven; x++)
{
printf("%d, ", even[x]);
}
getch();
return 0;
}
You keep readin inputs till numEven reaches 5. If the read input is an even number store it in the array and increment numEven.
Use a while loop if the number of times the program will ask the user for input is not fixed and dependent on the user's input.
while (numEven < 5) {
printf("Enter number: ");
scanf("%d", &num[counter]);
if (num[counter] % 2 == 0) {
even[numEven] = num[counter];
numEven++;
}
}