Imputing fractions using arrays in C - c

My program asks the user for a numerator and then a denominator right after (If option 1 is chosen). I am pretty sure i got that part correct.I can not seem to figure out how to display the fraction(s) though when I hit option 2.
This is my code:
#include<stdio.h>
#include<string.h>
typedef struct fraction
{
int numerator, denom;
} fraction; //defined the fraction.
int main()
{//start of program
int z = 0;
int y = 0;
while (1)
{ //start of while loop
int choice;
printf("\nPress 1 to enter a fraction\n");
printf("Press 2 to view the entered fraction\n");
scanf("%d", &choice);
fraction arrFraction[100];
arrFraction[0].numerator = 0;
arrFraction[0].denom = 0;
if (choice == 1) // first option (enter numerator and then denom after)
{
printf("Enter the fraction\n");
scanf("%d", &arrFraction[y].numerator);
scanf("%d", &arrFraction[z].denom);
y++
z++;
}// end of first if statement(to enter the fraction)
if (choice == 2) //to view the entered fractions.
{
printf("\n-----------------------------");
for (int m = 0; m < z; m++)
{
printf(" %d / %d \n", arrFraction[y].numerator/arrFraction[z].denom);
}
printf("\n\n-----------------------------");
} // end of second if statement (to view the fraction entered earlier)
} // end of while loop
system("pause");
return(0);
}

You need to move fraction arrFraction[100]; out of while loop, otherwise, every iteration, there will be a new array.
That said,
printf(" %d / %d \n", arrFraction[y].numerator/arrFraction[z].denom);
is wrong, you're supplying two format specifiers but one argument. This invokes undefined behavior. Your compiler should have warned you.
I believe, what you want instead is
printf(" %d / %d \n", arrFraction[y].numerator, arrFraction[z].denom);
That said, I'm not very convinced with the overall logic. Why do you seem to need an array of 100 elements? If you're only interested in previous record (not records), use only a simple variable, not an array. Besides, you don;t need to have two separate index/ counters anyway. A single index will be able to manage the inputs in much concise and robust way.

Related

Scanning Values Until Getting a Significant Character in C

For my homework, I am trying to code a calculator which can also calculate average of taken numbers. I don't want to ask for number of numbers because our teacher don't want it in that way. So I thought of scanning values until the user presses "p". But as you would guess, the numbers are float and "p" is a character. What I want to do is assigning the value scanned to both of them if it is possible. I tried different ways, played with the codes but it isn't working properly. So I am seeking your advice.
It prints a value when p is inputted as like 3rd, 5th, 7th (oddth) number (sometimes right, sometimes wrong but I can fix it if I figure this out). But it doesn't print a value in other occasions and expects infinite inputs from the user.
This is the code I have written for this. scanf("%f %c", &number1, &pause); command is where I want to know about, actually.
#include<stdio.h>
float number1, number2, i, result;
char pause;
int main() {
scanf("%f", &number1);
i = 0;
while (pause != 'p') {
number2 = number1 + number2;
scanf("%f %c", &number1, &pause);
i++;
}
result = number2 / (i - 1);
printf("%f", result);
}
Use double not floats if there is no specific reason to do so (like using uC without double FPU).
You do not initialize the variables
Always check the result of the I/O operation.
#include <stdio.h>
int main ()
{
double number1= 0, number2 = 0, i = 0, result = 0;
char pause = 0;
char line[128];
while (pause != 'p')
{
if(fgets(line, sizeof(line), stdin))
{
if(sscanf(line, "%lf %c",&number1, &pause) != 2)
{
printf("Wrong input - try again\n");
pause = 0;
continue;
}
number2 = number1 + number2;
i++;
}
else
{
// do something with I/O error
}
}
result = number2 / (i-1);
printf("%lf",result);
}
You can play with it yourself : https://onlinegdb.com/Hy3y94-3r
I noticed 3 problems with your code.
First I would advise you to use meaningful variables names. number1, number2, etc. and the i which represents the number of inputs given can be an int instead of a float.
Secondly, you lack of printing to the user what's going on in your program; it's better to have messages like "enter your number, do you wanna stop? the result is...etc".
Lastly, having two inputs in one line of code can make it hard to debug, knowing that reading strings and characters in C is already hard for beginners. For example, %c does not skip whitespace before converting a character and can get newline character from the previous data entry.
Here is my fix: I changed some variables' names, printed some messages and read the two inputs in two different lines with adding scanf(" %c") with the space to avoid that problem.
#include<stdio.h>
float sum, temp, result;
int nb;
char pause;
int main () {
pause='a';
while (pause != 'p'){
printf("Enter your number: ");
scanf("%f",&temp);
sum+=temp;
nb++;
printf("type 'p' if you want to stop: ");
scanf(" %c",&pause);
}
result = sum / nb;
printf("the average is : %f",result);
}
I tested it, should work fine
Edit: after explaining that you don't want to ask the user each time, here is how the code should work (the case that the user don't input a float is not treated, and just take it as zero
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
float sum, temp, result;
int nb;
char input[50];
int main () {
sum=0;
nb=0;
printf("Enter your numbers, then type 'p' to stop\n");
do{
printf("Enter your next number: ");
scanf("%s", input);
if(strcmp(input,"p")!=0)
{
float temp= atof(input);
sum+=temp;
nb++;
}
}while(strcmp(input,"p")!=0);
if(nb!=0)
result = sum / nb;
printf("\nThe average is : %f",result);
}

