How do you write a C program to increment a number by keypress and auto-decrement it per second?

increment and decrement operators in c
increment and decrement problems in c
what is the process to create increment and decrement statement in c
multiple increment decrement operator in c examples
increment a counter in c
how to add to a variable in c
for loop decrement in c programming
how to calculate the execution time of a program in c

I'm trying to write a program in which a number starts from 0, but when you press any key, it gets incremented by 1. If nothing is pressed, it keeps on decreasing by 1 per second until it reaches 0. Every increment or decrement is displayed on the console window.

Problem with my approach is that nothing happens until I press a key (that is, it checks if anything is pressed with getch()). How do I check that nothing is pressed? And of course, !getch() doesn't work because for that to work, it'll still need to check for keypress which nullifies the purpose itself.

OS: Windows 10 Enterprise, IDE: Code::Blocks

void main()
    int i, counter = 0;
    for (i = 0; i < 1000; i++)
        // if a key is pressed, increment it
        if (getch())
            counter += 1;
            printf("\n%d", counter);
        while (counter >= 1)
            if (getch())
                printf("\n%d", counter);

Incrementing and Decrementing in the C Language, Two common C shortcuts are ++ and —, which are used for incrementing (adding one to) For example, you have variable count and you need to add 1 to its value. Type this into your editor, save the source code to disk, compile, and run​. I'm trying to write a program in which a number starts from 0, but when you press any key, it gets incremented by 1. If nothing is pressed, it keeps on decreasing by 1 per second until it reaches 0. Every increment or decrement is displayed on the console window.

This could be done with multithreading as already suggested, but there are other possibilities.

ncurses for example has the possibility to wait for input with a timeout.

An example for ncurses (written by Constantin):

char c = getch();
printf("Char: %c\n", c);

I think poll could also be used on stdin to check if input is available.

And to make your program more responsive you could lower your sleep or delay to for example 100ms and only decrement if ten iterations of sleep have passed without input. This will reduce the input lag.

C Programming Tutorial, If you have come to C in the hope of finding a powerful language for writing everyday computer C is one of a large number of high level languages which can be used for general purpose A pointer to a function is an automatic local variable. The simplest of these perhaps are the increment and decrement operators:. Prev Next Increment operators are used to increase the value of the variable by one and decrement operators are used to decrease the value of the variable by one in C programs. Syntax: Increment operator: ++var_name; (or) var_name++; Decrement operator: – -var_name; (or) var_name – -; Example: Increment operator : ++ i ; i ++ ; Decrement operator : – – i ; i – – ; Example program

Here is a pthread example that works on linux. The concept is ok, but there are probably existing loops/libraries for this.

#include <stdio.h>

