Originally Posted by
langamer101
Code:
#include<iostream.h>
#include<conio.h>
int prnmsg(int a);
main()
{
clrscr();
int n;
cout<<"Enter a number : ";
cin>>n;
do
{
cout<<"hello world"<<prnmsg(n);
}
while(prnmsg(n)<=1);
getch();
return(0);
}
int prnmsg(int a)
{
int sum;
do
{
a--;
sum=a;
return sum;
}
while(a<=1);
}
Let's see what does this code do..
Until line 9 is pretty clear.
Line 10 we reach the do while structure.We enter the loop and the message is printed.
Then ,in line 14,the prnmsg function is called.Inside this function we decrease the a(which has the value of n) by one in line 23.
Then we assign a to sum at line 24.
Then ,in line 25, the function will be terminated(!) and sum will be returned.So the do-while structure at lines 21-27 is useless,because at line 21 we are sure that our code will enter the loop,but in line 25 the function will be terminated,so the statement at line 27 with the while will not be checked at all.No matter if a<=1(line 27) <-the function is not going to reach this point,so the loop inside the function will never be executed!!
Then after the function returns sum we come back at line 14 and check if prnmsg(n)<=1 which is equivalent to sum<=1.This will be true only if the user inputs something that is smaller or equal to 1,so actually <= is wrong.
You could use something like this
(read the e.g. i have on a post above with --)
Code:
#include<iostream>
using namespace std;
int main(void)
{
int n;
cout<<"Enter a number : ";
cin>>n;
do
{
cout<<"hello world"<<endl;
}
while(--n);
return(0);
}
or with less lines
Code:
#include<iostream>
using namespace std;
main()
{
int n;
cout<<"Enter a number : ";
cin>>n;
while(n--)
{
cout<<"hello world"<<endl;
}
return(0);
}