for loop resulting in undefined behaviour c

#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
int mult;
int n;
int ans;
ans = mult * i;
printf("Please enter a multiple you want to explore.");
scanf("%d", &mult);
printf("Please enter the number which you would want to multiply this number till.");
scanf("%d", &n);
for(i = 0; i<n; i++) {
printf("%d x %d = %d \n", &mult, &i , &ans);
}
return 0;
}
Hi guys, this is a simple code which is supposed to help the user to list the times table for n times. However, i am receiving undefined behaviour and I am quite stumped as to what is wrong with my implementation of my "for" loop.
I am receiving this as my output.
6356744 x 6356748 = 6356736
for n times in my consoles.
I want to ask
Is anything wrong with the logic of my code? (i assume i do have a problem with my code so please do enlighten me)
Would it be better(or even possible) to use pointers to point to the memory addresses of the mentioned variables when i have to change the value of the variables constantly? If yes, how do i go around doing it?
Thanks!
In printf you must provide integers. You are now giving the addresses of integers. So change
printf("%d x %d = %d \n", &mult, &i , &ans);
to
printf("%d x %d = %d \n", mult, i, ans);
and to make the table, replace ans with just mult*i, so:
printf("%d x %d = %d \n", mult, i, mult*i);
You should also check the return value of scanf to check if it has succeeded reading your input:
do {
printf("Please enter a multiple you want to explore.");
} while (scanf("%d", &mult)!=1);
do {
printf("Please enter the number which you would want to multiply this number till.");
} while (scanf("%d", &n)!=1);
The things you see are the values of the variables memory location.
Change your lines inside for loop as below
ans = mult * i;
printf("%d x %d = %d \n", mult, i, ans);
There are some mistakes in your code .
you are using the & operator in print statement which is used to print the address of the variable.
Initiate the loop with the value '1' instead of '0' & execute the loop till 'i' less than equal to 'n'.
instead of using the ans variable outside the loop , use it inside the loop as it evaluate the multiplication result in each iteration of the loop.
#include <stdio.h>
int main()
{
int i;
int mult;
int n;
int ans;
printf("Please enter a multiple you want to explore.");
scanf("%d", &mult);
printf("Please enter the number which you would want to multiply this number till.");
scanf("%d", &n);
for(i = 1; i<=n; i++) {
ans = mult*i ;
printf("%d x %d = %d \n", mult, i , ans);
}
return 0;
}

C Programming sum of all integer numbers between two integers