void *timer(void* arg){
    int* counter = (int*)arg;
    while(*counter > 0){
        int a = *counter;
        printf("counter: %d \n", a);
        *counter = a - 1;

int main(int arg_c, char** args){
    int i = 100;
    pthread_t loop;

    pthread_create(&loop, NULL, timer, &i);

        printf("inc counter: %d \n", i);
    printf("%d after\n", i);

    pthread_join(loop, NULL);

    return 0;

This starts a second thread, which has the countdown on it. That decrements the counter every second. On the main thread it has a loop with getchar. They both modify i.

How to measure time taken by a function in C?, We can call the clock function at the beginning and end of the code for which we measure time, subtract (the number of clock ticks per second) to get processor time, like following. The function fun() waits for enter key press to terminate. Please write comments if you find anything incorrect, or you want to share more  4 How do you write a C program to increment a number by keypress and auto-decrement it per second? Oct 9 '18. 4 Can someone explaint what this code do? Oct 19 '16.

Another example using ncurses and POSIX timers and signals (and global variables).

#include <ncurses.h>
#include <signal.h>
#include <time.h>

int changed, value;

void timer(union sigval t) {
        (void)t; // suppress unused warning
        changed = 1;

int main(void) {
        int ch;
        timer_t tid;
        struct itimerspec its = {0};
        struct sigevent se = {0};

        se.sigev_notify = SIGEV_THREAD;
        se.sigev_notify_function = timer;
        its.it_value.tv_sec = its.it_interval.tv_sec = 1;
        timer_create(CLOCK_REALTIME, &se, &tid);
        timer_settime(tid, 0, &its, NULL);

        halfdelay(1); // hit Ctrl-C to exit

        for (;;) {
                ch = getch();
                if (ch != ERR) {
                        changed = 1;
                if (changed) {
                        changed = 0;
                        mvprintw(0, 0, "%d ", value);


[PDF] CCS C Compiler Manual, Type Qualifiers . Using Program Memory for Data . int seconds; // Number of seconds since last entry long day Address Auto-Increment/Auto-Decrement PIN=char - If a valid key press is determined on “PIN”, the software will return the. David Collins. Full-time human 11 How do you write a C program to increment a number by keypress and auto-decrement it per second? Oct 9 '18.

You need use thread, and need use __sync_add_and_fetch and __sync_sub_and_fetch to avoid concurrency problem

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <termios.h>
#include <unistd.h>
#include <iostream>

static void* thread(void* p) {
    int* counter = (int*)p;
    while (1) {
        if (*counter > 0) {
            __sync_sub_and_fetch(counter, 1);
            printf("sub => %d\n", *counter);
        }  else {

    return NULL;

int main() {
    int counter = 0;
    char ch;

    struct termios orig_attr, new_attr;
    tcgetattr(fileno(stdin), &orig_attr);
    memcpy(&new_attr, &orig_attr, sizeof(new_attr));
    new_attr.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(fileno(stdin), TCSANOW, &new_attr);

    pthread_t pid;
    if (pthread_create(&pid, NULL, thread, &counter)) {
        fprintf(stderr, "Create thread failed");

    while(1) {
      char c = getchar();
      __sync_add_and_fetch(&counter, 1);
      printf("add: %d\n", counter);

    return 0;

[PDF] VisiLogic: Ladder Programming, Bit to Numeric . You use Ladder Logic to write your project application. Ladder is based on If Key #1 is held down for 5 seconds, TD1 decrements to zero. O1 Up Counter in your program, place an Increment function in a net and select C. VisiLogic: Ladder Programming. 75 requested. (Socket 0). SB. 174. Automatic. 2 Defining list and inner dictionary as the value of a dictionary in c Dec 27 '18 2 How do you write a C program to increment a number by keypress and auto-decrement it per second? Oct 9 '18

[PDF] CAPL Scripting Quickstart, CAPL (Communication Access Programming Language) For CANalyzer and Auto complete for names C-like programming language Signal change. ▷ Time event. ▷ Key press on Start. { write ("Start of CANoe");. } for CAN message for CAN messages. Time variables for seconds Increment or decrement by 1. The Increment and Decrement Operators in C are some of the Operators, which are used to increase or decrease the value by 1. For instance, Incremental operator ++ is used to increase the existing variable value by 1 (x = x + 1). And decrement operator – – is used to decrease or subtract the existing value by 1 (x = x – 1).

[PDF] CCS C Compiler Manual PCB, PCM & PCH, How do I write variables to EEPROM that are not a byte? By default, the compiler files are put in C:\Program Files\PICC and the int seconds; // Number of seconds since last entry Address Auto-Increment/Auto-Decrement Returns the receive pin for the second UART on this PIC result better key press detection. In this example, you'll learn to overload increment ++ and decrement -- operators in C++. To understand this example, you should have the knowledge of the following C++ programming topics: In this tutorial, increment ++ and decrements -- operator are overloaded in best possible way, i.e., increase the value of a data member by 1 if ++ operator

C - Increment/decrement Operators, Example program for increment operators in C: In this program, value of “i” is incremented one by one from 1 up to 9 using “i++” operator and output is displayed  Here we increment int variables in different ways. The program shows both the ++ operator (with 2 pluses) and the += operator (with a plus and an equals). Note: The post-increment here begins with the value 0 and changes it to the value 1. Also: You use any constant or other expression resulting in a numeric value in the increment statement.

  • Why not? If there's some adverse effect I don't know about, what alternative can I use to simulate a delay? Nested for loops are highly CPU consuming so I avoided that. I do not want the decrement to happen immediately because that woudn't give the user enough time to increment it in the first place.
  • If you want to do multiple things at once (waiting for delay to finish and waiting for a keystroke), you might want to look into multithreading
  • How would you handle a keypress while you are blocked in a delay()?
  • For Windows you want… : call GetNumberOfConsoleInputEvents and if it's above zero call ReadConsoleInput.
  • If this is for a real-life thing, consider using a third-party event library, like You'd have two listeners, a timer and a stream, and each handler would increment/decrement.
  • int c to be able to safely compare with EOF :)
  • @pmg: Thanks. I see that ilkkachu has already made the relevant edit.
  • An alternative to setting VTIME would be to use select() to see if input becomes available within a particular time period. You'd still need to put the terminal in raw mode to be able to detect anything but full lines, though.
  • Doesn't work for me (FreeBSD 11.2) :( Basically counting up is ok. but the first count down (if I don't hit a key within a second) goes all the way to 0 in a flash.
  • @pmg I witnessed a similar problem on certain Android platforms. Clearing the EOF flag on stdin solved the problem. (I have updated the answer.) I would be curious if that fixes the problem for you on FreeBSD also.