How to make compiler repeat until the number 0 is presed - c

I'm wondering how to make the compiler repeat itself if the user presses a random button at the end. But if the user presses "0" the compiler exits.
My code:
#include<stdio.h>
#include<stdlib.h>
#include <math.h>
#include <float.h>
struct mystruct
{
float startnummer;
float hoppnummer;
float svarighetsgrad;
float domarpoangs[7];
};
int main(void)
{
struct mystruct data;
float max = 0;
float min = FLT_MAX;
float sum = 0;
float avg = 0;
int i = 0;
float resultat = 0;
printf("Startnummer: \n");
scanf_s("%f", &data.startnummer);
printf("Hoppnummer:\n");
scanf_s("%f", &data.hoppnummer);
printf("Svarighetsgrad:\n");
scanf_s("%f", &data.svarighetsgrad);
for (i = 0; i < 7; i++)
{
printf("domarpoang %d\n", i + 1);
float f;
if (scanf_s("%f", &f) == 1)
{
if (f < min) min = f;
if (f > max) max = f;
data.domarpoangs[i] = f;
}
else
{
printf("error parsing float\n");
exit(0);
}
}
system("cls");
printf("Startnummer: %.1f \n", data.startnummer);
printf("Hoppnummer: %.1f\n", data.hoppnummer);
printf("Svarighetsgrad: %.1f\n", data.svarighetsgrad);
for (i = 0; i < 7; i++)
{
printf("Domarpoang %d: %.1f\n", (i + 1), data.domarpoangs[i]);
}
for (i = 0; i < 7; i++)
{
sum += data.domarpoangs[i];
}
sum = sum - (max + min);
avg = sum/5;
resultat = avg * 3 * data.svarighetsgrad;
printf("Hoppoang:%.2f \n", resultat);
printf("Tryck tangent for nytt hopp!");
getchar();
getchar();
return 0;
}
*If the user presses random button, the compiler repeat itself from the beginning
*If the user presses 0, the compiler exits.
Any help is appreciated, thank you.

This answer puts a loop around the body of your main() code, taking care to re-initialise some of the variables for the next iteration.
There are many SO questions about getting keyboard input and clearing the debris. I know of no simple standard ways of testing for keyboard input such as kbhit(), for taking a single key input such as getch() or for flushing the input. Even getchar() is horrible - it won't return until you have pressed "Enter" which it leaves in the input buffer. This has resulted in many SO answers with impenetrable (to me) formats for scanf() to flush the input, or testing if (getchar() == EOF) - which does not respond to the "Enter" key.
So I have put a simple wrapper around the main() code, which terminates when '0' is entered followed by a control char (because fgets() appends the newline) or terminator. This removes the need to clean up the input - except in the case where the user inputs some silly typing. GIGO!
#include <stdio.h>
#include <float.h>
#define BUFFSIZE 10
struct mystruct {
float startnummer;
float hoppnummer;
float svarighetsgrad;
float domarpoangs[7];
};
int main(void)
{
char kbuff [BUFFSIZE+1];
struct mystruct data;
float max;
float min;
float sum;
float avg;
int i;
float resultat;
do {
max = 0; // initialise for each loop
min = FLT_MAX;
sum = 0;
printf ("Body of your main loop\n");
fgets(kbuff, BUFFSIZE, stdin);
} while (kbuff[0] != '0' || kbuff[1] >= ' ');
return 0;
}

Related

Using a loop to run a program n amount of times

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!

Multidimensional array in C with some math.h

