write a program print first n odd numbers using formula
Answers
Answer:
The total of any set of sequential odd numbers beginning with 1 is always equal to the square of the number of digits, added together. If 1,3,5,7,9,11,…, (2n-1) are the odd numbers, then; Sum of first odd number = 1. Sum of first two odd numbers = 1 + 3 = 4 (4 = 2 x 2).
Answer:
This is in Java,
int ctr=1;
for(int i=1;ctr<=n;i+=2,ctr++)
{
System.out.println(i);
}
Explanation:
•First off we get a number from the user.
•Secondly we set up a control variable to check the number of iterations. Basically the loop depends on the control variable(I've initialised ctr here) so it will work until the value of control variable hits the value of n.
•Now the loop is given and the formula for consecutive odd numbers is (x+2) where x is an odd number starting from 1.
• Let's talk bout how the loop works. The value of i starts off as 1 (which is the first odd number) and then the control moves on to check the condition.
This is where ctr comes into action as it will decided the number of iterations of the loop. Since 1 is indeed lesser than n (I'm assuming n is greater than 1) the loop prints 1 and then the control moves on to update expression. Here the value of i is increased by 2 and ctr is increased by 1 (which denotes that the loop has already run one time out of the n iterations). Now it repeats until ctr exceeds the value and n.
Hope it helps buddy :)