I'm a newbie!
I'm supposed to get 2 integers from the user, and print the result(sum of all numbers between those two integers).
I also need to make sure that the user typed the right number.
The second number should be bigger than the first one.
And if the condition isn't fulfilled, I have to print "The second number should be bigger than the first one." and get the numbers from the user again until the user types right numbers that meet the condition.
So if I programmed it right, an example of the program would be like this.
Type the first number(integer) : 10
Type the second number(integer) : 1
The second number should be bigger than the first one.
Type the first number(integer) : 1
Type the second number(integer) : 10
Result : 55
End
I think that I have to make two loops, but I can't seem to figure out how.
My English is limited, to help your understanding of this quiz, I'll add my flowchart below.
I tried many different ways I can think of, but nothing seems to work.
This is the code that I ended up with now.
But this doesn't work either.
#include <stdio.h>
void main(void)
{
int a = 0;
int b = 0;
int total_sum = 0;
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
while (a > b) {
printf("The second number should be bigger than the first one.\n");
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
}
while (a <= b) {
total_sum += a;
a++;
}
printf("Result : \n", total_sum);
}
Instead of using loop to sum the numbers, we can use mathematical formula.
Sum of first N integers= N*(N+1)/2
#include <stdio.h>
int main(void)
{
int a = 0;
int b = 0;
int sum;
//Run infinite loop untill a>b
while(1)
{
printf("Type the first number : ");
scanf("%d", &a);
printf("Type the second number : ");
scanf("%d", &b);
if(a>b)
{
printf("The second number should be bigger than the first one.\n");
}
else
{
break;
}
}
//Reduce comlexity of looping
sum=((b*(b+1))-(a*(a-1)))/2;
printf("Result : %d " , sum);
return 0;
}
After corrections your code should run. The community has pointed out many mistakes in your code. Here's an amalgamated solution:
#include <stdio.h>
int main(void)
{
int a = 0;
int b = 0;
int correctInput=0;
int total_sum = 0;
do
{
printf("Type the first number : \n");
scanf("%d", &a);
printf("Type the second number : \n");
scanf("%d", &b);
if(a<b)
correctInput=1;
else
printf("The second number should be bigger than the first one.\n");
}
while (correctInput ==0) ;
while (a <= b) {
total_sum += a;
a++;
}
printf("Result : %d \n" , total_sum);
return 0;
}
Factorials are used frequently in probability problems. The factorial of a positive integer n (written n! and pronounced "n factorial") is equal to the product of the positive integers from 1 to n: n! = 1 x 2 x 3 x x n Write a program that takes as input an integer n and computes n!.

display highest/lowest and the avg of inputed marks - C programming

I'm writing a c program for my intro class and I'm stuck on the if/else statements. we have to output the highest,lowest grade entered as well as the avg for those. Marks entered must be between 0-100. this is my code so far, i can't seem to figure it out, thanks for any advice! :
#include <stdio.h>
int main (void)
{
int numberofMarks;
int i;
int x;
int y;
int numofPasses=1;
int numofFails=1;
float sumpassedMarks =0;
float sumfailedMarks=0;
float markEntered=0;
float highestMark=0;
float lowestMark=0;
float totalMark=0;
float avgofMarks=0;
float avgpassedMarks=0;
float avgfailedMarks=0;
printf (" ---=== IPC mark Analyser ===---\n");
printf ("Please enter the number of marks(between 3 and 40): ");
scanf ("%d", &numberofMarks);
//asks user for number of marks, only takes 3-40, otherwise outputs error msg
for (i=1 ; (numberofMarks < 3)||(numberofMarks > 40) ; i++) {
printf ("Invalid number, enter a number between 3 and 40 inclusive: ");
scanf ("%d", &numberofMarks);
}
//for loop recieves the mark
for (x=1 ;(x <= numberofMarks) ; x++) {
printf ("%d> ", x);
scanf ("%f", &markEntered);
//contd loop..loop makes sure mark entered is between 1-100
for (y=1; (markEntered <0)||(markEntered>100); y++)
{
printf ("Error, Enter values between 0 and 100 incluisve.\n");
printf ("%d> ", x);
scanf ("%f", &markEntered);
if (markEntered >= 50) {
numofPasses=numofPasses+1;
}
if else (markEntered <= 49) {
numofFails = numofFails+1;
}
if else (markEntered > highestMark) {
highestMark = markEntered;
}
else (markEntered < lowestMark) {
lowestMark = markEntered;
}
}
//adds the mark entered to all the marks entered for a overall sum
totalMark = totalMark + markEntered;
}
avgofMarks = (float)totalMark / numberofMarks;
avgpassedMarks = (float)sumpassedMarks / numberofMarks;
avgfailedMarks = (float)sumfailedMarks / numberofMarks;
printf ("Total of %d students passed with an average of %.1f.\n", numofPasses,avgpassedMarks);
printf ("Total of %d students failed with an average of %.1f.\n", numofFails, avgfailedMarks);
printf ("Highest mark in the group: %.1f\n", highestMark);
printf ("lowest mark in the group: %.1f\n", lowestMark);
printf ("The average of all marks in this group is %.1f.\n", avgofMarks);
printf ("Program Ended.\n");
return 0;
}
The work asks,
In the loop in which marks are being entered, after each entry examine the value of the mark entered:
If it is a pass, add one to the number of passes and add the value of the mark to the sum of passed marks.
If it is a fail, add one to the number of fails and add the value of the mark to the sum of failed marks.
If the value is higher than the highest mark, set highest mark to the value read.
If the value is lower than the lowest mark, set the lowest mark to
the value read. After all the marks are entered and examined, divide
the sums by the corresponding number of marks to get the average and
print the results.
This is my output vs the sample output.
Your code is a mess; let's try to get some things straight here:
If you're not gonna use i in the body of a for loop, no reason to initialize and increment it. Better to use a while.
When you post a question, clear all not-strictly-necessary code from the answer, so that it's easier to help
Instead of making 15 variables, consider using an array or, if you're not gonna use the values later in the program, print the result directly.
Ex.
int a = 10, b = 15; If you wanna print the sum, no reason to save it in a new int sum, just printf("%d", a + b);
Do not request the number of votes outside of a loop, and then loop to verify the value (your first for loop). Consider a DO..WHILE loop instead.
Ex.
do{
scanf("%d", &n);
} while(n <= 0);
//Scan integer and save into n, until you get a positive value
Avoid nesting for loops for no reason, use more if() .. else if() .. if necessary.
It's not the best of practise, but you can also use the continue and break keywords to continue or stop the loops respectively.
Do not use "else" randomly. If you have more conditions to check, leave the if without else. You wanna use else after an if condition if (when the first condition comes back true) you don't want to check the next condition (they will be skipped !)

