Enjoy an ad free experience by logging in. Not a member yet? Register.

Results 1 to 4 of 4

11022007, 03:22 AM #1
 Join Date
 Nov 2007
 Posts
 4
 Thanks
 1
 Thanked 0 Times in 0 Posts
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(); }
11022007, 03:30 AM
#2
 Join Date
 Nov 2007
 Posts
 4
 Thanks
 1
 Thanked 0 Times in 0 Posts
*update*
please disregard variable: sum ,I actually meant k in the last line.
11022007, 08:58 PM
#3
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 2K1)...
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
Last edited by sage45; 11022007 at 09:06 PM.
HTML & CSS Forum Moderator
"If you don't know what you think you know, then what do you know."
R.I.P. Derrick Thomas #58
1/1/1967  2/8/2000
Users who have thanked sage45 for this post:
Naikon (11032007)
11032007, 02:25 AM
#4
 Join Date
 Nov 2007
 Posts
 4
 Thanks
 1
 Thanked 0 Times in 0 Posts
I see what you mean
Thanks very much for the help.