it presents only the next odd number and for
The problem is here:
while(imp<n){
imp=n+2;
In fact, the problem starts a little earlier because you did not assign any value to imp
before using it, then the value of this variable will be undetermined and may not even enter this while
. If it "worked" in your case, it’s by coincidence, but you can’t program by coincidence.
Anyway, even if you get into while
, right in the first iteration you make the value of imp
be equal to n + 2
. I mean, right now imp
will have a value greater than n
and therefore the condition imp < n
is no longer satisfied. That’s why the while
only runs once.
For the program to work, you have to consider its requirements:
- the value read (
n
) is the amount of numbers, so it should be used as control of the loop
- the
n
also determines what is the initial value to be printed: is the odd number immediately after n
- that is, if
n
is odd, the initial value is n + 2
- if
n
is even, the initial value is n + 1
You could do something like:
// obtém o valor inicial a ser impresso
int num;
if (n % 2 == 0) // se n é par, o valor inicial é n + 1
num = n + 1;
else // se n é ímpar, o valor inicial é n + 2
num = n + 2;
Or we can use the very result of n % 2
(the rest of the division by 2, i.e., it is zero for even numbers and 1 for odd numbers):
int num = n + 1 + (n % 2);
From there, we know that num
is an odd number, so to get the next odd odd, just add 2 to it. I do this n
times. It would look like this:
int n;
printf("Digite um numero: \n");
scanf("%d", &n);
// se n é ímpar, soma 2 para encontrar o próximo ímpar, se for par, soma 1
int num = n + 1 + (n % 2); // n % 2 é o resto da divisão por 2, então se for ímpar será 1, se for par será zero
// assim, num é o primeiro número ímpar imediatamente depois de n
for (int i = 0; i < n; i++) { // repito o for n vezes
printf("%d\n", num);
num += 2; // como num é ímpar, posso somar 2 para ir para o próximo ímpar
}
You can make it even shorter, taking advantage of the fact that in a for
we can initialize and increment multiple variables:
int n;
printf("Digite um numero: \n");
scanf("%d", &n);
for (int i = 0, num = n + 1 + (n % 2); i < n; i++, num += 2) {
printf("%d\n", num);
}
Thanks, helped d+!
– Hebert