Program for AVERAGE and FACTORIAL

blade's Avatar, Join Date: Sep 2010
Newbie Member
Please give the program code of this problems:

1. Enter a number (x) and get the average of all numbers from 1 to x.
2. Enter a number (x) and print the factorial of the number.
Program will look like this:
Enter value: 4
4 24
-Exit when the value entered is zero (0).
factorial = (n)*(n-1)*(n-2)
ex: 4!=4*3*2*1

* I dont have any clue on number 2 on how to do it.
*This two numbers need a loop (for).
* I tried number 1 but it's not right, anyway here is the program code i did:
Code:
#include <stdio.h> 
#include <conio.h> 
int main() 
{ 
int x,y; 
float z; 
clrscr(); 
printf ("\nEnter a number:\t"); 
scanf ("%d",&x); 
for (y=z;y>0;y--); 
z=(y+z)/(x); 
printf ("\n\nThe average of all numbers from 1 to %d is %f",x,z); 
getch(); 
return(0); 
}

*THANKS in advance.

Last edited by shabbir; 16Sep2010 at 08:42.. Reason: Code blocks
virxen's Avatar, Join Date: Nov 2009
Pro contributor
exercise 1

Code:
#include <stdio.h>

int main(){
    int x=0,y=0;
    float z=0;//always initialize variables in the beginning
    while (x<=0){//number must be greater or equal to 1
        printf ("\nEnter a number:\t");
        scanf ("%d",&x);getchar();//always after a scanf
    }
    for (y=1;y<=x;y++)
        z+=y;//use the for loop from 1 to given number,store the total sum of these numbers in z
    z/=x;//after exiting the loop divide result with total numbers
    printf ("\n\nThe average of all numbers from 1 to %d is %f",x,z);
    getchar();
    return 0;
blade like this
blade's Avatar, Join Date: Sep 2010
Newbie Member
Quote:
Originally Posted by virxen View Post
exercise 1

Code:
#include <stdio.h>

int main(){
    int x=0,y=0;
    float z=0;//always initialize variables in the beginning
    while (x<=0){//number must be greater or equal to 1
        printf ("\nEnter a number:\t");
        scanf ("%d",&x);getchar();//always after a scanf
    }
    for (y=1;y<=x;y++)
        z+=y;//use the for loop from 1 to given number,store the total sum of these numbers in z
    z/=x;//after exiting the loop divide result with total numbers
    printf ("\n\nThe average of all numbers from 1 to %d is %f",x,z);
    getchar();
    return 0;
thanks
virxen's Avatar, Join Date: Nov 2009
Pro contributor
for the factorial send the code you tried to help you.