Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
when a user give int value of number>0 why doesn't do while loop prints " n is" forvever and when i delete scanf()in do while loop it prints "n is:" forever?

What I have tried:

#include <stdio.h>
#include <stdlib.h>
 int get_negative_int( void);
int main()
{
    int i=get_negative_int();
   printf("%i is negative integer",i);

   }
    int get_negative_int( void){ int n;
       do{
        printf("n is:");
scanf("%i",&n);
       } while (n>0);
       return n;

   }
Posted
Updated 24-Mar-17 10:29am

Because inside the loop you change the value of n:
C++
scanf("%i",&n);
The scanf function reads input from the standard input stream - normally the console, as typed by the user - and puts the value into the variable.
So while n starts as a "fixed value" it gets a new value each time you go round the loop, and so the test at the end of the while loop looks at a different value each time.

It's like a stage magician doing the same card trick on ten members of the audience in turn: each time they get to pick a card, and each time it's a different card. When one of them picks the Ace of Spades, the magician stops doing the trick.
 
Share this answer
 
First, advice: Lear'n to indent your code, it helps reading.
C++
#include <stdio.h>
#include <stdlib.h>
int get_negative_int( void);
int main()
{
	int i=get_negative_int();
	printf("%i is negative integer",i);

}
int get_negative_int( void){
	int n;
	do{
		printf("n is:");
		scanf("%i",&n);
	} while (n>0);
	return n;

}


When you don't understand what your code is doing or why it does what it does, the answer is debugger.
Use the debugger to see what your code is doing. Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute, it is an incredible learning tool.

Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900