write algorith to display first n odd numbers ?
algorithm to find first n odd numbers
Collapse
X
-
-
What exactly does first mean? I assume that you are only concerned with positive odd numbers, so the first odd number is 1, and you want to follow it with the smallest odd number that is greater than 1.
What exactly are the constraints on your assignment? There are two ways to proceed: step through the integers, testing each for odd; or start from a known first odd number and repeatedly construct the next odd number. The latter approach might be considered cheating ... depending on the precise rules (or constraints) on the assignment.Comment
-
We use % operator to get reminder.. and if odd number is divided by 2 we get reminder 1
Algorithm
1 Start
2 Enter max
3 for(i=0;i<mx;i+ +)
if(i%2==1)
printf(i)
end if
end for
4 stopCode:#include<stdio.h> #include<conio.h> void main() { int max,i; printf("Enter value of max"); scanf("%d",&max); printf("Odd Numbers : \n"); for(i=0;i<=max;i++) { if(i%2==1) printf("%d",i); } }
Comment
-
@whodgson, I don't let my programs go near limit values like INT_MAX because here there be dragons. The loop only terminates when a is larger than INT_MAX. If a is an int then that can't ever happen. If a is a long then it is implementation-dependent whether that will ever happen. Changing the termination condition to a<INT_MAX will work ... but only if INT_MAX is odd.
The OP wants the first n odd numbers. Safer to terminate the loop by counting down on n.Comment
-
Dear whodgson
As a fresher to C or CPP language its better and clear for Anirudh to get logic and understand it.....Comment
-
@whodgson and swapnali143 both algorithms are valid and reasonable ways to solve this problem. It is not possible to say which is better in this instance because the OP has not given enough detail in their description of the problem. It is entirely possible that for their purposes either would do but it is also possible that they were supposed to be making use of a particular operator (% for example).
@whodgson donbock has already highlighted the INT_MAX issue in your code and I will say little further except that this is not the only way loop end tests can go wrong and it is always worth ensuring that your loops can actually end having performed the correct number of iterations for all input values to the algorithm.
@swapnali143 you really should write main as returning int and avoid using conio.h. You do not know what platform the viewers of this forum use so you need to assume that it is a conforming platform with no extensions. main returning void is an extension in some C compilers and should be avoided conio.h is a extension header on some platforms and should also be avoided. Writing properly portable code is a skill that is worth developing.Comment
Comment