How to carry a value through scanf to a function - c

I have a quick question in the program I'm trying to create. I can't seem to figure out how I can carry through the value that someone inputs for my variable of "denom" so that it can be successfully used in the function I've created. Help would be much appreciated.
#include <stdio.h>
//Global Variables
int num, denom;
void simplify(int *numerator, int *denominator);
int main () {
int num1, denom1;
//Prompt User as to what program is
printf("Fraction Simplifier\n");
printf("===================\n");
//Ask User for Numerator and Denominator
printf("Numerator: ");
scanf("%d", &num);
printf("Denominator: ");
scanf("%d", &denom);
//Call Function
simplify(&num1, &denom1);
//Display final output
printf("%d / %d = %d / %d\n", num, denom, num1, denom1);
return 0;
}
//Simplify function
void simplify(int *numerator, int *denominator)
{
int num1, denom1;
num1 = 1;
num = num1;
denom = denom1;
num1 = num1 / num1;
denom1 = denom1 / num1;
*numerator = num1 ;
*denominator = denom1;
}

Your simplify() method doesn't even try to use the passed values.
It boils down to *numerator = 1 and *denominator = is undefined (since denom1 is never initialized). i.e. it sets "out values" to "constants". You probably meant to do something like:
int num1 = *numerator;
int denom1 = *denominator;

In Simplify() function:
*int num1, denom1;
denom = denom1;* (1)
denom1 = denom1 / num1; (2)
*denominator = denom1;* (3)
in (1) denom1 has undefined values. So when you use:
(2)denom1 still has an undefined value
and in (3)
denominator has an undefined value

Related

How to run a c program using loops to find the remainder of two numbers without using multiplication, division and modulo operators?

#include <stdio.h>
int main()
{
int num1, num2;
printf ("Input value for num1: ");
scanf ("%d", &num1);
printf ("Input value for num2: ");
scanf ("%d", &num2);
int prod =0, i;
for(i = 1; i <= num1; i++){
prod += num2;
}
int quo = 0 , rem = 0;
for(rem = num1 - num2; rem >= 0; rem = rem-num2) {
if(rem < 0)
break;
else
quo++;
}
//The last part is that i need to find the remainder without using multiplication, division and the modulo itself.
printf ("The product of %d and %d is: %d\n", num1, num2, prod);
printf ("The integer quotient of %d and %d is: %d\n", num1, num2, quo);
return 0;
}
The simplest solution for calculating a mod b for positive integers a and b with only subtraction and addition is to subtract b from a until the result is smaller than a. However, this takes many iterations if b is much smaller than a.
A method with better worst-case performance is the following:
#include <stdio.h>
unsigned rem(unsigned a, unsigned b)
{
if(b == 0) return 0; // Error
while(a >= b)
{
unsigned s = b;
do
{
a = a - s;
s = s + s;
} while(a >= s);
}
return a;
}
int main(void)
{
unsigned example = rem(32453, 3);
printf("%u\n", example);
}
This method is based on the fact that to get closer to the result, we can subtract any multiple of b as long as it is smaller than a, so in each inner iteration we try to subtract twice the multiples of the last iteration until the subtractor becomes too large and we start over again with a single multiple of b.
Be aware that this will give wrong results if s = s + s; overflows the unsigned range. Hence, a should not be larger than half the upper limit of unsigned.
If you want a slow calculation of num1 % num2 (i.e. without multiplication/division) you can do:
// Calculate num1 % num2
unsigned rem(unsigned num1, unsigned num2)
{
if (num2 == 0) {.... error handling ....}
while (num1 >= num2) num1 -= num2;
return num1;
}
int main(void)
{
unsigned num1 = 42;
unsigned num1 = 3;
unsigned rem = rem(num1, num2);
printf("%u", rem);
return 0;
}

Why does my program produce no file output?

I am working on a lab assignment which asks me to take a given number from a user, and output that many Fibonacci numbers, test case being 20. I am also asked to have all program output be put into a file named csis.txt. I think that I have done everything correctly in regards to the syntax, but I get a blank csis.txt file. Does anyone see why I am getting blank output files? Does anyone know how I can get each iteration of the for loop to be included in the output? Thanks.
#include <stdio.h>
FILE *fp;
int fib(int num);
int main(void) {
int num, num1 = 0, num2 = 1;
fopen_s(&fp, "csis1.txt", "w");
printf("How many Fibonacci numbers would you like to output?\n");
fprintf(fp, "How many Fibonacci numbers would you like to output?\n");
scanf_s("%d", &num);
printf("The Fibonnaci sequence up to %d numbers:\n%d\n%d\n", num, num1, num2);
fprintf(fp, "The Fibonnaci sequence up to %d numbers:\n%d\n%d\n", num, num1, num2);
printf(fib(num));
fprintf(fp, fib(num));
fclose(fp);
return 0;
}
int fib(num) {
int fibnum, counter;
int num1 = 0, num2 = 1;
for (counter = 3; counter <= num; counter++) {
fibnum = num1 + num2;
printf("%d\n", fibnum);
fprintf(fp, "%d\n", fibnum);
num1 = num2;
num2 = fibnum;
}
}

