Pages

When Programming is Life

Thursday, 5 February 2015

Find Factorial of a Number in C Programming Without Using Loops and Recursion

Find Factorial of a Number in C Programming Without Using Loops and Recursion
Find Factorial of a Number in C Programming Without Using Loops and Recursion


Do you remember in my previous tutorial I asked you guys to find the factorial of a number in another way? I mean without using Loops or Recursive function? No? Don't worry, here I'm gonna share that logic and the code of that. I know you tried many things to find the factorial but which I was talking about then is using goto. Yes using goto you can calculate the factorial of a number without Loops and Recursion. 

First lets see the code then we will discuss each line thoroughly. 



/*Find Factorial of a Number without Loops and Recursion
C Programming Code
by ©Anuran Barman.2015.All Rights Reserved.*/

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

 int n, fact=1;

   printf("enter the number for finding the factorial ");
   scanf("%d",&n);

   if(n==0)
       printf("factorial=1");
   else
    {
        a:
        if(n>0)
        {
           fact = fact * n--;
           goto a;
         }
      }
     printf("factorial = %d",fact);

getch();
return 0;
}


First here we create two variables,one to contain the number given by the user and one to hold the final factorial. After that we create a base case. if the given number is 0 then we make the factorial to give output 1. One more thing, we have initialized the fact variable to 1 as it will start multiplying the next integers from 2 to n. In the else block we make a goto statement a. We also put a condition there to make the block work again and again,like a loop, with the help of goto statement. The block of code will run till n is greater than 0.At last we successfully print the factorial of the number stored in fact variable. 

Simple enough. Hope you have understood the concept well. If you have any question regarding this code and logic behind it you can ask me in comments.

In my last tutorial I asked you guys to think why this method of calculating factorial is not so effective.Have you worked on that? Why this method does not fit all conditions? Got that point? No? Don't worry. In my following tutorial I will clarify all my questions and their answers thoroughly. Till then stay tuned with Standard Programming !!
Share this post
  • Share to Facebook
  • Share to Twitter
  • Share to Google+
  • Share to Stumble Upon
  • Share to Evernote
  • Share to Blogger
  • Share to Email
  • Share to Yahoo Messenger
  • More...

0 comments

:) :-) :)) =)) :( :-( :(( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ :-$ (b) (f) x-) (k) (h) (c) cheer

 
Posts RSSComments RSSBack to top
© 2011 Standard Programming ∙ Designed by BlogThietKe
Released under Creative Commons 3.0 CC BY-NC 3.0