The code I have so far for setting up my array is this:
#include <stdio.h>
void printArray(float myArray[4][3]);
int main(void)
{
};
printArray(sides);
return 0;
}
void printArray(float passedArray[4][3])
{
printf("Side A\tSideB\tSide C\n");
for (int x = 0; x < 4; x++)
{
for (int y = 0; y < 3; y++)
{
printf("%.3f \t", passedArray[x][y]);
}
printf("\n");
}
}
I've also created a way to evaluate the hypotenuse in a previous code if I was given an input from the user:
#include <stdio.h>
#include <math.h>
double hypotenuse(double lengtha, double lengthb);
int main() // Start of main function
{
double lengtha, lengthb; //storing variables for later use
printf("Enter the length of side A: \n"); //Prompt user for input of A
scanf("%lf", &lengtha); //Stores input from user
printf("Enter the length of side B: \n\n"); // Prompt user for input of B
scanf("%lf", &lengthb); //Stores input from user
return 0; // terminate
} /* End function main */
double hypotenuse(double sidea, double sideb)
{
return sqrt(pow(sidea, 2) + pow(sideb, 2));
} /* End function */
The main issue that' I'm running into however though, is I'm unsure how to take the pre stored values from my first code/arrays, throw them into the equation, then have them output into side c into the table. I know there has a to be a way, but it's really hard to find too much info since C is a bit older. Any suggestions or help would be greatly appreciated!
If i understood you correctly, you could just iterate over every row of your array and assign the result of the function call to the last column:
for (int i = 0; i < 4; ++i) {
array[i][2] = hypotenuse(array[i][0], array[i][1]);
}

How do I add a loop for scanf in C?

I have a short question:
How can I expand my program so that it checks if I entered the right format?... if not the program should repeat the scanf.
This is how far I came:
#include <stdio.h>
int main()
{
float zahlen[2];
int i = 0;
while (i < 2 && zahlen != EOF) {
printf("%d. Zahl", i + 1);
scanf_s("%f", &zahlen[i]);
}
printf("Division: %f\n", zahlen[0] / zahlen[1]);
printf("Produkt: %f\n", zahlen[0] * zahlen[1]);
printf("Summe: %f\n", zahlen[0] + zahlen[1]);
printf("Diffenrenz: %f\n", zahlen[0] - zahlen[1]);
printf("Mittelwert: %f\n", (zahlen[0] + zahlen[1]) / 2);
getchar();
return 0;
}
Would appreciate any help of you. Have a nice day/night.
You should define what a right format is. But in a form of pseudo-code
float input;
// First get the input
do {
sacnf_s("%f", &input);
} while (!IsRightFormat(input)); // If the input was not correct get it again
// Do your stuff here
// ...

C scanf in loop continues automaticly without input

I'm trying to get input in an array, I expect input like the following.
5 (Number of the second dimensions in the array)
2 (Number of the first dimensions in the array)
So we get an array deeln[2][5] in this example. I try to get it with the following code:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isinarray(int val, int *arr, int size){
int countimp;
for (countimp=0; countimp < size; countimp++) {
if (arr[countimp] == val)
return true;
}
return false;
}
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
scanf("%s", temp);
for(cj = 0; cj < k; cj++){
deeln[ci][cj] = temp[cj*2]-'0';
}
}
//loop while.
}
But i've got a problem, whenever i try to input, the program runs automaticly without getting any input when it loops around the third scanf for the 2nd or 3rd time. So then i'm not able to input anything.
What to do? Has it something to do with pointers or am i using scanf wrong?
UPDATE:
If I enter a printf after printf("cj is nu %i \n", cj); then the output also just came after the loop was going its own way. and not before i should give more input, using the third scanf.
The solution of my question was quite easy. I found it after thinking of my input. The problem was that in the input, as described, there were spaces. Somehow scanf can't handle with spaces, unless you use some other syntax. But my solution is to just use fgets instead of scanf where I wanted to get the input. So the new and working code is as follows:
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isinarray(int val, int *arr, int size){
int countimp = 0;
for (countimp=0; countimp < size; countimp++) {
if (arr[countimp] == val)
return true;
}
return false;
}
int main(void){
int t, k = 0, d = 0, ci = 0, cj = 0, ta = 0;
//get input
scanf("%i", &k);
scanf("%i", &d);
char temp[20];
int deeln[d][k];
memset(deeln, 0 , sizeof(deeln));
memset(temp, 0 , sizeof(temp));
for(ci = 0; ci < d; ci++){
fgets(temp, 20, stdin);
for(cj = 0; cj < k; cj++){
ta = cj*2;
deeln[ci][cj] = temp[ta]-'0';
}
}
//loop while.
return 1;
}
Thanks for helping everbody, even though we all didn't came to this. But I hope it will help others!
Two places to look:
1)
cj = 0;//initialize cj before using here
scanf("%i", &temp[cj]);//temp is both an array, and an int. Fix your format specifier,
//and use an index operator - temp[?] (not sure I am using the right index)
2)
deeln[ci][cj] = temp[cj*2]-'0'; //fix your logic here (array index will be exceeded)
An example of working code...
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
for(cj = 0; cj < k; cj++){
if(scanf("%i", &temp[cj]) != EOF)
{
deeln[ci][cj] = temp[cj]-'0';
}
else deeln[ci][cj] = -1;
}
}
getchar();
//loop while.
}
you can play with the index of temp[cj] to make it what you actually want, but I assume you are intending to read from stdin, then populate deeln[][] with that value, for each scanf.
If you want to parse a string containing spaces and digets, "1 3 8 5 3", you could use strtok()
But your code as it is is not reading a string in, it is reading integers.
This is not perfect, you will have to do some debug, but will illustrate strtok(). You have to enter spaces between each digit after indices are selected: i.e.:
3
3
4 6 8
2 4 7
1 2 8
int main(void){
int k, d, ci, cj, ck, ta;
//get input
scanf("%i", &k);
scanf("%i", &d);
char inStr[d][k*5]; //space for up to k 3 digit numbers with 1 space each
char *buf=0;
int deeln[d][k], temp[k];
for(ci = 0; ci < d; ci++){
printf("d= %i, ci= %i \n", d, ci);
if(scanf("%s ", inStr[ci]) != EOF)
{
buf = strtok(inStr[ci], " ");
cj = 0;
while(buf && (cj < k))
{
deeln[ci][cj] = atoi(buf);
cj++;
}
}
}
//getchar();waits for user input, pauses execution
}

