Program for AVERAGE and FACTORIAL

Discussion in 'C' started by blade, Sep 15, 2010.

Joined:
Sep 15, 2010
Messages:
2
0
Trophy Points:
0
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);
} ```

Last edited by a moderator: Sep 16, 2010
2. virxenNew Member

Joined:
Nov 24, 2009
Messages:
387
90
Trophy Points:
0
exercise 1

Code:
```#include <stdio.h>

int main(){
int x[COLOR=Red]=0[/COLOR],y[COLOR=Red]=0[/COLOR];
float z[COLOR=Red]=0[/COLOR];[COLOR=Red]//always initialize variables in the beginning[/COLOR]
[COLOR=Red]while (x<=0){//number must be greater or equal to 1[/COLOR]
printf ("\nEnter a number:\t");
scanf ("%d",&x);[COLOR=Red]getchar();//always after a scanf[/COLOR]
[COLOR=Red]}[/COLOR]
[COLOR=Red]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[/COLOR]
[COLOR=Red]z/=x;//after exiting the loop divide result with total numbers[/COLOR]
printf ("\n\nThe average of all numbers from 1 to %d is %f",x,z);
getch[COLOR=Red]ar[/COLOR]();
return 0;

```

Joined:
Sep 15, 2010
Messages:
2
0
Trophy Points:
0
thanks

Joined:
Nov 24, 2009
Messages:
387