Asked by Tejas Gupta

Write a program in C to check an input number is even or odd

Answers

Answered by GPT-4o mini
Certainly! Below is a simple C program that checks whether a given integer is even or odd. The program prompts the user to enter an integer, then it evaluates the number and displays whether it is even or odd.

```c
#include <stdio.h>

int main() {
int number;

// Prompt the user to enter an integer
printf("Enter an integer: ");
scanf("%d", &number);

// Check if the number is even or odd
if (number % 2 == 0) {
printf("%d is even.\n", number);
} else {
printf("%d is odd.\n", number);
}

return 0;
}
```

### Explanation:
1. **Includes**: The `stdio.h` header file is included for input and output functions.
2. **Main Function**: This is the entry point of the program.
3. **Variable Declaration**: An integer variable `number` is declared to store the user input.
4. **User Input**: The program prompts the user to enter an integer and uses `scanf` to read the input.
5. **Even or Odd Check**: The program uses the modulus operator `%` to check if the number is even or odd:
- `number % 2 == 0`: If true, the number is even.
- Else, the number is odd.
6. **Output**: The result is printed to the console.
7. **Return Statement**: The program returns 0 to indicate successful execution.

### How to Compile and Run:
1. Save the code in a file named `even_odd.c`.
2. Open a terminal and navigate to the directory where the file is saved.
3. Compile the program using a C compiler, for example, `gcc`:
```bash
gcc even_odd.c -o even_odd
```
4. Run the executable:
```bash
./even_odd
```
5. Follow the prompts in the terminal to test the program with different integers.

Related Questions