Skip to content

Instantly share code, notes, and snippets.

@marioluan
Created November 11, 2012 22:06
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marioluan/4056426 to your computer and use it in GitHub Desktop.
Save marioluan/4056426 to your computer and use it in GitHub Desktop.
Programa em Java que calcula o fatorial de um número inteiro
/*
* Faça um programa que calcule o fatorial de um número inteiro.
* Repita a operação de cálculo X vezes.
*/
package cap14;
import java.util.Scanner;
public class Exercicio03 {
public static void main(String[] args){
Scanner ent = new Scanner(System.in);
int num, fat = 1;
int cont = 1;
do{
System.out.println("Digite um nº");
num = ent.nextInt();
for(int i = 1;i <= num; i++){
fat = fat * i;
}
System.out.println("!" + num + " = " + fat);
cont++;
}while(cont < 2);
}
}
/* Passo-a-passo do algoritmo
fat = fat * i -> fat
fat = 1 * 1 -> 1
fat = 1 * 2 -> 2
fat = 2 * 3 -> 6
fat = 6 * 4 -> 24
fat = 24 * 5 -> 120
*/
Copy link

ghost commented Mar 29, 2017

Nice!

@gabrielgyns
Copy link

Valeu, ajudou.

@KenyOS
Copy link

KenyOS commented Apr 24, 2018

thanks!

@johnlimaa
Copy link

Muito obrigado!

@thoomassf
Copy link

Ajudou muito, vlw

@vitinha83627894832
Copy link

Ajudou demais, obrigada!

@Alexlexgross
Copy link

thank so much mano!!

@leandrostavares
Copy link

Por acaso eu acabei aqui lendo seu código e notei que o laço DO...WHILE não é necessário.
Esse laço só vai executar uma vez e pois o contador será igual a 2 após o término do laço.

Removendo a parte do scanner e o contador poderíamos resumir assim:

int num = 2; // Fatorial a ser calculado
int fat = 1;

for(int i = 1; i <= num; i++){
fat = fat * i;
}

System.out.println("!" + num + " = " + fat);

@leandrosantos0
Copy link

muito bom
me ajudou muito na aula de programação no IFMA

@Kamado8421
Copy link

obrigado você me garantil um 10 na melhor materia do mundo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment