I am new to the C programming language. I am attempting to run the code below an N amount of times (based on the user input of "Enter amount of iterations"). I am trying to do this using a for loop (also tried with a while loop) but have been unsuccessful.
Whenever I run the code below, my terminal continuously repeats "Enter two float numbers:". I have to close the terminal and reopen it to try again. Does the issue have to do with my for loop? I am interpreting my for loop as: "a=0; if a > 0; increment a". Is there a way I can set a limit for "if a > 0" or should I be using a while loop? If the user enters "3" for amount of iterations, I am expecting the program to ask "Enter two float numbers" 3 times (with the answer).
float sum (float m, float n){
return m+n;}
int main() {
float x, y;
int a;
printf("Enter amount of iterations: ");
scanf("%d", &a);
for (int i; i < 0; i++) {
printf("Enter two float numbers: ");
scanf("%f %f", &x, &y);
float su = sum(x,y);
printf("%f and %f = ", x, y);
printf("%f\n", su);}
return 0;}
CORRECT ANSWER Formatted for readability:
float sum(float m, float n)
{
return m + n;
}
int main()
{
float x, y;
int a;
printf("Enter amount of iterations: ");
scanf("%d", &a);
for (int i = 0; i < a; i++)
{
printf("Enter two float numbers: ");
scanf("%f %f", &x, &y);
float su = sum(x, y);
printf("%f and %f = ", x, y);
printf("%f\n", su);
}
return 0;
}
This should behave more like you would like it to:
#include <stdio.h>
static float sum(float m, float n)
{
return m + n;
}
int main(void)
{
float x, y;
int a;
printf("Enter amount of iterations: ");
if (scanf("%d", &a) != 1)
{
fprintf(stderr, "Invalid input for iterations\n");
return 1;
}
for (int i = 0; i < a; i++)
{
printf("Enter two float numbers: ");
if (scanf("%f %f", &x, &y) != 2)
{
fprintf(stderr, "Failed to read to floating point numbers\n");
return 1;
}
float su = sum(x, y);
printf("%f and %f = ", x, y);
printf("%f\n", su);
}
return 0;
}
Note that it checks that the input operations are successful, and reports errors on standard error (stderr). The code uses a standard C for loop to count from 0 up to a limit — this is idiomatic C. You should get used to using it.
As I noted in a comment, the a in the for loop is different from and unrelated to the a declared earlier in your code and set by the input operation. The a in the for loop is not initialized; you can't tell how many times the loop will be executed. A good compiler should warn you about redefining or shadowing a.
for (i = 0; i < a; i++); - answer provided by J.S!
Related
This my first program of C programming using recursive functions, it calculates the sum of the first n natural numbers. I am not able to get an output from it, it asks for the number but after that the program doesnt respond, can someone please help me out?
int n();
int main(){
int num;
printf("Enter num:\n");
scanf("%d", &num);
n(num);
printf("The sum of %d is: %f", num, n(num));
return 0;
}
int n(int x){
if (x != 0){
return n(x) + n(x-1);
**strong text** }
else{
return x;
}
}
Firstly, in the recursive function, return n(x) + n(x-1); should have been return x + n(x-1); as in the first case, n(x) will continuously make a called to another n(x), therefore making an infinite loop, or, more formally, return a 0xC00000FD exception, a Stack Overflow exception.
Also, in the last printf() function, %f should have been %d:
#include <stdio.h>
int n(int x)
{
if (x > 0) {return x + n(x-1);} return x;
}
int main()
{
int num;
printf("Enter num: ");
scanf("%d", &num);
printf("The sum of %d is: %d", num, n(num));
return 0;
}
Using %f to print an integer will caused an undefined behavior, because %f is a float format specifier, as noted here.
If you really want to convert it to a float:
#include <stdio.h>
int n(int x)
{
if (x > 0) {return x + n(x-1);} return x;
}
int main()
{
int num;
printf("Enter num: ");
scanf("%d", &num);
printf("The sum of %d is: %f", num, (double) n(num));
return 0;
}
*Note: Ran on Code::Blocks 20.03, Windows 10 64bit.
More info on format specifiers : https://www.tutorialspoint.com/format-specifiers-in-c
It should be return x instead of calling the same function,
you can use type conversion for changing the integer into a float,
int n();
int main(){
int num,x;
printf("Enter num:\n");
scanf("%d", &num);
x=n(num);
printf("The sum of %d is: %f", num, float(x));
return 0;
}
int n(int x){
if (x != 0){
return x + n(x-1);
**strong text** }
else{
return x;
}
}
This question already has answers here:
Simple C scanf does not work? [duplicate]
(5 answers)
Closed 1 year ago.
I wrote this C program using 2 functions, but in this first case grade() is not prompting for the input:
#include <stdio.h>
int motivQuote();
char grade();
void main()
{
int x;
char y, z;
printf("Programmer-defined Function Type 2\n");
x = motivQuote();
printf("Returned value is %d\n\n", x);
printf("Expected grades this semester:\n");
printf("Subject1: ");
y = grade();
printf("\nReturned value is %c\n", y);
}
int motivQuote()
{
int n = 0;
printf("Select quote (1 or 2):");
scanf_s("%d", &n);
if (n == 1)
printf("\n~ Robert Collier ~\n\t\"Success is the sum of small efforts, repeated day in and day out.\"\n");
if (n == 2)
printf("\n~ David Bly ~\n\t\"Striving for success without hard work\n\tis like trying to harvest where you haven’t planted.\"\n");
return n + 2;
}
char grade()
{
char grade = 0;
scanf_s("%c", &grade, 1);
return grade;
}
And here in the second case, grade() prompts for the input only in the second call, but the first one is not working:
#include <stdio.h>
int motivQuote();
char grade();
void main()
{
int x;
char y, z;
printf("Programmer-defined Functions\n");
x= motivQuote();
printf("Returned value is %d\n\n", x);
printf("Expected grades this semester:\n");
printf("Subject1: ");
y= grade();
printf("\nSubject2: ");
z= grade();
printf("Returned values are %c and %c\n", y, z);
}
int motivQuote ()
{
int n = 0;
printf("Select quote (1 or 2):");
scanf_s("%d", &n);
if (n==1)
printf("\n~ Robert Collier ~\n\t\"Success is the sum of small efforts, repeated day in and day out.\"\n");
if (n==2)
printf("\n~ David Bly ~\n\t\"Striving for success without hard work\n\tis like trying to harvest where you haven’t planted.\"\n");
return n+2;
}
char grade()
{
char grade = 0;
scanf_s("%c", &grade,1);
return grade;
}
Can anyone tell me what's the reason please?
Use scanf(" %c",&grade,1); with a space before %c. This will solve the problem.
In my C Program, I want to get the average of the sum of numbers being entered until the program stops. What should I add to check the average? Thank you!
#include <stdio.h>
int main (void)
{
int x;
int sum = 0;
int average;
int testEOF;
//Statements
printf("Enter your numbers: <EOF> to stop.\n");
do
{
testEOF = scanf("%d", &x);
if (testEOF !=EOF)
sum +=x;
} while (testEOF !=EOF);
printf ("\nTotal: %d\n", sum);
printf ("\nAverage: %d\n", average);
return 0;
//main
}
As other people explained, you have to initialize sum and count, they are never given their initial values. No need to initialize average and x because you assign sum/count to average and users will assign any value to x.
You have to put everything you want your if statement to do in {...}. But you didn't. Your if statement only does sum +=x and does not work for count++ and average = sum / count. So your program increases the value of count even after EOF. So you found 14/6 rather than 14/5.
You checked testEOF != EOF twice. One is in the if statement, other is in do-while.
I put the code below:
#include <stdio.h>
int main (void){
float x;
float sum = 0;
float count = 0;
float average;
float testEOF;
printf("Enter your numbers: <EOF> to stop.\n");
while(1){
testEOF = scanf("%f", &x);
if (testEOF ==EOF){
break;
}
sum +=x;
count++;
average = sum / count;
}
printf ("\nTotal: %f\n", sum);
printf ("\nAverage: %.2f\n", average);
return 0;
}
#include <stdio.h>
int main (void)
{
float x;
float sum;
float count;
float average;
float testEOF;
//Statements
printf("Enter your numbers: <EOF> to stop.\n");
do
{
testEOF = scanf("%f", &x);
if (testEOF !=EOF)
sum +=x;
count++;
average = sum / count;
} while (testEOF !=EOF);
printf ("\nTotal: %f\n", sum);
printf ("\nAverage: %.2f\n", average);
return 0;
}
This is now almost correct. The only thing is that the number is not getting divided by the number of values entered.
Example:
2
3
3
3
3
Sum is 14
Average: 2.3 (should be 2.8)
This seems that count is being added by 1 every time I get the average.
Well if you want your output to be printed with decimal point you can do the following , in that case
for inputs like 0, 1, 1 the out would be 0.666667 otherwise it will be simply 0 ignoring the decimal part.
the while part can be optimized as suggested by #David C. Rankin
double sum = 0;
double average = 0;
unsigned int count = 0;
//Statements
printf("Enter your numbers: <EOF> to stop.\n");
do
{
testEOF = scanf("%d", &x);
if (testEOF != EOF)
{
sum += x;
count++;
}
} while (testEOF != EOF);
printf ("\nTotal: %f\n", sum);
average = sum / count;
printf ("\nAverage: %f\n", average);
Im writing a simple program to show the distance/time between two converging trains. I wanted to test the program and return output value through the function float converge, and then apply that to the main function, but it seems that the converge function does not work.
#include <stdio.h>
float converge(int x, int y, int z) {
return x / (y + z);
}
int main(void) {
int dist, speed1, speed2;
printf("Enter distance in miles");
scanf("%d\n", &dist);
printf("Enter train 1 speed and train 2 speed in mph");
scanf("%d%d\n", &speed1, &speed2);
converge(dist, speed1, speed2);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
float converge (float x, float y, float z)
{
int time=x/(y+z);
return time;
}
int main ()
{
float dist, speed1, speed2;
printf("Enter distance in miles:\t");
scanf("%f", &dist);
printf("Enter speed of first train in mph:\t");
scanf("%f", &speed1);
printf("Enter speed of second train in mph:\t");
scanf("%f", &speed2);
printf("Time between this two trains is %f",converge(dist, speed1, speed2));
}
There are multiple problems in your code:
converge performs integer arithmetic and converts the result to float only for the return value. If you want to compute a fractional number, you should change it to: double converge(int x, int y, int z) { return (double)x / ((double)y + z); } or better use double for the input values and the argument types:
double converge(double x, double y, double z) { return x / (y + z); }
There are trailing newlines in the scanf() conversion formats: this will cause scanf() to consume any trailing white space typed after the numbers, including any number of newlines typed at the prompts. You will not get the second prompt as long as you enter empty lines. Remove these \n from the format strings.
The result of the computation is not printed.
Here is a modified version:
#include <stdio.h>
double converge(double x, double y, double z) {
return x / (y + z);
}
int main(void) {
double dist = 0, speed1 = 0, speed2 = 0;
printf("Enter distance in miles: ");
scanf("%lf", &dist);
printf("Enter train 1 speed and train 2 speeds in mph: ");
scanf("%lf%lf", &speed1, &speed2);
if (speed1 + speed2 <= 0)
printf("No collision\n");
else
printf("Time until collision: %f seconds\", 3600 * converge(dist, speed1, speed2));
return 0;
}
Why is this code not producing an output?
It produces no output for the expected output from the result of converge() because there is no statement in the provided code, which could cause this output.
You need for example one printf() statement after the call to converge() in order to print the result of converge():
#include <stdio.h>
float converge (int x, int y, int z)
{
return x/(y+z);
}
int main (void)
{
int dist, speed1, speed2;
float converge_result;
printf("Enter the distance between the two trains in miles:\n");
scanf("%d", &dist);
printf("\n");
printf("Enter the speed of train 1 and the speed of train 2 in mph:\n");
scanf("%d %d", &speed1,&speed2);
printf("\n");
converge_result = converge(dist, speed1, speed2);
printf("The time until the two trains encounter each other is:\n %f",converge_result);
return 0;
}
or alternatively:
#include <stdio.h>
float converge (int x, int y, int z)
{
return x/(y+z);
}
int main (void)
{
int dist, speed1, speed2;
printf("Enter the distance between the two trains in miles:\n");
scanf("%d", &dist);
printf("\n");
printf("Enter the speed of train 1 and the speed of train 2 in mph:\n");
scanf("%d %d", &speed1,&speed2);
printf("\n");
printf("The time until the two trains encounter each other is: \n%f ",
converge(dist,speed1,speed2);
return 0;
}
By the way, the calculation of the distance in time seems incorrect or at least incomplete.
I'm writing this program for class in which I have to compute the equivalent resistance in series.
The description of the Homework is:
"The present homework is concerned with the use of pointers in computing the equivalent resistance to resistors connected in series. The number of resistors N connected in series and their resistance values R[0], R[1], …, R[N-1] are user-supplied...the inputting of the number of resistors N and the one-dimensional array elements R[0], R[1], …, R[N-1] is done within the “input” prototype function...these values in turn are passed to the “series” prototype function, where the computation of the equivalent resistance Req is performed... the input and output values are outputted to the console from within the “input” function.
-The prototype functions “input” and “series” are to be both placed before the “main” function, with the prototype function “series” placed between the “input” and “main” functions."
Code:
#include <stdio.h>
#define x 100
#define y 10000
float series(int N, float R[]);
void input() {
printf("\n---------------Compute equivalent resistance in series!---------------\n");
int N;
float R[y];
printf("\nPlease enter amount of resistors: \n");
scanf_s("%d", &N);
for (int i = 1; i <= N; i++) {
printf("\nEnter resistance for resistor %d: \n", i);
scanf_s("%f", &R[i]);
}
series(N, R);
printf("\n");
for (int i = 1; i <= N; i++) {
printf("The resistance of R[%d] is: %.2f.\n", i, R[i]);
}
printf("\nThe equivalent resistance is: %.2f Ohms.", Req);
}
float series(int N, float R[]) {
float Req = 0;
for (int i = 1; i <= N; i++) {
Req += R[i];
}
return Req;
}
int main() {
input();
getchar();
return 0;
}
My problem is that Req isn't being returned to the 'input' function in order to output the Equivalent resistance. Please help. Thank You
You're never assigning the result of series to a variable.
float req_ret;
req_ret = series (N, R);