Need help terminating program when secret number is found

I'm trying to write a c program that uses a function that adds 2 integers to a random number. Which I have accomplished below. My problem is, I set a variable to a secret number and when that number is found, I need the program to terminate and it does not.
int x,y,secretnumber;
secretnumber = 5;
do
{
printf("Please enter two integers to be added together to a random number from 0-99 \n"
"Keep entering numbers until you hit the secret number!\n");
scanf("%i%i", &x, &y);
if(sumintsrand(x,y) != secretnumber)
{
printf("The summation of integers %i and %i and a random number is %i \n\n",x,y,sumintsrand(x,y));
}
else
{
printf("You have found the secret number: %i! Goodbye!\n", secretnumber);
}
}
while(sumintsrand(x,y) != secretnumber);
return 0;
}
int sumintsrand(int x, int y)
{
int sumintsrand = x + y + rand()%5;
return sumintsrand;
}
If anyone has any idea where I'm going wrong I would really appreciate it
UPDATE
I compiled your program with my earlier suggested mod, and I didn't get silly large numbers, so pass on that - different question?
It seems a bit strange to keep changing the random number - the same guess might fail once but work the next time. Also there is a confusion about whether the range is 5 or 99.
So I've simplified your work, to make you guess two numbers that sum to the secret number. If that's not your intention, perhaps you can draw on my code.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define MAXVAL 5
int main(){
int x, y, secretnumber, testval;
srand ((unsigned)time(NULL));
secretnumber = rand() % (MAXVAL+1);
do
{
printf("Enter two integers to be added to equal a secret random number from 0-%d\n"
"Keep entering numbers until you hit the secret number!\n", MAXVAL);
if (scanf("%d%d", &x, &y) != 2)
return 0; // exit program
testval = x + y;
if(testval != secretnumber)
printf("Sorry - try again!\n\n");
else
printf("You have found the secret number: %d + %d = %d! Goodbye!\n",
x, y, secretnumber);
}
while(testval != secretnumber);
return 0;
}
You are calling your sumintsrand() function thrice. Each time, the result of the function is going to be different based on what rand() returns.
Your call to sumintsrand()within the while loop may have found the secret number, but that is not retained. You need to store it for checking whether while loop needs to be terminated.
UPDATE:
int sum = 0;
do {
scanf("%i%i", &x, &y);
sum = sumintsrand(x,y);
} while(sum != secretnumber);
It's not working, because in that line while(sumintsrand(x,y) != secretnumber); you are calling sumintsrand a second time - and it gives other result.
Possible solutions:
Save the result of first call of sumintsrand and check if it(the saved result) is the same as secretnumber
Use break
Make bool variable which will end the loop - at the beginning it will be true, when you will find the number just set it to false.

Resources