No idea how to properly receive and use user input

I have the main code I want to use written out. All I need to do is get the user to input five numbers. Then once they insert the numbers I need them to be inputted into the array so that they can be calculated. I have tried to understand how to successfully get user input and use it, but have been unable to figure it out.
int
main (int argc, char **argv)
{
int number1;
int number2;
int number3;
int number4;
int number5;
int a[5];
printf("Enter a number\n");
scanf ("%d, number1");
printf("Enter a number\n");
scanf ("%d, number2");
printf("Enter a number\n");
scanf ("%d, number3");
printf("Enter a number\n");
scanf ("%d, number4");
printf("Enter a number\n");
scanf ("%d, number5");
a[0] = number1;
a[1] = number2;
a[2] = number3;
a[3] = number4;
a[4] = number5;
int mean = (a[0] + a[1] + a[2] + a[3] + a[4]) / 5;
int difference0 = a[0] - mean;
int difference1 = a[1] - mean;
int difference2 = a[2] - mean;
int difference3 = a[3] - mean;
int difference4 = a[4] - mean;
int variance = ((difference0 * difference0) + (difference1 * difference1) + (difference2 * difference2) + (difference3 * difference3) + (difference4 * difference4)) / 5;
double sdeviation = sqrt(variance);
printf("the mean of the array is %d\n",mean);
printf("the variance of the array is %d\n",variance);
printf("the standard deviation of the array is %f\n",sdeviation);
return 0;
}
First of all, you don't need the numberN local variables. You can define the array and read the numbers into it directly.
That said, do not repeat the same code over and over again.
Change the code like
#define ARRSIZE 5
int a[ARRSIZE] = {0};
for (int i = 0; i < ARRSIZE ; i++) {
printf("Enter a number\n");
scanf ("%d", &a[i]);
}
Also, it's always a good practice to check the return value of scanf() function to ensure that the scanning was successful.
Suggestion: Always enable compiler warnings and try to resolve the warnings.
Just to add to the other answer by #Sourav, there are principles you have to learn as a programmer. One of which is, if you have to repeat any task with minor variations, you're most likely going to use a loop. Also, to quote Sinan Ünür
When you find yourself adding an integer suffix to variable names, think I should have used an array.
If you wish to create 5 int variables and you're just naming each one: number1 ... number 5, then you should just create an array to hold them all. It is a lot easier and enables you to refer to each one dynamically because of how arrays work.
int numbers[5]; //Now you can refer to each one by numbers[X]
...
for (int i = 0; i < 5; ++i) {
numbers[i] = a[i] - mean;
}
Those are just two very small modifications I would have added to your code so that it is a lot smaller and easier on the eyes. You'll learn this a lot better as you go along.
You need & operator before the variable you want to assign the upcoming value. On that way, you are saying that num1 = 4, where for is the user's value.
When you declare same type variables, just put then in row separated by comma. You don't need a new line for each one.It makes your code more legible
int argc and char **argv params, are not being used in this function and instead are consuming unnecessary ram memory
Try this:
#include <stdio.h>
#include <math.h>
int main()
{
int num1,num2, num3, num4, num5;
printf("Enter #1:\n");
scanf ("%d", &num1);
printf("Enter #2:\n");
scanf ("%d", &num2);
printf("Enter #3:\n");
scanf ("%d", &num3);
printf("Enter #4:\n");
scanf ("%d", &num4);
printf("Enter #5:\n");
scanf ("%d", &num5);
int mean = (num1 + num2 + num3 + num4 + num5) / 5;
int difference0 = num1 - mean;
int difference1 = num2 - mean;
int difference2 = num3 - mean;
int difference3 = num4 - mean;
int difference4 = num5 - mean;
int variance = ((difference0 * difference0) + (difference1 * difference1) + (difference2 * difference2) + (difference3 * difference3) + (difference4 * difference4)) / 5;
double sdeviation = sqrt(variance);
printf("the mean of the array is %d\n",mean);
printf("the variance of the array is %d\n",variance);
printf("the standard deviation of the array is %f\n",sdeviation);
return(0);
}

My program prints 0 instead of the expected number

