How to find sum of first n odd integers
When whole numbers divided by 2 leave a remainder of 1, they are called odd numbers.
Example: 1, 3, 5, 7…
Code
-
Let
nbe any number and initializesumandcountvalues to 0. -
An empty
list lis taken to append the values of odd numbers and variableiis initialized to 1. -
The
Whileloop is used to check whether the number is even or odd. If a number is odd, it is appended to thelist l. -
The
Forloop is used to iterate thelist l. The elements inlist lare added and stored in the variablesum. -
sumcontains the sum of the firstnodd integers.
n=10sum=0count=0l=[]i=1while(count<n):if(i%2!=0):l.append(i)i=i+2count=count+1for i in l:sum=sum+iprint(sum)