Whats wrong with this program - Output of a series

This is a discussion on Whats wrong with this program - Output of a series within the C Programming forums, part of the General Programming Boards category; Code: /* Write a program to add first seven terms of the following series using a for loop: (1/1!) + ...

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    47

    Whats wrong with this program - Output of a series

    Code:
    /*
    Write a program to add first seven terms of the following series using a for loop:
    
      (1/1!) + (2/2!) + (3/3!) + .....
    
    
    */
    
    
    #include<stdio.h>
    main()
    {
    	float result, temp_calc, num, temp, factorial;	
    
    	for (num=1; num<=7; num++)
    	{
    		for (temp=1; temp<=num; temp++)
    		{
    			
    			factorial = temp*temp-1;
    
    			temp_calc = (num/factorial);
    
    					
    
    		}		
    			
    			
    	}
    		result=result+temp_calc;
    		
    	
    		printf("(1/1!) + (2/2!) + (3/3!) + (4/4!) + (5/5!) + (6/6!) + (7/7!) = %f", result);
    }
    I don't know..but I am not getting the expected output here.

  2. #2
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    Code:
    factorial = temp*temp-1;
    So when temp is <= num @ 7, factorial is going to be 7 * 6. When temp = 1, you divide by 0. result = result + temp_calc should be inside your 1st loops body, after the 2nd, and you should initialize result = 0; You should figure out a better way to determine the factorial of a number.

  3. #3
    Registered User
    Join Date
    Jan 2006
    Posts
    47
    Thanks for bringing me back on track..got it now

    Done a few changes...with the factorial thing...

    Code:
    result=0;
    
    for (num=1; num<=7; num++)
    	{
    		for (temp=1, factorial=1; temp<=num; temp++)
    		{
    			
    			factorial = factorial*temp;
    
    			temp_calc = (num/factorial);
    
    					
    
    		}	
    		
    		result=result+temp_calc;
    			
    			
    	}

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Basic C input output program help
    By trevordunstan in forum C Programming
    Replies: 2
    Last Post: 01-27-2008, 06:41 PM
  2. How do you read gzip output from 'C' program?
    By brett in forum C Programming
    Replies: 5
    Last Post: 03-13-2006, 12:01 AM
  3. Base converter libary
    By cdonlan in forum C++ Programming
    Replies: 22
    Last Post: 05-15-2005, 02:11 AM
  4. Replies: 10
    Last Post: 02-17-2005, 09:27 PM
  5. Wrong output.
    By doampofo in forum C Programming
    Replies: 2
    Last Post: 03-13-2003, 12:23 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21