#include <stdio.h>
int main() {
// Write C code here
int a, b = 1, c, d;
printf("Value of a:");
scanf("%d", &a);
while (b < a) {
c = b * a;
printf("%d", c);
b++;
}
return 0;
}
I was trying to find the factorial of a number but I don't know how to add the values.
It's written in C.
There are some problems in your code:
the expression c = b * a; computes an intermediary result, but not a useful one. You should compute c = c * b; multiplying the current factorial by the next integer to get the next factorial.
for the expression c = c * b; you must initialize c to 1 before the beginning of the loop.
printf("%d", c); outputs just the digits. You should output a space or a newline to separate the numbers.
scanf("%d", &a) may fail to convert a number from user input, for example if the user typed A. a will stay uninitialized, causing undefined behavior when you use it in further expressions. You should test that scanf() succeeded and returned 1, the number of successful conversions.
Here is a modified version:
#include <stdio.h>
int main() {
int a, b = 1, c = 1;
printf("Value of a:");
if (scanf("%d", &a) == 1) {
while (b < a) {
c = c * b;
printf("%d\n", c);
b++;
}
}
return 0;
}
It is recommended to use the for loop to group the initialization, increment and test of the loop variable in a single place:
#include <stdio.h>
int main() {
int a;
printf("Value of a:");
if (scanf("%d", &a) == 1) {
int c = 1;
for (int b = 1; b < a; b++) {
c = c * b; // one can also write c *= b;
printf("%d\n", c);
}
}
return 0;
}
Related
The Fibonacci series is not obtained on running this program. The whole process terminates after giving input in scanf.
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int);
int main()
{
int n, i = 0, c;
printf("Print the fibonacci series");
scanf("%d", n);
for (c = 1; c <= n; c++)
{
printf("%d\n", fibonacci(i));
i++;
}
return 0;
}
int fibonacci(int n)
{
if (n = 0)
return 0;
else if (n = 1)
return 1;
else
return (fibonacci(n - 1) + fibonacci(n - 2));
}
With scanf you need the give the address of the variable.
scanf("%d",&n); <= need to give the address of the integer
You can find some examples here:
http://www.cplusplus.com/reference/cstdio/scanf/
As you have already been told in Robert's answer, scanf expects an address for each format specifier. So, if format specifier %d is provided, the address of an integer is expected: scanf will write the value there.
If n is the variable containing the integer, &n is its address. Passing something that is not an address causes trouble: it is undefined behavior and will likely cause a segmentation fault.
There are also some problems in your Fibonacci generator. I suppose you want to print the n-th number in the sequence, but you iterate n times calling fibonacci() function (which only returns the last value) always with parameter i, which value is 0.
In fibonacci function you try to check for the exit conditions, but pay attention:
if (n = 0)
return 0;
doesn't check the value of n; it performs an assignment (the value of n will be 0 and the condition will be false). So it will proceed to the next "test"
if (n = 1)
return 1;
It is an assignment as well, 1 is assigned to n so the condition is true and 1 is returned. That's why you see 1 n times.
In order to make it work
correct the scanf issue
pass c to fibonacci()
correct the function so that the value is tested (== instead of =)
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int);
int main()
{
int n, c;
printf("Print the fibonacci series\n");
scanf("%d", &n);
for (c = 1; c <= n; c++)
{
printf("%d\n", fibonacci(c));
}
return 0;
}
int fibonacci(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return (fibonacci(n - 1) + fibonacci(n - 2));
}
You missed the & sign in the scanf statement, and also , I think you got confused with the assignment operator = and logical equal ==, in the Fibonacci function.
#include <stdio.h>
#include <stdlib.h>
int fibonacci(int);
int main()
{
int n, i = 0, c;
printf("Print the fibonacci series");
scanf("%d", &n);
for (c = 1; c <= n; c++)
{
printf("%d\n", fibonacci(i));
i++;
}
return 0;
}
int fibonacci(int n)
{
if (n == 0)
return 0;
else if (n == 1)
return 1;
else
return (fibonacci(n - 1) + fibonacci(n - 2));
}
I'm practicing programming in c, but I've come across an issue that I can't seem to figure out. I have a printf statement with two markers for two different int values. No matter what the first int is, it prints 0, but the second int prints normally. Here's the code:
#include <stdio.h>
#include <stdlib.h>
int a, temp;
int toBinary();
int toDecimal();
int main()
{
char c;
for(;;)
{
scanf("%d",&a);
scanf(" %c",&c);
switch(c)
{
case 'a' :
printf("%d converted to binary: %d\n",a,toBinary());
break;
case 'b' :
printf("%d converted to decimal: %d\n",a,toDecimal());
break;
case 'c' :
printf("EXIT\n");
return 0;
break;
default :
printf("ERROR c value: %c\n",c);
return 0;
}
}
}
int toBinary()
{
if (a == 0)
return 0;
else
{
temp = a;
a /= 2;
return (temp % 2 + 10 * toBinary());
}
}
int toDecimal()
{
int res=0, base = 1, rem;
while (a > 0)
{
rem = a % 10;
res = res + rem * base;
a /= 10;
base *= 2;
}
return res;
}
The problem is that the printf statements in the first two cases ignore the actual value of int a, but it works normally for the value of the two functions. I'm not sure what's wrong, as a is given a value before, in the scanf statement, and I am using the proper marker in the text.
Since the order of argument evaluation is unspecified, this is undefined behavior.
The simplest fix would be to save a copy of a in a different variable, and print that.
int a_copy = a;
printf("%d converted to binary: %d\n",a_copy,toBinary());
But it would be better if the function didn't use a global variable in the first place.
int toBinary(int a)
{
if (a == 0)
return 0;
else
{
return (a % 2 + 10 * toBinary(a / 2));
}
}
Then you would do:
printf("%d converted to binary %d"\n, a, toBinary(a));
If a is modified in either toBinary() or toDecimal(), it's an UB.
The order of argument evaluation in one function call is unspecified. Some compilers evaluate them L->R (like GCC), some others do it R->L (like VC).
Try this and you'll find it out:
printf("%d %d %d\n", a, toBinary(), a);
printf("%d %d %d\n", a, toDecimal(), a);
The value of a in the function toBinary() gets reduced to 0 due to presence of the statement a /= 2; and it is getting recursively executed.
Hence your printf statement prints 0 for the value of a.
As #Barmar suggested, it's a good coding practice to use local variables rather than global variables inside a function.
I am solving the greedy algorithm of from the cs50 course without using the cs50 header file. I have written some code. It works fine with numbers as input but when I give it a string or chars as input, it does not prompt me back. I do not know how to solve this issue.
#include <stdio.h>
int main()
{
float c;
int C, nQ, rem1, nD, rem2, nN, rem3;
do
{
printf("O hai! How much change is owed? ");
scanf("%f", &c);
}
while(c<0);
C = c * 100;
nQ = C / 25;
rem1 = C % 25;
nD = rem1 / 10;
rem2 = rem1 % 10;
nN = rem2 / 5;
rem3 = rem2 % 5;
printf("%d\n", nQ+nD+nN+rem3);
}
This is because a float cannot accept a string. You are expecting c to hold other data types when it is just a float variable.
I would suggest you to take input as a string and use atof() to check whether the input is a floating type or not. Something like this:
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
int main()
{
float c;
int C, nQ, rem1, nD, rem2, nN, rem3;
char str[10];
do
{
printf("O hai! How much change is owed? ");
scanf("%s", str);
}
while(atof(str) > 0);
c = atof(str);
C = c * 100;
nQ = C / 25;
rem1 = C % 25;
nD = rem1 / 10;
rem2 = rem1 % 10;
nN = rem2 / 5;
rem3 = rem2 % 5;
printf("%d\n", nQ+nD+nN+rem3);
}
This makes sure that you are using a do while loop only for floating point numbers.
You are expecting c to be negative after your entered a sequence that is not a floating point number.
This is not a valid assumption. If scanf fails, the value of the variable read is undefined.
You need to check the return value of scanf to know if the read was indeed successful. So you can change the code to.
int read;
do
{
printf("O hai! How much change is owed? ");
read = scanf("%f", &c);
if (read == EOF){
// Appropriate error message.
return -1;
}
if (read != 1)
scanf("%*s");
}
while(read != 1 || c < 0);
Now, if the scanf doesn't read a float, it will return 0 and you can continue prompting.
Demo here
Why this code doesn't print the full array.How to correct the code or improve to print the full array
int main(void) {
float value[MAX], a;
int bit, i;
int group[10];
bit = 0;
do {
scanf("%f", &a);
value[bit] = a;
bit++;
} while (a == '\n');
for (i = 0; i < bit; i++)
printf("%f", value[i]);
}
Change the stop condition of your reading from
while(a=='\n');
to some int/float value.
As mentioned by someprogrammerdude, variable "a" never be equal to '\n'.
My instructor has asked us to follow the variables through this code and determine when the variables change. He says the inputs should be
8, 4, 2, 1
I have compiled and run the code to he me understand it but it doesn't stop. It just ouputs "Feed me two numbers please:" over and over. Any help is greatly appreciated.
#include <stdio.h>
main ()
{
int a;
int b;
int c=0;
int d=0;
int e=0;
int f=0;
while (c == 0 || a + b !=0){
printf("Feed me two numbers please: \n");
scanf ("%d %d", &a, &b);
if (c == c + 1){
printf("Welcome to my world!\n\n");
}
if (c = 0){
d = a + b;
e = d;
}
else if (a + b > d){
d = a + b;
}
else if (a + b < e){
e = a + b;
}
if (a < f){
f=a;
}
c = c + 1;
}
printf("Now hear this:%d %d\n\n", d, e, f);
}
In
if (c = 0)
you're assigning 0 to c, the expression of the assignment returns the assigned value, so the expression will be always evaluated to false as it's equivalent to if(0), it should be if(c == 0).
Also
if (c == c + 1)
doesn't make any sense, what exactly do you mean? I think it should be c > 0.
In all cases, you should use the debugger, it can save you a lot of time, and will help you to really understand your code.