3
/* A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number: (1) Without using recursion (2) Using recursion */ #include<stdio.h> #include<conio.h> void main() { long int num,s=0,ch,sum; clrscr(); printf("Enter any number: "); scanf("%ld",&num); printf("\n\nChoose: 1: obtain sum of digits non-recursively\n\n"); printf(" 2: obtain sum of digits recursively\n\n\n"); printf("Your choice: "); ch=getche(); switch(ch) { case '1': while(num!=0) { s=s+(num%10); num=num/10; } printf("\n\n\nsum of digits = %d\n",s); break; case '2': s=sum+num;

New microsoft office word document

Embed Size (px)

Citation preview

Page 1: New microsoft office word document

/* A 5-digit positive integer is entered through the keyboard, write a function to calculate sum of digits of the 5-digit number:(1) Without using recursion(2) Using recursion */

#include<stdio.h>#include<conio.h>void main() {

long int num,s=0,ch,sum;clrscr();

printf("Enter any number: ");scanf("%ld",&num);

printf("\n\nChoose: 1: obtain sum of digits non-recursively\n\n");printf(" 2: obtain sum of digits recursively\n\n\n");

printf("Your choice: ");ch=getche();

switch(ch) {

case '1':

while(num!=0) {

s=s+(num%10);

num=num/10;

}

printf("\n\n\nsum of digits = %d\n",s);

break;

case '2':

s=sum+num;

printf("\n\n\nSum of digits = %d\n",s);break;}

getch();

}

sum(long n) {

Page 2: New microsoft office word document

static s=0;

if(n==0)return s;

else {

s=s+n%10;n=sum(n/10);

return n;

}

}

Out Put

/* Write a recursive function to obtain the first 25 numbers of a Fibonacci sequence. In a Fibonacci sequence the sum of two successive terms gives the third term. Following are the first few terms of the Fibonacci sequence:1 1 2 3 5 8 13 21 34 55 89... */

#include<stdio.h>#include<conio.h>void main() {

unsigned i,num=25,c=1,fib;clrscr();

for(i=0;i<num;i++) {

printf("%u ",fib*c);

c++;}

Page 3: New microsoft office word document

getch();}

fib(unsigned n) {

if(n==0)return 0;

if(n==1)return 1;

else

return fib(n-1)+fib(n-2);

}

Out Put