I have to write code that displays the Fibonacci sequence to the user desired number of terms and must also use a while loop. I'm not sure why this code isn't working.
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int max;
printf("Enter the max term of the Fibonacci Sequence:\n");
scanf("%i", &max);
int a=0;
int b=0;
a=2;
while(a<max) {
if((a==0||a==1))
{
printf("%i\n", &a);
++a;
}
else if(a>1)
{
a=(a-1)+(a-2);
printf("%i\n", &a);
++a;
}
}
return 0;
}
You can try this.
#include <stdio.h>
#include <stdlib.h>
int main (void) {
int max;
printf("Enter the max term of the Fibonacci Sequence:\n");
scanf("%i", &max);
int n=0;
int a=0;
int b=1;
int next;
while(n<max) {
if ( n <= 1 )
{
next = n;
n++;
}
else
{
next = a + b;
a = b;
b = next;
n++;
}
printf("%d\n", next);
}
return 0;
}
issues with your code:
following declaration & initialisation, you set a=2 => it won't take the true branch of the if statement -- '0' will not be printed in your result.
a=(a-1)+(a-2); i.e a = 1
then you are doing ++a; => a == 2. thus it again else statement with same a==2.
hence it will print the same value and loop executes infinitely.
In the very beginning of your program (before the while loop) a is 2 (see the line a=2).
And in the while loop you do following:
a=(a-1)+(a-2); // a = 2-1+2-2 i.e. a = 1
and right after it
++a; // a == 2
So, after it a==2 again. This loop never ends.
But it is technical problem. More important is that you are trying to calculate not Fibonacci Sequence. In the Fibonacci Sequence each subsequent number is the sum of the previous two. But in your code there is adding of not two previous numbers of Fibonacci Sequence, but previous two Natural numbers.
You have variable b, because someone told you to add it. And it was right! Just remember previous found element of the Fibonacci Sequence in b. When you know previous one element and current one, it is possible to calculate next one.
Related
Using a do...while() loop need to continuously scan for random integers that will be inputted by the user and print out its square, separated in each line. Once the inputted value is 0, it will still print out its square value but should then terminate the loop afterwards.
this is the sample input:
2,
6,
0
this is the sample output:
4,
36,
0
This is my code so far:
#include <stdio.h>
int main() {
int a;
int num;
int b;
do {
scanf("%d", &a);
} while (a != 0);
while (a > num) {
num++;
if (num == a) {
b = num * a;
printf("%d", b);
}
}
}
I think this might help:
#include <stdio.h>
int main() {
int a;
do {
scanf("%d", &a);
printf("%d\n", a * a);
} while (a != 0);
}
The first issue I can see in your code is that the variable num is not initialized to a specific value, so num > a is meaningless and the second loop won't work correctly.
The second is that the a variable can store only one value at a time and that's why the value users enter will be replaced with the last value they entered, and finally, you can only print the square of a number out.
A very simple solution is that you can want the user to enter as many numbers as they want (and also 0 as the last number), press Enter at the end. After that, only call printf to print the square of them on the screen.
#include <stdio.h>
int main()
{
int a;
do
{
scanf("%d", &a);
printf("%d ", a * a);
} while(a != 0);
return 0;
}
#include <stdio.h>
int even_numbers_sum(){
int d;
for(d=0;d<=100;d++){
if(d%2==0){
printf("\n this is even number loop %d",d);
}
}
int sum;
sum=sum+d;
printf("\n the value of total sum of the loop %d",sum);
return sum;
}
int main(){
even_numbers_sum();
}
my main aim is to calculate the sum of all the elemets of for loop i took a for loop and described its value and put a equation (if) to pass anynumber if its only even other wise it will not work and i have to add all those even number till 100 how do i do it
Initialised sum to 0 at the beginning. Changed the return type of the function to void as int was unnecessary. Sum has to be incremented in the if statement.
#include <stdio.h>
void even_numbers_sum(){
int d;
int sum=0;
for(d=0;d<=100;d++){
if(d%2==0){
printf("\n this is even number loop %d",d);
sum=sum+d;
}
}
printf("\n the value of total sum of the loop %d",sum);
}
int main(){
even_numbers_sum();
}
look the following code. I've written this code for any number if you want to change the upper bound instead of 100 , you just have to pass the integer to the function i.e. if you want to get the sum of all even integers from 0 to 100, you have to pass 100 while calling the function.
#include <stdio.h>
void even_numbers_sum(int i){
int d;
int sum=0;
for(d=0;d<=i;d+=2){
printf("\n this is even number loop %d",d);
sum=sum+d;
}
}
printf("\n the value of total sum of the loop %d",sum);
}
int main(){
even_numbers_sum(100);
return 0;
}
1.first change is here in function declaration and definition you have to write int i in the parentheses.
void even_numbers_sum(int i)
2.Secondly there is no need to put the condition if you want to start from 0. it can be done by simply increment d by 2.
for(d=0;d<=i;d+=2)
3.Your main method has return type int so there should be some integer returned.
return 0;
I hope this will help you to solve your problem. If there is anything which you want to ask I'll be glad to help you.
Firstly, you should initialize sum as 0 at begin. sum may be not 0 without initialization.
Secondly, in your code, sum will be only add with the final even number (100), not add each each even number from 0 to 100.
A correct example as below:
#include <stdio.h>
int even_numbers_sum()
{
int d, sum = 0; // initialize sum as 0
for (d = 0; d <= 100; d++) {
if (d % 2 == 0) {
printf("\n this is even number loop %d", d);
sum = sum + d; // add each even number to sum
}
}
// sum=sum+d; // This line code will add final even number and sum
printf("\n the value of total sum of the loop %d", sum);
return sum;
}
int main()
{
even_numbers_sum();
}
Task is to display the array that has no repetitions based on some user generated input.
I'm trying to compare the number with every number before it, if the equality happens, a=1, it should skip it. Code doesn't return anything.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int X[30],Y[30],i,j,k=0,a,N;
printf("Length of the vector: ");
scanf("%d",&N);
printf("Input the numbers: ");
for(i=0;i<N;i++)
scanf("%d",X+i);
Y[0]=X[0];
for(i=1;i<N;i++){
for(j=i-1;j>=0;j--)
if(X[i]=X[j])
a=1;
if(a==0){
k++;
Y[k]=X[i];
}
a=0;
}
for(i=0;i<k;i++)
printf("%d",Y[i]);
}
Three separate issues in your code block:
a is not initialized the first time through your loop. Add a line a = 0; above your loop.
Your if block reads if(X[i]=X[j]); it should be if(X[i] == X[j]) (you're missing one =)
Your final value of k is going to be one less than the total number of elements that you have. Change your final for loop to i = 0; i <= k; i++
Hey guys so I need to make a program which asks the user to enter a number as a argument and then let them know if it is a prime number or 0 otherwise. So the code I have so far is as follows but I am a little confused on how to make it run through all the possible values of the and make sure that it isn't a non-prime number. Right now what happens is that the program opens, I enter a value and nothing happens. Note: I have math in the header as I am unsure if it is needed or not at this stage.
EDIT: SO I MADE THE CHANGES SUGGESTED AND ALSO ADDED A FOR LOOP HOWEVER WHEN I GO TO COMPILE MY PROGRAM I GET AN WARNING SOMETHING ALONG THE LINES OF 'CONTROL MAY REACH END OF NON-VOID FUNCTION'. HOWEVER THE PROGRAM DOES COMPILE WHEN I GO TO ENTER A NUMBER AND HIT ENTER IRRELEVANT OT WHETHER OR NOT IT IS A PRIME NUMBER I GET AN ERROR BACK SAYING 'FLOATING POINT EXCEPTION: 8'.
EDIT 2: THE FLOATING POINT ERROR HAS BEEN FIXED HOWEVER NOW THE PROGRAM SEEMS TO THINK THAT EVERY NUMBER IS NON - PRIME AND OUTPUTS IT THIS WAY. I CAN'T SEEM TO SEE WHY IT WOULD DO THIS. I AM ALSO STILL GETTING THE 'CONTROL MAY REACH END OF NON-VOID FUNCTION' WARNING
#include <stdio.h>
#include <math.h>
int prime(int a){
int b;
for(b=1; b<=a; b++){
if (a%b==0)
return(0);
}
if(b==a){
return(1);
}
}
int main(void){
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1){
printf("%d is a prime number \n",c);
}
else
printf("%d is not a prime number\n",c);
}
1. You never initialized i (it has indeterminate value - local variable).
2. You never call function is_prime.
And using a loop will be good idea .Comparing to what you have right now.
I just modified your function a little. Here is the code
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b=2,n=0;
for(b=2; b<a; b++)
{
if (a%b==0)
{
n++;
break;
}
}
return(n);
}
int main(void)
{
int c, answer;
printf("Please enter the number you would like to find is prime or not= ");
scanf("%d",&c);
answer = prime(c);
if(answer==1)
{
printf("%d is not a prime number \n",c);
}
else
{
printf("%d is a prime number\n",c);
}
return 0;
}
Explanation-
In the for loop, I am starting from 2 because, I want to see if the given number is divisible by 2 or the number higher than 2. And I have used break, because once the number is divisible, I don't want to check anymore. So, it will exit the loop.
In your main function, you had not assigned properly for the printf() statement. If answer==1, it is not a prime number. (Because this implies that a number is divisible by some other number). You had written, it is a prime number(which was wrong).
If you have any doubts, let me hear them.
I suggest you start with trial division. What is the minimal set of numbers you need to divide by to decide whether a is prime? When can you prove that, if a has a factor q, it must have a smaller factor p? (Hint: it has a prime decomposition.)
Some errors your program had in your prime finding algorithm:
You start the loop with number 1 - this will make all numbers you test to be not prime, because when you test if the modulo of a division by 1 is zero, it's true (all numbers are divisible by 1).
You go through the loop until a, which modulo will also be zero (all number are divisible by themselves).
The condition for a number to be prime is that it must be divisible by 1 and itself. That's it. So you must not test that in that loop.
On main, the error you're getting (control reaches end of non-void function) is because you declare main to return an int.
int main(void)
And to solve that, you should put a return 0; statement on the end of your main function. Bellow, a working code.
#include <stdio.h>
#include <math.h>
int prime(int a)
{
int b;
for (b = 2; b < a; b++) {
if (a % b == 0)
return (0);
}
return 1;
}
int main(void)
{
int c, answer;
printf
("Please enter the number you would like to find is prime or not= ");
scanf("%d", &c);
answer = prime(c);
if (answer == 1) {
printf("%d is a prime number \n", c);
} else {
printf("%d is not a prime number\n", c);
}
return 0;
}
On a side note, don't use the CAPSLOCK to write full sentences. Seems like you're yelling.
Mathematically the maximum divisor of a number can be as a large as the square of it, so we just need to loop until sqrt(number).
A valid function would be:
//Function that returns 1 if number is prime and 0 if it's not
int prime(number) {
int i;
for (i = 2; i < sqrt(number); i++) {
if (a % i == 0)
return (0);
}
return 1;
}
#include<stdio.h>
int main()
{
int n , a, c = 0;
printf ("enter the value of number you want to check");
scanf ("%d", &n);
//Stopping user to enter 1 as an input.
if(n==1)
{
printf("%d cannot be entered as an input",n);
}
for(a = 2;a < n; a++)
{
if(n%a==0)
{
c=1;
break;
}
}
if(c==0 && n!=1)
{
printf("%d is a prime number \n",n);
}
else
{
if(c!=0 && n!=1)
{
printf("%d is not a prime number \n",n);
}
}
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main()
{
int x,i;
printf("enter the number : ");
scanf("%d",&x);
for ( i=2; i<x;i++){
if ( x % i == 0){
printf("%d",x);
printf(" is not prime number ");
printf("it can be divided by : ");
printf("%d",i);
break;
}[this is best solution ][1]
}
if( i>=x) {
printf("%d",x);
printf(" is prime number");
}
}
it's me again. I deleted my previous question because it was very poorly asked and I didn't even include any code (i'm new at this site, and new at C). So I need to write a program that prints out the digits smaller than 5 out of a given number, and the number of the digits.
For example: 5427891 should be 421 - 3
The assignment also states that i need to print the numbers smaller than 5 in a recursive function, using void.
This is what I've written so far
#include<stdio.h>
void countNum(int n){
//no idea how to start here
}
int main()
{
int num, count = 0;
scanf("%d", &num);
while(num != 0){
num /= 10;
++count;
}
printf(" - %d\n", count);
}
I've written the main function that counts the number of digits, the idea is that i'll assign (not sure i'm using the right word here) the num integer to CountNum to count the number of digits in the result. However, this is where I got stuck. I don't know how to extract and print the digits <5 in my void function. Any tips?
Edit:
I've tried a different method (without using void and starting all over again), but now i get the digits I need, except in reverse. For example, instead of printing out 1324 i get 4231.
Here is the code
#include <stdio.h>
int rec(int num){
if (num==0) {
return 0;
}
int dg=0;
if(num%10<5){
printf("%d", num%10);
dg++;
}
return rec(num/10);
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++)
{
scanf("%d", &a);
rec(a);
printf(" \n");
}
return 0;
}
Why is this happening and how should I fix it?
There is nothing in your question that specifies the digits being input are part of an actual int. Rather, its just a sequence of chars that happen to (hopefully) be somewhere in { 0..9 } and in so being, represent some non-bounded number.
That said, you can send as many digit-chars as you like to the following, be it one or a million, makes no difference. As soon as a non-digit or EOF from stdin is encountered, the algorithm will unwind and accumulate the total you seek.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int countDigitsLessThanFive()
{
int c = fgetc(stdin);
if (c == EOF || !isdigit((unsigned char)c))
return 0;
if (c < '5')
{
fputc(c, stdout);
return 1 + countDigitsLessThanFive();
}
return countDigitsLessThanFive();
}
int main()
{
printf(" - %d\n", countDigitsLessThanFive());
return EXIT_SUCCESS;
}
Sample Input/Output
1239872462934800192830823978492387428012983
1232423400123023423420123 - 25
12398724629348001928308239784923874280129831239872462934800192830823978492387428012983
12324234001230234234201231232423400123023423420123 - 50
I somewhat suspect this is not what you're looking for, but I'll leave it here long enough to have you take a peek before dropping it. This algorithm is fairly pointless for a useful demonstration of recursion, to be honest, but at least demonstrates recursion none-the-less.
Modified to print values from most significant to least.
Use the remainder operator %.
"The result of the / operator is the quotient from the division of the first operand by the second; the result of the % operator is the remainder. In both operations, if the value of the second operand is zero, the behavior is undefined" C11dr ยง6.5.5
On each recursion, find the least significant digit and test it. then divide the number by 10 and recurse if needed. Print this value, if any, after the recursive call.
static int PrintSmallDigit_r(int num) {
int count = 0;
int digit = abs(num % 10);
num /= 10;
if (num) {
count = PrintSmallDigit_r(num);
}
if (digit < 5) {
count++;
putc(digit + '0', stdout);
}
return count;
}
void PrintSmallDigits(int num) {
printf(" - %d\n", PrintSmallDigit_r(num));
}
int main(void) {
PrintSmallDigits(5427891);
PrintSmallDigits(-5427891);
PrintSmallDigits(0);
return 0;
}
Output
421 - 3
421 - 3
0 - 1
Notes:
This approach works for 0 and negative numbers.
First of all, what you wrote is not a recursion. The idea is that the function will call itself with the less number of digits every time until it'll check them all.
Here is a snippet which might help you to understand the idea:
int countNum(int val)
{
if(!val) return 0;
return countNum(val/10) + ((val % 10) < 5);
}
void countNum(int n, int *c){
if(n != 0){
int num = n % 10;
countNum(n / 10, c);
if(num < 5){
printf("%d", num);
++*c;
}
}
}
int main(){
int num, count = 0;
scanf("%d", &num);
countNum(num, &count);
printf(" - %d\n", count);
return 0;
}
for UPDATE
int rec(int num){
if (num==0) {
return 0;
}
int dg;
dg = rec(num/10);//The order in which you call.
if(num%10<5){
printf("%d", num%10);
dg++;
}
return dg;
}
int main(){
int n;
scanf("%d", &n);
int i,a;
for(i=0;i<n;i++){
scanf("%d", &a);
printf(" - %d\n", rec(a));
}
return 0;
}