From your program, you can do a separate function outside of main, which does this calculation. The benefit of functions, is that you can call them from anywhere in the program and will often save lines. For example, if for some reason you wanted to do the same calculation at the end of main, you would have to repeat the entire for. If you do a function that does this calculation, just call it.
The prototype of a function is as follows:
<tipo> <nome_da_função>(<parâmetros>)
{
código;
...;
}
The function type defines the type that will be returned by the function. In the function to perform its calculation, the result of this, that is, the variable soma
, will be an integer, so the returned value will be an integer, so the type is int
.
The function name is worth the same rules for naming a variable, nothing new here.
The parameter of a function is what you need to do your calculation or what you need to be past its function to do anything inside it. For you to do your for
you need the element that the user entered ( n
), since it is part of for
. Therefore, it is a parameter to its function.
Obersvation: Note that parameters are variables, and should be declared as variables as well.
So far, we already know the type and parameters of the function, so we can already create it.
int divisor(int elem)
{
int divisor = 0, soma = 0;
for (divisor = 1; divisor < elem; divisor++)
if ( elem % divisor == 0 )
soma = soma = + divisor;
return soma;
}
Note that the parameter need not necessarily have the same name as the variable that will pass, in other words: the name of the variable inside the function may be different from the variable that is in the main.
Function created, just call her in main to make the necessary calculation.
Result:
#include <stdio.h>
#include <stdlib.h>
int divisor(int elem)
{
int divisor = 0, soma = 0;
for (divisor = 1; divisor < elem; divisor++)
if ( elem % divisor == 0 )
soma = soma = + divisor;
return soma;
}
int main()
{
int n, resultado;
printf("Digite um numero inteiro positivo: ");
scanf("%d", &n);
/*A função divisor retornará o resultado do cálculo, logo posso
igualá-la a uma variável (Essa variável será igual ao resultado
da conta) */
resultado = divisor(n);
if (resultado == n)
printf("O numero %d e perfeito \n", n);
else
printf("o numero %d nao e perfeito \n", n);
return 0;
}
If you have not understood something, ask here or look on the internet, there is a lot of material about it, otherwise it's just custom, I did not understand it either, but if you use it a lot, you'll get used to it and learn how to use it.