Gemini adlı üyeden alıntı: mesajı görüntüle
Q1. The following program generates the sum of the first n numbers.


#include <stdio.h>

main()
{

int n;
int i = 0;
int sum = 0;

printf("Please enter a positive integer: ");
scanf("%d", &n);

while (i < n) sum+=++i;

printf("the sum of the first %d numbers is %d\n", n, sum);
}



(a) Convert the program to calculate the factorial of n, which is the product of the first n numbers, and obtain the values of the factorial for the following inputs:

a. n = 3 n! = _______________
b. n = 12 n! = _______________
c. n = 13 n! = _______________
d. n = 20 n! = _______________
e. n = 23 n! = _______________
f. n = 43, n! = _______________

(2 points)


(b) If you see a problem with the results, what is the cause?
(1 point)



(c) Modify the program so that if the answer is correct, the program outputs the result, otherwise it outputs the message "Error: cannot compute factorial for this number". Obtain the output for the following inputs:


a. n = 3 n! = _______________
b. n = 12 n! = _______________
c. n = 13 n! = _______________
d. n = 20 n! = _______________
e. n = 23 n! = _______________
f. n = 43, n! = _______________

(2 points)



Arkadaşlar cevabı arıyorum sınavdayım HELP ME

Cevap şöyle:
#include <stdio.h>

main()
{

int n;
int i = 0;
int prod = 1;

printf("Please enter a positive integer: ");
scanf("%d", &n);

while (i >0) prod*=i--;

printf("the product of the first %d numbers is %d\n", n, prod );
}

Bu şekilde önce 3 girildi ise mesela, 3 den başlar, 0'dan büyükmü diye bakar. Büyükse sonuçla çarpar. 3*1 =3 eder. sonra i 1 azaltılır bu şekilde 3*2*1 hesaplanır ve i 0'a ulaşınca while döngüsünden çıkılır.

Fakat 0'ın verilmesi durumunda program sonucu 1 bulacaktır. 0'ın faktöryeli hesaplanmak istendiğinde (ya da negatif) hata mesajı görüntülenmelidir. O da şöyle:

#include <stdio.h>

main()
{

int n;
int i = 0;
int prod = 1;

printf("Please enter a positive integer: ");
scanf("%d", &n);

if(n<=0)
{
printf("Cannot calculate the factorial of this number");
return;
}


while (i >0) prod*=i--;

printf("the product of the first %d numbers is %d\n", n, prod );
}

Bir de eğer sonuç 32 biti aşarsa sonuç gösterilemez. Bu yüzden int veritipi değiştirilmeli. Sonucu tutamıyor. long yada ulong olabilesi aslında.