-2

I need help with this problem. The only thing I have done is to input the numbers less than 0. Any ideas?

Write a program. In main create a DO loop. In the loop ask the user to enter a number. If the number is positive call a function. If the number is negative end the program. In the function keep track of how many times the function has been called and each time in the function print the number of times you have called the number on a new line. Pass no values to the function. DO NOT USE GLOBAL VARIABLES THIS TIME

So far, I only have this code:

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

void counter(void);
int main()
{
    int number;

    do 
    {
        printf("\nEnter a number: ");
        scanf("%d", &number);

        if(number >= 0)
        {
            //counter();
        }

    }while(number >= 0);


    printf("\nPress any key to continue...");
    getch();

    return 0;
}

void counter(void)
{
    //counter code`enter code here`
    enter code here

}
ElGavilan
  • 6,610
  • 16
  • 27
  • 36
  • Since this question is unlikely to help any future visitors, it should probably be duped against a better question, like [this one](http://stackoverflow.com/questions/572547/what-does-static-mean-in-a-c-program). – Daniel Pryden Jan 27 '15 at 03:57

2 Answers2

0

Create a static variable in the function and print it.

void counter(void)
{
    static int num;
    printf("%d\n",++num);
}

static is essential because static variables exist as long as the program does. So, the variable still exists once the function ends. Also, static variables are automatically initialized to 0 when the program starts.

Spikatrix
  • 20,225
  • 7
  • 37
  • 83
0

Your counter() function needs to maintain state. You probably want to use the static keyword.

In a real-world non-homework situation, I would advise against doing it this way. Hidden state almost always leads to complexity and makes it difficult to unit test your functions.

Daniel Pryden
  • 59,486
  • 16
  • 97
  • 135