-1

this is the code ..but it is not displaying the first and the last number that came from the user.
anyone can help me with this small problem??

#include <iostream.h>
#include <conio.h>
main()
{
int  f,l,f1,l1;
clrscr();
cout<<"Enter the First digit:";
cin>>f;
cout<<"Enter the Last digit:";
cin>>l;
f1=f;
l1=l;
cout<<"The Odd numbers/digits between "<<f<<" and "<<l<<" Are: "<<endl;
for (f++;f<l;f++)
{
if ((f%2)!=0)
cout<<" "<<f<<endl;
}
cout << "And Even numbers/digits between "<<f1<<" and "<<l<<" are:"<<endl;
for (f1++;f1<l1;f1++)
{
if ((f1%2)==0)
cout<<" "<<f1<<endl;
}
getch();
}

the output:

Enter the first number:1
Enter the Last number:10
The Odd numbers between 1 and 10 are:
3
5
7
9
And the even number between 1 and 10 are:
2
4
6
8

Edited by __avd: Added [code] tags. Encase your code in: [code] and [/code] tags.

4
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by dusktreader
Featured Replies
  • combine your even and odd in one loop : [code] for(int num = start; num != end; ++num){ if(num % 2 == 0) cout << num << " is even\n"; else cout << num << "is odd\n"; } [/code] Read More

0

Firstly, please use code tags (there's still time to edit your post and put them in).

For your for loops, you are incrementing your values in your initialization step (and thereby skipping over the first value) and you were losing your last (if you want it) by having a termination condition that was < instead of <=: for ([COLOR="Red"]f++[/COLOR];f<l;f++) in both cases
Use a different variable if you can and have for (int index = f;index <=l;index++) (for example) In that same vein don't use 1 letter variable names, there's no savings there and there is a decrease in readability.

Edited by happygeek: fixed formatting

1

combine your even and odd in one loop :

for(int num = start; num != end; ++num){
  if(num % 2 == 0) cout << num << " is even\n";
  else cout << num << "is odd\n";
}
0

this is the code ..but it is not displaying the first and the last number that came from the user.
anyone can help me with this small problem??

1. Use an index variable in your loops
2. You don't need to iterate over all of the values, testing each for even or oddness. Instead, step your loops by 2!

for( int i=evenStart; i<=seriesEnd; i+=2 )
        // do whatever.  The value of i will be even
    for( int i=oddStart; i<=seriesEnd; i+=2 )
        // do whatever.  The value of i will be odd

The trick here is setting evenStart and oddStart to the correct value based on a variable like seriesBegin

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.