Finding the interpolation with user input

I made some revisions to the algorithm, and get a value (though it is incorrect) in the function, but the return value refuses to send it back to the main function. Also, I cannot get they yes no portion of the code that ask for the program to rerun to function.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
/*Prototype for functions used*/
float getdistance(float[], float[], float, int);
float printvalue(float);
int main()
{
int maxtime = 18;
float usertime = 0;
char reiteration;
char y, n;
int reit_choice = 0;
float interpolation = 0.0;
float time_arr[]={0,3,5,8,10,12,15,18};
float distance_arr[]={2,5.2,6,10,10.4,13.4,14.8,18};
do
{
printf("Please enter a number between 0 and 18 for the starting time:");
scanf("%f", &usertime, "\b");
while(usertime <0 || usertime >18)
{
printf("The value you have entered is not valid, please enter a value between 1 and 18");
scanf("%f", &usertime, "\b");
}/*End of data verification loop*/
getdistance(time_arr, distance_arr, usertime, maxtime);
printf("%f", interpolation);
printvalue(interpolation);
system("pause");
printf("would you like to check another time?(y/n)");
scanf("%c[y n]", &reiteration, "\b");
while(reiteration!='y' || reiteration!='n')
{
printf("Please enter either y for yes or n for no");
scanf("%c", &reiteration, "\b");
}/*End of choice verification loop*/
if(reiteration = 'y')
{
reit_choice = 1;
}
else
{
reit_choice = 0;
}
}/*End of do loop*/
while(reit_choice);
}/*End of main loop*/
float getdistance(float time_arr[], float distance_arr[], float usertime, int maxtime)
{
int index=0;
float interpolation = 0;
for(index; usertime > time_arr[index]; index++)
{
if(usertime<3)
{
break;
}
}/*End of value assignment for loop*/
interpolation = (time_arr[index]) + (((time_arr[index +1] - time_arr[index])/(distance_arr[index +1] - distance_arr[index])) * (usertime - distance_arr[index]));
printf("%f", interpolation);
return interpolation;
}/*End of distance calculation loop*/
float printvalue(float interpolation)
{
printf("The interpolation was %f", interpolation);
}/*End of screen print loop*/
The reason for 0 output is
getdistance(time_arr, distance_arr, usertime, maxtime);
in int main() function you're calling the function getdistance which calculates the interpolation value and returns the value, But in main function the returned value is not assigned to the variable interpolation . so you've to modify the code as
interpolation = getdistance(time_arr, distance_arr, usertime, maxtime);
printvalue(interpolation);
Which will print the output

Resources