So I made a function that returns a value which is the connection (sum) of 2 numbers that the user gives. But everytime I enter these 2 numbers, the result is somehow always 0.
float connection(int num1, int num2, float result)
{
result= num1 + num2;
return (result);
}
int main()
{
int num1= 0;
int num2= 0;
float result= 0.0;
printf("\nChoose the first number you'd like to connect: ");
scanf("%d", &num1);
getchar();
printf("choose the second number you'd like to connect: ");
scanf("%d", &num2);
connection(num1, num2, result);
printf("The result is: %f", result);
}
The problem here is (I believe) that you expect the argument result you pass to the function to change value. That's not how C works, instead all arguments are passed by value and the variable result inside the called function is a local variable which has no connection to the result variable in the calling function. Changing one variable will not affect the other.
Instead use the value the function returns:
result = connection(num1, num2, result);
Of course, this means passing result as an argument is totally meaningless, and you don't even need it in the function:
int connection(int num1, int num2)
{
return num1 + num2;
}
Also note that I changed the return-type, as adding two integers will never result in a floating-point number.
On a side-note to modify the argument means you have to pass it by reference, which is not supported by C. It can be emulated though, by using pointers:
void connection(int num1, int num2, int *result)
{
*result = num1 + num2;
}
Then call it as
int result;
connection(num1, num2, &result);
You are mixing up two possibilities: returning a value and changing a variable by passing it to a method as a reference.
This is how to return a value (in this case, you don't need the result parameter):
float connection(int num1, int num2)
{
float result= num1 + num2;
return result;
}
...
result = connection(num1, num2);
This is how to pass a variable as a reference (in this case you don't need a return value):
void connection(int num1, int num2, float *result)
{
*result= num1 + num2;
}
...
connection(num1, num2, &result);
I think forgot to assign your result back to your variable:
connection(num1, num2, result); // returned value is missed
result = connection(num1, num2, result); // returned value saved
If, instead, you want your function to modify the variable, C is passed by value so you need some pointers:
void connection(int num1, int num2, float *result)
{
*result = num1 + num2;
}
connection(num1, num2, &result);
Simply make your function call pass by reference
#include<stdio.h>
float connection(int *num1, int *num2, float *result)
{
*result= *num1 + *num2;
return (*result);
}
int main()
{
int num1= 0;
int num2= 0;
float result= 0.0;
printf("\nChoose the first number you'd like to connect: ");
scanf("%d", &num1);
getchar();
printf("choose the second number you'd like to connect: ");
scanf("%d", &num2);
connection(&num1, &num2, &result); //Function Called by reference
printf("The result is: %f", result);
}
For further details on function calls Read It

Floating-point exception from fraction simplification program in C

When I run the following code, I always get a floating-point exception. How can I fix it?
#include <stdio.h>
//Global Variables
int num, denom, num1, denom1;
void simplify(int *numerator, int *denominator);
int main () {
//Prompt User as to what program is
printf("Fraction Simplifier\n");
printf("===================\n");
//Ask User for Numerator and Denominator
printf("Numerator: ");
scanf("%d", &num);
printf("Denominator: ");
scanf("%d", &denom);
//Call Function
simplify(&num1, &denom1);
//Display final output
printf("%d / %d = %d / %d", num, denom, num1, denom1);
return 0;
}
//Simplify function
void simplify(int *numerator, int *denominator)
{
num = num1;
denom = denom1;
num1 = num1 / num1;
denom1 = denom1 / num1;
num1 = *numerator;
denom1 = *denominator;
}
It looks as if num1 is never initialized. It will be zero, which will result in a division by zero.
Your simplify function is flawed. Here's what it means when you are calling simplify:
call simplify, passing the address of num1 and denom1
And here's what your code inside of simplify means:
num = num1; /* Assign the value of num1 to num, meaning set num to 0. */
denom = denom1; /* Assign the value of denom1 to denom, meaning set denom to 0. */
num1 = num1 / num1; /* Divide num1 (which is 0) by num1 (which is 0). Error! */
You can simplify your program and make it easier to understand by eliminating your global variables. This will also help you to correct your errors. Here's a rewrite:
#include <stdio.h>
void simplify(int numerator, int denominator, int* newNumerator, int* newDenominator);
int main () {
int num, denom, num1, denom1;
/* Do your input code */
//Call Function
simplify(num, denom, &num1, &denom1);
//Display final output
printf("%d / %d = %d / %d", num, denom, num1, denom1);
return 0;
}
//Simplify function
void simplify(int numerator, int denominator, int* newNumerator, int* newDenominator)
{
int simplifiedNumerator;
int simplifiedDenominator;
/* Calculate your results.. left out your original code, which calculates incorrectly */
/* You will refer to the ints numerator and denominator */
/* Assign your results */
*newNumerator = simplifiedNumerator;
*newDenominator = simplifiedDenominator;
}
Notice that simplify now has four parameters. The first two are the values you want to use in the calculation (we don't need pointers), and the pointers are only used to assign the results to the addresses passed in.

Resources