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;
}
}
Related
So I'm coding in C and compiling with gcc, I was attempting to create a simple code to display the Fibonacci sequence, you can input the amount of digits of the sequence you'd like to be displayed. Instead of the expected 0 1 1 2 3 5 8 etc. I get 0 1 1 2 3 4 5 6 7 etc. And I can't figure out why, if I remove the second "while" from the code, it works as intended, but I don't understand why. Do variables lose their values if they're inside multiple "while"s? Please help me figure this out. Again I'm a beginner so try to keep it simple.
My code:
#include <stdio.h>
int main()
{
int num, num1 = 0, num2 = 1, cont = 0;
printf("Insert the amount of digits of the Fibonacci sequence you'd like to display: \n");
scanf("%d", &num);
if(num == 1){
printf("%d ", num1);
}
if(num >= 2){
printf("%d ", num1);
printf("%d ", num2);
}
while(cont < num - 2){
num1 = num1 + num2;
printf("%d ", num1);
cont++;
while(cont < num - 2){
num2 = num1 + num2;
printf("%d ", num2);
cont++;
}
}
return 0;
}
The answer to your main question is no. Variables work like this: We declare a variable somewhere in our code. This variable has a name, a value (we either initialize it or it has a random value) and an address in memory. Your program has access to this variable within the block which this variable has been declared. In this particular example, because you declared the variable cont in the main function, that means wherever you change the value of this variable in the main function that change takes place.
The problem in your code is that the variable num1 doesn't change accordingly and, in the whole program, has the value 1. That is the reason why the values printed change by 1. A piece of code that would solve this problem is the following:
#include <stdio.h>
int main()
{
int num, num1 = 0, num2 = 1, cont = 0,temp;
printf("Insert the amount of digits of the Fibonacci sequence you'd like to display: \n");
scanf("%d", &num);
if(num == 1){
printf("%d ", num1);
}
if(num >= 2){
printf("%d ", num1);
printf("%d ", num2);
}
while(cont < num - 2){
temp = num2;
num2 = num1 + num2;
num1 = temp;
printf("%d ", num2);
cont++;
}
return 0;
}
This code just stores the value of num2 in a variable temp, so we don't lose the value of num2 because we want to modify it and the new value of variable num1 must be the old value of variable num2.
#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;
}
Sorry for being such a novice.
For this question I used C language, and the libraries stdlio.h and stdlib.h.
Question
So a question is asking me to:
Open a text file named 'numbers.txt' in read mode. This text file
has 6 integers in it.
Read the 6 integers from that text file using a loop.
Calculate and display the total and average of those 6 integers.
The text file 'numbers.txt' holds the integers: 5, 10, 15, 20, 25.
Here's my code:
FILE *n;
n = fopen("numbers.txt", "r");
int a, num, sum = 0;
float avg;
for (a = 0; a < 6; a++) {
fscanf(n, "%d", &num);
sum = sum + num;
}
avg = sum / (a - 1);
printf("Sum = %d\nAverage = %.2f\n\n", sum, avg);
fclose(n);
Another variation of the question is that I need to use a while loop to read the integers in the text file.
Here's my code for that:
FILE *n;
n = fopen("numbers.txt", "r");
int a = 0, num, sum = 0;
float avg;
while (fscanf(n, "%d", &num) != EOF) {
fscanf(n, "%d", &num);
sum = sum + num;
a++;
}
avg = sum / a;
printf("Sum = %d\nAverage = %.2f\n\n", sum, avg);
fclose(n);
Problem
When I run each of the above programs, I expect this output:
Sum = 75
Average = 15.00
However I get this instead (for the first code):
Sum = 100
Average 20.00
And this (for the second code):
Sum = 55
Average = 18.00
How am I able to get the correct output from both of these programs?
Again I apologise for how basic this question is. Nonetheless, any help would be appreciated.
In the first one, you tried to read one-to many numbers, but since there were only 5 numbers, the last number was added twice to your sum, so you ended up adding an extra 25 to the sum to get 100.
In the second code, after reading the last number, the end of the file was reached, so your code did not get the opportunity to add the last read number, so you missed adding 25 to your sum.
You were much closer with your first code, just change the for-loop to only iterate 5 times
Here is my observation,
Case 2 : The problem is here in below two line of code
while (fscanf(n, "%d", &num) != EOF) { /* this is fine, scanf() stored read int into num */
fscanf(n, "%d", &num); /* this is not needed as overwrites previous num, just remove it */
/* some code */
}
Also this
avg = sum / a;
doesn't get you expected result as sum/a results in integer but you are assigning it to avg which is float. One way to overcome this is to do typecasting like below
avg = (float)(sum / a);
Sample code :
int main(void) {
FILE *n;
n = fopen("numbers.txt", "r"); /* always do error handling to make more robust code */
if(n == 0) {
#TODO error handling */
}
int a = 0, num, sum = 0;
float avg;
while (fscanf(n,"%d", &num) != EOF) {
//fscanf(n, "%d", &num);// remove this
sum = sum + num;
a++;
}
avg = (float)(sum / a);// typecast it
printf("Sum = %d\nAverage = %.2f\n\n", sum, avg);
fclose(n);
return 0;
}
Case 1 : Here
for (a = 0; a < 6; a++)
rotating loop fixed number of times may not be a problem for now but it creates issue when you don't know in advance how many integer number file having. so better rotate loop until EOF. For e.g
for (a = 0; ; a++) {
if(fscanf(n, "%d", &num) == 1) /* compare with return value */
sum = sum + num;
else
break;
}
I am working on a program to organize a list of numbers from a file and output these numbers in a easier to read format. Such as a file called Counting.txt containing the numbers:
11
1 1 2 3 4 4 4 4 5 5 7
and I want it to output:
1x2 2x1 3x1 4x4 5x2 7x1
The formula for output being vXc, where v is the number and c is the number of times it occurs. But my current program only outputs it as:
1x1 2x1 3x1 4x1 4x1 4x1 4x1 5x1 5x1 7x1
I believe there is a small error in my for loop that doesn't allow me to change my c variable, or the number indicating how many times the actual number occurs. Can anyone help?
My code:
#include <stdio.h>
int main () {
FILE* file = fopen("counting.txt", "r");
int total_num, count = 1, num, num2, i;
if (file == NULL) {
printf("Did not find counting.txt file.\n");
}
fscanf(file, "%d", &total_num);
fscanf(file, "%d", &num);
for (i = 1; i < total_num; i++) {
fscanf(file, "%d", &num);
if (num2 == num) {
count = count + 1;
} else {
printf("%dX%d ", num, count);
count = 1;
}
}
return 0;
}
In the loop you read into num instead of num2. So in general num2 is undefined. You also need at the end of each loop's iteration to assign to num the value of num2.
Also when you print the number of repetitions you should refer to the old value and not the current one, since you don't know if the current number will be followed by other equal numbers.
So you could change your loop to:
for (i=1; i< total_num; i++) {
fscanf(file, "%d", &num2);
if (num2 == num) {
count = count + 1;
}
else {
printf("%dX%d ", num, count);
count = 1;
}
num = num2;
}
printf("%dX%d ", num, count);
#include <stdio.h>
#include <conio.h>
main() {
float num1, num2, num3, num4, num5, sum;
printf("Enter a Number between");
fflush;
scanf("%f",&num1);
fflush;
printf("Enter a Number between");
scanf("%f",&num2);
fflush;
printf("Enter a Number between");
scanf("%f",&num3);
fflush;
printf("Enter a Number between");
scanf("%f",&num4);
fflush;
printf("Enter a Number between");
scanf("%f",&num5);
fflush;
sum = num1 + num2 + num3 + num4 + num5;
printf("The sum of the five numbers you have entered is %f",sum);
getch();
}
I am a newbie in c programming. We have an assignment and I have created the above code. But we need a shorter solution. The user must input five numbers and display the sum. Can you please help me to translate this code using do while function or post test loop. Thank you very much in advance!
You can use a cycle to read 5 values and accumulate their sum. I prefer to leave you with this hint only because this seems like a homework assignment. You may reuse the same variable reading 5 different inputs and have a separate variable in which you accumalate the sum. You can also use a for cycle instead of the do... while you seem to be using.
Use a for loop to input numbers (say 5 in this case) and add it with value stored in sum in each iteration.
int num , sum = 0;
for(int i = 0; i < 5; i++)
{
scanf("%d", &num);
sum += num;
}
When someone asks me to do their homework for them, I enjoy coming up with a slightly convoluted, but functionally correct answer. :)
#include <stdio.h>
#include <conio.h>
int main()
{
float numbers[5] = {0.0F};
float sum = 0.0F;
int count = 5;
while(count --> 0)
{
printf("Enter a number for entry %d: ", 5-count);
scanf("%f",numbers+count);
sum += numbers[count];
}
printf("The sum is %f\n", sum);
getch();
return 0;
}