By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,963 Members | 920 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,963 IT Pros & Developers. It's quick & easy.

algorithm

P: 2
I have an assignment to write an algorithm to print the first 10 odd numbers and this is my attempt
Initialize the first counter to 1 (i=1)
Initialize the second counter to 0 (j=0)
second counter is equal to second counter plus first counter(j=j+i)
print the value of the second counter (print j)
if second counter is greater than 10 (if j>10)
stop
else if j is less than 10 (j<10)
Add 2 to the value of the second counter (j=j+2)
print j
Repeat steps 4 to 9 until the value of second counter is greater than 10

Is it correct?
Apr 30 '18 #1
Share this Question
Share on Google+
2 Replies


Expert 100+
P: 2,396
Second counter (j) holds the successive odd values. You terminate the loop as soon as j>10. That means you print the positive odd numbers that are less than 10: 1,3,5,7,9. That’s only 5 values.

You call i “the first counter” but its value stays at 1. It doesn’t count. What do you intend for it to do?

Your algorithm says what to do when j>10 and what to do when j<10. What should you do if j=10?

Does your assignment restrict what properties of odd numbers you’re allowed to take advantage of? For example, your algorithm takes advantage of the handy fact that successive odd numbers differ by 2. Another potentially helpful property of odd numbers is that the value of the nth odd number is (2*n)-1 (for n >= 1). On the other hand, if the assignment says the only thing you are allowed to know about odd numbers is that they have a remainder of 1 when divided by 2, then you should start from 0, test the remainder, increment by 1 and repeat until you find the 10th value that passes the test.
May 1 '18 #2

P: 2
This reply is very useful.Thank you and here is my second attempt
Step 1:Initialize the counter to 0 (j=0)
Step 2:counter is equal to j plus 1(j=j+1)
Step 3:print the value of the counter (print j)
Step 4:if counter is greater than 20 (if j>20)
Step 5:stop
Step 6:else if j is less than 20 (j<20)
Step 7:Add 2 to the value of the counter (j=j+2)
Step 8:print j
Step 9:Repeat steps 4 to 9 until the value of counter is greater than 20
May 2 '18 #3

Post your reply

Sign in to post your reply or Sign up for a free account.