Print "n" natural odd numbers

1

I am solving an exercise that asks me to enter a value for example: 5 and print the first 5 natural numbers in the case:

entry:

Type the value of n: 5

  • 1
  • 3
  • 5
  • 7
  • 9

The code I wrote works however does not seem to me the best logic for solving it. Would anyone else have known any other "simple" solution because I am still learning

n = int(input("Digite o valor de n: "))

i = 1

while i <= (n+n):
if i % 2 != 0:
    print(i)
    i += 1
else:
    i += 1
    
asked by anonymous 11.04.2017 / 05:48

3 answers

2

I was able to understand and apply with another logic without needing to add n + n , in case it would look this way:

n = int(input("Digite o valor de n: "))

i = 0
ímpar = 1

while i < n: 
  print(ímpar)
  i = i + 1
  ímpar = ímpar + 2
    
11.04.2017 / 06:33
3

A very simple alternative would be with the function range(start, stop, step)

  • Start: initial number of the sequence.
  • Stop: this number, but does not include it in the sequence.
  • Step: The difference between each number in the sequence.

    n = int(input("Digite o valor de n: "))
    for i in range(1, n+n, 2):
       print(i)
    

output:

    
11.04.2017 / 06:07
-1

You can use the for loop, which I really like:

printf("Digite o numero");
int k = scanf(&k);

for(int x = 0; x < k; k++){
if(k%2 != 0){
printf("%i\n", k);
} // end if
} // end for
    
11.04.2017 / 12:03