So I was trying to solve the FizzBuzz challenge in various languages using the string method to improve the code. I got stuck in C because things work differently here. This is my code, I'm getting errors, can anyone explain them to me and help to get the correct code.
#include<stdio.h>
#include<string.h>
int main()
{
int i,n;
char output;
printf("Enter Range: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
if(i%3==0)
strcat(output,"Fizz");
if(i%5==0)
strcat(output,"Buzz");
if(output=="\0")
strcat(output,i);
printf("\ni");
}
printf("\nEnd.\n");
return 0;
}
Thanks.
@Ashwini Singh
There are some mistakes in your code ,
1) You declared the output
variable as char datatype & concatenate string in Fizz/Buzz
in char . so how can be value of string(which is a array of character) placed in character output
.
2) You are concatenate the integer value i
with character output
e.g strcat(output,i)
. we need to first typecast the integer value i
in to char/string datatype & then concatenate with output
.
The condition of the FizzBuzz programs are,
1) If number is multiple of 3 then add Fizz in the resultant string
2) If number is multiple of 5 then add Buzz in the resultant string
3) If number is neither multiple of 3 nor multiple of 5 then add number in the resultant string
Code :
#include<stdio.h>
#include<string.h>
int main()
{
int i,n;
char output[100]=" ";
printf("Enter Range: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
char s[] = {'0' + i, '\0'};
if(i%3==0)
strcat(output,"Fizz ");
else if(i%5==0)
strcat(output,"Buzz ");
else
strcat(strcat(output,s)," ");
}
puts(output);
return 0;
}
Output :
Enter Range: 10
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz