Search This Blog

Monday, 3 March 2025

How to write a simple calculator program in C using if else?

Creating a simple calculator program in C using if-else statements is a great way to practice your programming skills. Below is a step-by-step guide along with the complete code for a basic calculator that can perform addition, subtraction, multiplication, and division.

Step-by-Step Guide

  1. Include Necessary Headers: Start by including the standard input-output header file.
  2. Declare Variables: You'll need variables to store the two numbers, the operator, and the result.
  3. Get User Input: Prompt the user to enter two numbers and an operator.
  4. Use if-else Statements: Based on the operator entered, use if-else statements to perform the corresponding arithmetic operation.
  5. Display the Result: Print the result of the operation.
  6. Handle Division by Zero: Ensure that the program checks for division by zero to avoid errors.

Complete Code

#include <stdio.h>

int main() {
    float num1, num2, result;
    char operator;

    // Get user input
    printf("Enter first number: ");
    scanf("%f", &num1);
    printf("Enter an operator (+, -, *, /): ");
    scanf(" %c", &operator); // Note the space before %c to consume any leftover whitespace
    printf("Enter second number: ");
    scanf("%f", &num2);

    // Perform calculation based on the operator
    if (operator == '+') {
        result = num1 + num2;
        printf("%.2f + %.2f = %.2f\n", num1, num2, result);
    } else if (operator == '-') {
        result = num1 - num2;
        printf("%.2f - %.2f = %.2f\n", num1, num2, result);
    } else if (operator == '*') {
        result = num1 * num2;
        printf("%.2f * %.2f = %.2f\n", num1, num2, result);
    } else if (operator == '/') {
        if (num2 != 0) {
            result = num1 / num2;
            printf("%.2f / %.2f = %.2f\n", num1, num2, result);
        } else {
            printf("Error! Division by zero.\n");
        }
    } else {
        printf("Invalid operator! Please use +, -, *, or /.\n");
    }

    return 0;
}

Explanation of the Code

  1. Input Handling:

    • The program prompts the user to enter two numbers and an operator.
    • The scanf function is used to read the input values.
  2. Calculation Logic:

    • The program checks the operator using if-else statements.
    • Depending on the operator, it performs the corresponding arithmetic operation.
    • For division, it checks if the second number is zero to prevent division by zero.
  3. Output:

    • The result of the operation is printed to the console.
    • If the operator is invalid, an error message is displayed.

How to Compile and Run

  1. Save the code in a file named calculator.c.
  2. Open a terminal and navigate to the directory where the file is saved.
  3. Compile the program using the following command:
gcc calculator.c -o calculator

Run the program:

./calculator

You can now enter numbers and operators to perform calculations! This simple calculator program is a great starting point for learning C programming and can be expanded with more features as you become more comfortable with the language.

To-Do List Application in C

 2. To-Do List Application

Description: Build a simple command-line to-do list application that allows users to add, view, and delete tasks.

Key Features:

  • Add tasks with a description.
  • View all tasks.
  • Delete tasks by index.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_TASKS 100
#define TASK_LENGTH 100

char tasks[MAX_TASKS][TASK_LENGTH];
int task_count = 0;

void add_task(const char *task) {
    if (task_count < MAX_TASKS) {
        strcpy(tasks[task_count], task);
        task_count++;
    } else {
        printf("Task list is full!\n");
    }
}

void view_tasks() {
    if (task_count == 0) {
        printf("No tasks available.\n");
        return;
    }
    for (int i = 0; i < task_count; i++) {
        printf("%d: %s\n", i + 1, tasks[i]);
    }
}

void delete_task(int index) {
    if (index < 1 || index > task_count) {
        printf("Invalid task number!\n");
        return;
    }
    for (int i = index - 1; i < task_count - 1; i++) {
        strcpy(tasks[i], tasks[i + 1]);
    }
    task_count--;
}

int main() {
    int choice;
    char task[TASK_LENGTH];

    while (1) {
        printf("\n1. Add Task\n2. View Tasks\n3. Delete Task\n4. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
        getchar(); // Consume newline

        switch (choice) {
            case 1:
                printf("Enter task: ");
                fgets(task, TASK_LENGTH, stdin);
                task[strcspn(task, "\n")] = 0; // Remove newline
                add_task(task);
                break;
            case 2:
                view_tasks();
                break;
            case 3:
                printf("Enter task number to delete: ");
                int task_num;
                scanf("%d", &task_num);
                delete_task(task_num);
                break;
            case 4:
                exit(0);
            default:
                printf("Invalid choice!\n");
        }
    }
    return 0;
}

What is a simple calculator in C?

 

Simple Calculator

Description: Create a console-based calculator that can perform basic arithmetic operations such as addition, subtraction, multiplication, and division.

Key Features:

  • Input two numbers and an operator (+, -, *, /).
  • Display the result.
  • Handle division by zero.
#include <stdio.h>

int main() {
    char operator;
    float num1, num2, result;

    printf("Enter first number: ");
    scanf("%f", &num1);
    printf("Enter an operator (+, -, *, /): ");
    scanf(" %c", &operator);
    printf("Enter second number: ");
    scanf("%f", &num2);

    switch (operator) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            if (num2 != 0) {
                result = num1 / num2;
            } else {
                printf("Error! Division by zero.\n");
                return 1;
            }
            break;
        default:
            printf("Invalid operator!\n");
            return 1;
    }

    printf("Result: %.2f\n", result);
    return 0;
}

ગુજરાત રોજગાર સમાચાર Published On : 26-Feb-2025

 ગુજરાત રોજગાર સમાચાર   Published On : 26-Feb-2025

Please Click

Government Job At Gujarat State

🚀 Exciting Job Opportunities Ahead!

Get ready to take the next step in your career with the latest recruitment announcement! Here’s everything you need to know to apply successfully.


📅 Important Dates to Remember

  • 🗓️ Starting Date of Online Application28th February 2025 (from 13:00 hrs)
  • 🗓️ Last Date to Apply Online15th March 2025 (till 23:59 hrs)
  • 🗓️ Exam DateTo be announced

📈 Eligibility Criteria

👧 Age Limit & Relaxation

  • The age limit varies depending on the post.
  • Age relaxation is available as per government rules for reserved categories.

🎓 Educational Qualification

  • Candidates must meet the educational qualifications specific to the post they are applying for.
  • For detailed qualification criteria, please refer to the official notification.

🏦 Experience

  • Some positions may require prior work experience. Be sure to check the detailed advertisement for post-wise requirements.

💼 Salary & Pay Scale

Selected candidates will enjoy an attractive salary package along with applicable allowances, in line with government norms.


🌟 Selection Process

The selection process will consist of:

  1. Written Examination (Preliminary & Mains)
  2. Interview
  3. Document Verification

📂 How to Apply Online

Ready to apply? Follow these simple steps:

  1. Visit the official websiteGPSC Official Website or OJAS.
  2. Click on the “Apply Online” section.
  3. Register and fill in the required details.
  4. Upload necessary documents (photograph, signature, etc.).
  5. Pay the application fee (if applicable).
  6. Submit your application and take a printout for future reference.

📖 Important Links



📝 Vacancy Details: Exciting Opportunities Await!

A wide range of vacancies has been announced across various departments, offering numerous opportunities for candidates looking to advance their careers. Below is a comprehensive list of available positions. For a complete breakdown of vacancies, candidates are encouraged to check the official website.


Available Positions

Administrative and Management Roles

  • GPSC/202425/132: Administrative Officer, Class-2 (AYUSH)
  • GPSC/202425/136: Accounts Officer, Class-1, Gujarat Accounts Service
  • GPSC/202425/137: Deputy Director, Industrial Safety and Health, Class-1
  • GPSC/202425/141: Assistant Commissioner of Labour, Gujarat Labour Services, Class-1
  • GPSC/202425/157: Assistant Director of Insurance, Class-2, Finance Department
  • GPSC/202425/158: Programme Officer/Assistant Director, Class-1, Women and Child Development Department
  • GPSC/202425/238: Deputy Manager (Finance & Accounts), Class-2 (GWSSB)
  • GPSC/202425/239: Office Superintendent, Class-2 (GWSSB)

Engineering and Technical Positions

  • GPSC/202425/135: Assistant Conservator of Forest and Range Forest Officer, Class-2
  • GPSC/202425/144: Agriculture Engineer, Gujarat Agriculture Service, Class-2
  • GPSC/202425/146: Assistant Regional Transport Officer/Assistant Director of Transport, Class-2, Ports and Transport Department
  • GPSC/202425/149: Executive Engineer (Mechanical), Class-1, Under Narmada, Water Resources, Water Supply and Kalpsar Department
  • GPSC/202425/150: Assistant Director (F.S), (Geology and Mining) Class-1, Industries and Mines
  • GPSC/202425/235: Assistant Engineer (Mechanical), Class-2 (GWSSB)
  • GPSC/202425/236: Assistant Engineer (Civil), Class-2 (GWSSB)

Teaching and Academic Roles

  • GPSC/202425/159: Assistant Professor, Instrumentation and Control Engineering in Government Engineering College, GES, Class-2
  • GPSC/202425/160: Assistant Professor, Electrical Engineering in Government Engineering College, GES, Class-2
  • GPSC/202425/161: Assistant Professor, Electronics and Communication in Government Engineering College, GES, Class-2
  • GPSC/202425/162: Assistant Professor, Applied Mechanics in Government Engineering College, GES, Class-2
  • GPSC/202425/163: Assistant Professor, Civil Engineering in Government Engineering College, GES, Class-2
  • GPSC/202425/164: Assistant Professor, Power Electronics in Government Engineering College, GES, Class-2
  • GPSC/202425/165: Assistant Professor, Industrial Engineering in Government Engineering College, GES, Class-2
  • GPSC/202425/166: Assistant Professor, Plastic Engineering in Government Engineering College, GES, Class-2
  • GPSC/202425/167: Assistant Professor, Metallurgy in Government Engineering College, GES, Class-2
  • GPSC/202425/168: Assistant Professor, Rubber in Government Engineering College, GES, Class-2
  • GPSC/202425/169: Assistant Professor, Environmental Engineering in Government Engineering College, GES, Class-2
  • GPSC/202425/170: Assistant Professor, Information and Technology in Government Engineering College, GES, Class-2
  • GPSC/202425/171: Assistant Professor, Computer Engineering in Government Engineering College, GES, Class-2
  • GPSC/202425/172: Assistant Professor, Textile Engineering in Government Engineering College, GES, Class-2
  • GPSC/202425/173: Assistant Professor, Biomedical Engineering in Government Engineering College, GES, Class-2
  • GPSC/202425/174: Assistant Professor, Mechanical Engineering in Government Engineering College, GES, Class-2
  • GPSC/202425/175: Assistant Professor, Automobile Engineering in Government Engineering College, GES, Class-2
  • GPSC/202425/176: Assistant Professor, Chemical Engineering in Government Engineering College, GES, Class-2
  • GPSC/202425/177: Assistant Professor, Mining Engineering in Government Engineering College, GES, Class-2
  • GPSC/202425/178: Assistant Professor, Production Engineering in Government Engineering College, G