Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

Thread: do for loop to compute a set of odd integers.

1. do for loop to compute a set of odd integers.

Hi, I am very new to C programming.
I have stumbled on this problem for a while now, and anyone who could point me in the right direction with this, I thank you.

Basically, the user inputs a value for N, where the program prints a list of the odd integers less than N.
I want the program to print the odds such as (1,3) etc less than N.
I am a beginner, so please excuse my code

Here is the code:

Code:
```#include <stdio.h>
#include <conio.h>

void main()

{

int k;
int N;
int sum;

printf("please enter a value for variable N: \n");
scanf("%d" , &N);

k=2;

k = k+1;

do

{
k = k+1;

} while ( k < N  &&  k*k < N );

printf("the number of odds is: %d\n" , sum);

getch();

}```

• *update*

please disregard variable: sum ,I actually meant k in the last line.

• Ok... very simple.

An even integer is defined as any integer mutiplied by 2 or evenly divisble by 2... Hence 2K (2N in your case)

So therefore an odd integer would be defined as (2K+1) where you take an even integer and add 1 to it.

so in your program there would be two ways that you could complete this...

First (and most sensible way) is to take the integer that has been input... Start at 0 (since 0 is an even integer) and apply the formula 2K+1 until the the result of 2K+1 is greater than or equal to your variable (assuming a positive entry, if the entry is negative then you simple use -2K-1)...

I.E. I enter in 5
1 = 2*0 + 1
3 = 2*1 + 1
5 = 2*2 + 1 (since the result is equal to 5 the loop ends)

Using -7:

-1 = -2*0 - 1
-3 = -2*1 - 1
-5 = -2*2 - 1
-7 = -2*3 - 1 (since the result is equal to -7 the loop ends)

The second way is to divide the entered integer by 2 and take the result as the upper boundary of your loop. The resulting loop would end when the upper boundary is reached

I.E. - I enter in 9
9 / 2 = 4 (in C/C++ Integer division)
So then I continue as above:
1 = 2*0 + 1
3 = 2*1 + 1
5 = 2*2 + 1
7 = 2*3 + 1
9 = 2*4 + 1 (since the K value is equal to the result of the division, the loop ends)

HTH,

-saige-

• Users who have thanked sage45 for this post:

Naikon (11-03-2007)

• I see what you mean
Thanks very much for the help.

•

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•