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);
Related
#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'm using scanf to read in an int, however, I to make create an error if someone puts something other than an int. I have noticed that if I input a character for scanf("%d",%number);, it saves it as 0. I would like 0 to be an option. How do i avoid this issues?
the test code would be
int number;
scanf("%d",&number);
printf("%d",number);
Try this method to see if the entered input was a number %d:
#include <stdio.h>
int main(void) {
int number;
if (scanf("%d", &number))
printf("A number!\n");
else
printf("Not a number!\n");
return 0;
}
i've been trying to do a program that counts till the number that the user inputs (f,ex: 10) with recursion.
If the user inputs 10, the program will have to print out: 1,2,3,4,5,6,7,8,9,10.
I'm getting a [1] 49348 segmentation fault ./recs.exe and i wanted to know why am i getting it to prevent it in the future.
Here is my code:
#include <stdio.h>
int numbers(int n);
int main(int argc, char const *argv[]) {
int number;
int i;
printf("Put a number and the program will do everything for ya.\n");
printf("Number: ");
scanf("%d", &number);
for(i=0;i<=number;i++){
printf("%d, ", numbers(i));
}
}
int numbers(int n){
if(n==0||n==1){
return n;
} else {
return(numbers(n+1)); // I think the problem is here.
}
}
Hope you guys can explain my error and help me understand why it's happening to me to help me avoid this silly mistake. Thanks :)
You have a few issues in your algorithm.
the for loop calls the numbers program multiple times, starting the recursion multiple times. You need to start it only once, right?
you calling recursion with n+1, actually making every next invocation with an incremental value, which could be incremented indefinitely. Your recursion has no exit and will die with some out of memory or a crash.
To solve the first issue, just instantiate it once.
To print it correctly, you need to have the print statement withing the recursion.
For the second issue, you can do different approaches. The following is the easiest to understand and it passes max as a second argument.
void numbers(int n, int max) {
printf(%d ", n);
if (n >= max)
return;
numbers (n + 1, max);
}
int main() {
...
numbers(1, number);
}
a more efficient way is having a single argument and count it down to 0. But you have to be careful on when you want to print. In your case, if you need increment order of values, you have to make sure that the print happens after you return from recursion.
Here is the program which implements the second method:
#include <stdio.h>
void numbers(int n);
int main(int argc, char const *argv[]) {
int number;
int i;
printf("Put a number and the program will do everything for ya.\n");
printf("Number: ");
scanf("%d", &number);
// start recursion.
numbers(number);
printf("\n");
}
void numbers(int n){
if (n == 0)
return;
numbers(n-1);
// after return from recursion
printf("%d ", n);
}
Your recursion never end if you send a number >= 2, for exemple, if i send 2 to your numbers function, the next call step is 3, the next one is 4, 5, 6 ect....
The correct code is :
int main(int argc, char const *argv[]) {
int number;
int i;
printf("Put a number and the program will do everything for ya.\n");
printf("Number: ");
scanf("%d", &number);
for(i=0;i<=number;i++){
printf("%d, ", i);
}
if you want to do recursion, you can do a countdown, that lends more to the recursion
int main(int argc, char const *argv[]) {
int number;
printf("Put a number and the program will do everything for ya.\n");
printf("Number: ");
scanf("%d", &number);
numbers(number);
}
void numbers(int n)
{
printf("%d, ", n);
if (n > 0)
numbers(n - 1);
}
As discussed in the comments, your implementation will not stop counting because it has no idea what the target value is. For example, if the user enters '2', the code would run numbers(0), which would return 0, then numbers(1) which would return 1, then numbers(2) which would call numbers(3) and so on, until the stack ran out of space.
The following should work according to my understanding of the problem.
void count(int from, int to)
{
printf( "%d", from );
if( from < to )
{
printf( ", ");
count( from+1, to );
}
}
int main(int argc, char const *argv[])
{
int number;
printf("Put a number and the program will do everything for ya.\n");
printf("Number: ");
scanf("%d", &number);
count(1,number);
}
I've moved the printing into the recursive function because it makes it easier to output each number (and intelligently print the comma that comes between numbers), and it didn't make sense to me to use a recursive function and a for loop to count.
The function simply prints out the current value and then checks to see if it has reached its goal. If not, it recursively counts to the next number.
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;
}
I know that I can use
scanf("%d %d %d",&a,&b,&c):
But what if the user first determines how many input there'd be in the line?
You are reading the number of inputs and then repeatedly (in a loop) read each input, eg:
#include <stdio.h>
#include <stdlib.h>
int main(int ac, char **av)
{
int numInputs;
int *input;
printf("Total number of inputs: ");
scanf("%d", &numInputs);
input = malloc(numInputs * sizeof(int));
for (int i=0; i < numInputs; i++)
{
printf("Input #%d: ", i+1);
scanf("%d", &input[i]);
}
// Do Stuff, for example print them:
for (int i=0; i < numInputs; i++)
{
printf("Input #%d = %d\n", i+1, input[i]);
}
free(input);
}
Read in the whole line, then use a loop to parse out what you need.
To get you started:
1) Here is the manual page for getline(3):
http://man7.org/linux/man-pages/man3/getline.3.html
2) Some alternatves to getline:
How to read a line from the console in C?
3) Consider compressing spaces:
How do I replace multiple spaces with a single space?
4) Use a loop for parsing. You might consider tokenizing:
Tokenizing strings in C
5) Be careful and remember that your user could enter anything.
#include <conio.h>
#include <stdio.h>
main()
{
int a[100],i,n_input,inputs;
printf("Enter the number of inputs");
scanf("%d",&n_input);
for(i=0;i<n_input;i++)
{
printf("Input #%d: ",i+1);
scanf("%d",&a[i]);
}
for(i=0;i<n_input;i++)
{
printf("\nInput #%d: %d ",i+1,a[i]);
}
}
/*
_______________This program is in C Programming Language_______________
We have to directly enter all the elements in one line giving spaces between them. Compiler will automatically ends the for loop I have used and assign the value to their respective variables or array indexes. Below program and output will give you better understanding.
*/
#include <stdio.h>
int main()
{
//taking no of inputs from user
int len;
printf("Enter the number of inputs you want to enter : ");
scanf("%d", &len);
int i;
//defined an array for storing multiple outputs
int arr[100];
//included a printf statement for better understanding of end user
printf("Enter the inputs here by giving space after each input : ");
/*here is the important lines of codess for taking multiple inputs on one line*/
for (i=0;i<len;i++)
{
scanf("%d", &arr[i]);
}
printf("Your entered elements is : ");
for (i=0;i<len;i++)
{
printf("%d ", arr[i]);
}
}
/*
OUTPUT :
Enter the number of inputs you want to enter : 5
5 5 5 8 7
Your entered elements is : 5 5 5 8 7
*/