My program should calculate and print the gcd and lcm of n numbers. First user will enter the number n. Then, user will enter the n many numbers and these numbers should assign an array. Lastly, gcd and lcm will be calculeted and printed.
I can not use the user-defined functions in my program. I know this is strange but it is a must.
I wrote my code. It calculates and prints the gcd correctly. But when it comes to lcm it prints meaningless numbers. Also the program don't start without enter 2 numbers. Can somebody tell me where my mistake is?
here is my code:
#include <stdio.h>
#include <stdlib.h>
#define max 100
int main()
{
int n,i,ii, product,gcd,lcm,arr[max],j=1;
printf(" How many numbers do you want to enter?
");
scanf("%d ",&n);
for(i=0;i<n;i++)
{
printf(" enter the %d. number:
",(i+1));
scanf("%d ",&arr[i]);
}
gcd = arr[0];
while(j<n)
{
if(arr[j]%gcd==0){
j++;
}
else{
gcd=arr[j]%gcd;
}
}
printf("GCD of all numbers is %d
", gcd);
product=1;
for(ii=0;ii<n;ii++){
product=product*arr[i];
}
lcm=product/gcd;
printf("LCM of all numbers is %d",lcm);
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…