Wednesday, 12 August 2026

Break Statements in C

Controlling the flow of execution in programming is essential for building efficient and dynamic programs. The break statement in C programming allows you to immediately exit a loop or switch case when a specific condition is met, preventing unnecessary execution and giving better control over program behavior.

Instead of waiting for a loop to complete all its iterations, the break statement provides a direct way to stop execution at the right moment. This makes it especially useful in scenarios such as search operations, menu-driven programs, and error handling.

Let’s understand its syntax, usage, and practical examples so you can use it effectively in your programs.

 

What is Break Statement in C Programming?

The break statement in C is a control statement used to terminate the execution of a loop or a switch case prematurely. When the break statement is encountered, the program exits the loop or block and continues execution from the next statement outside it.

 

This makes it useful for interrupting repetitive tasks or ending processes when specific conditions are met.

 

Real-Life Example:

Imagine you’re searching for a book on a shelf. Once you find it, you stop searching and move on to the next task. Similarly, break stops a loop when a condition is satisfied.

 

Practical Example:

#include <stdio.h>

int main() {

    int i;

    for (i = 1; i <= 5; i++) {

        if (i == 3) {

            break;  // Exit the loop when i is 3

        }

        printf("%d\n", i);

    }

    return 0;

}

Run Code

 

Output:

1 

2

 

Explanation:

The loop stops when i == 3, and execution continues after the loop.

 

Syntax of Break Statement in C

break;

 

Components of the Break Statement

Keyword (break): The break keyword is a predefined statement in C. It tells the program to immediately exit the current loop or switch block.

 

Semicolon (;): The semicolon is required after the break keyword to terminate the statement.

 

Execution Context: The break statement is valid only inside: Loops in C (for, while, do while) and switch statement in C. It cannot be used outside these constructs.

 

C Break Statement in Loops

The break statement in C is used to exit a loop prematurely before the loop condition becomes false. It provides immediate termination of the loop and transfers control to the next statement following the loop.

 

How does Break work in Loops?

Condition Check: During loop execution, the condition for break is evaluated inside the loop body.

 

Break Execution: When the break statement is encountered, the loop stops executing immediately, even if the loop’s condition is still true.

 

Control Flow: Control exits the loop and resumes execution at the statement following the loop.

 

Example: Exit Loop on Specific Condition

#include <stdio.h>

int main() {

    int i;

    for (i = 1; i <= 5; i++) {

        if (i == 3) {  // Check the condition

            break;  // Exit the loop when i equals 3

        }

        printf("i = %d\n", i);

    }

    printf("Loop exited.\n");

    return 0;

}

Run Code

 

Output:

i = 1 

i = 2 

Loop exited.

 

Explanation:

The loop prints numbers from 1 to 2.

 

When i == 3, the break statement executes, and the loop exits.

 

Example: Breaking Out of an Infinite Loop

#include <stdio.h>

int main() {

    int i = 1;

    while (1) {  // Infinite loop

        printf("Iteration: %d\n", i);

        if (i == 3) {

            break;  // Exit when i equals 3

        }

        i++;

    }

    printf("Exited infinite loop.\n");

    return 0;

}

Run Code

 

Output:

Iteration: 1 

Iteration: 2 

Iteration: 3 

Exited infinite loop.

 

Explanation:

The infinite while (1) loop is controlled using the break statement.

 

When i == 3, the break statement terminates the loop.

 

C Break Statement in Switch Case

In a switch case in C programming, the break statement is used to terminate the execution of a particular case and exit the switch block. Without the break statement, the program continues to execute subsequent cases (fall-through behavior), even if they don’t match the condition.

 

How Break Works in Switch Case?

Condition Matching: The switch expression is evaluated, and the matching case is executed.

 

Terminate Case: When the break statement is encountered within the case, it stops further execution inside the switch.

 

Exit Switch: Control exits the switch block and continues with the code following it.

 

Syntax of Break in Switch Case

switch (expression) {

    case value1:

        // Code for case 1

        break;

    case value2:

        // Code for case 2

        break;

    default:

        // Default code

}

 

Example: Break in Switch Case

#include <stdio.h>

int main() {

    int choice = 2;

    switch (choice) {

        case 1:

            printf("You selected Option 1.\n");

            break;  // Exit after executing case 1

        case 2:

            printf("You selected Option 2.\n");

            break;  // Exit after executing case 2

        case 3:

            printf("You selected Option 3.\n");

            break;  // Exit after executing case 3

        default:

            printf("Invalid option selected.\n");

    }

    return 0;

}

Run Code

 

Output:

You selected Option 2.

Behavior Without Break Statement

 

Explanation:

The variable choice is assigned the value 2.

 

The switch statement evaluates the value of choice.

 

Since choice matches case 2, that block is executed.

 

The program prints: "You selected Option 2."

 

The break statement stops further execution inside the switch.

 

Control moves to the statement after the switch block.

 

Example: Behavior Without break Statement in Switch Case

#include <stdio.h>

 

int main() {

    int choice = 2;

 

    switch (choice) {

        case 1:

            printf("You selected Option 1.\n");

 

        case 2:

            printf("You selected Option 2.\n");

 

        case 3:

            printf("You selected Option 3.\n");

 

        default:

            printf("Invalid option selected.\n");

    }

 

    return 0;

}

Run Code

 

Output:

You selected Option 2.

You selected Option 3.

Invalid option selected.

 

Explanation:

The variable choice is assigned the value 2.

 

The switch statement matches case 2.

 

Since there is no break statement, execution continues to the next cases.

 

This behavior is called fall-through.

 

The program executes case 2, case 3, and then the default case.

 

Without break, all subsequent cases run until the switch block ends.

 

Nested Loops and Break Statement in C

In nested loops, one loop exists inside another, and the break statement plays an essential role in controlling their execution. The break statement, when used in nested loops, only exits the innermost loop where it is placed. The outer loops continue to execute unless explicitly terminated with additional logic or break statements.

 

How Break Works in Nested Loops?

Innermost Loop: The break statement exits the current (innermost) loop where it is written.

 

Outer Loop Continuation: After the innermost loop exits, the outer loop continues its next iteration, if applicable.

 

Selective Termination: To break out of multiple loops, specific logic or flags can be combined with the break statement.

 

Example: Break in Nested Loops

#include <stdio.h>

int main() {

    int i, j;

    for (i = 1; i <= 3; i++) {

        for (j = 1; j <= 3; j++) {

            if (j == 2) {

                break;  // Exits the inner loop

            }

            printf("i = %d, j = %d\n", i, j);

        }

    }

    return 0;

}

Run Code

 

Output

i = 1, j = 1 

i = 2, j = 1 

i = 3, j = 1

 

Explanation:

When j == 2, the break exits the inner loop. The outer loop (i) continues with its next iteration.

 

Example 2: Breaking Out of Both Loops

 

To exit both loops, use a flag variable or goto statement.

 

Uses of Break Statement in C

Below are the common uses of the break statement in C:

 

Exit Loops Prematurely: Allows immediate termination of loops (for, while, do while) when a specific condition is met, avoiding unnecessary iterations.

 

Terminate Infinite Loops: Used to safely exit intentionally infinite loops, such as while (1), when a certain event occurs.

 

Control Switch Statements: Prevents fall-through behavior by exiting a case block after executing its code in a switch statement.

 

Optimize Search Operations: Stops further iterations when a required value is found, saving time and resources.

 

Error Handling in Loops: Exits a loop if an error condition arises, allowing the program to handle the error outside the loop.

 

Nested Loops Control: Exits the innermost loop in nested loops, improving clarity and control over complex structures.

 

Menu-Driven Programs: Used in interactive applications to break out of loops or switch cases based on user input.

 

Simplify Logic: Reduces the need for complex conditional checks by providing a direct way to terminate loops or blocks.

 

Real-Time Monitoring: Breaks the loop when specific real-time conditions, like a sensor threshold or timeout, are met.

 

Avoid Redundant Iterations: Improves performance by avoiding unnecessary computations once the desired result is achieved.

Check Vowel or Consonants in C

Option 1: Vowel and Consonant Program in C

#include <stdio.h>

 

int main() {

   

    // Declare character variable

    char ch;

    printf("Enter a character: ");

    scanf("%c", &ch);

 

    // Check if the character is a vowel

    // using if-else

    if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||

        ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {

        printf("%c is a vowel.", ch);

    } else {

        printf("%c is a consonant.", ch);

    }

 

    return 0;

}

Run Code

 

Output:

Enter a character: A

A is a vowel.

 

Explanation:

Include Standard I/O Library: #include <stdio.h> enables the use of scanf() and printf() functions for input and output.

 

Declare Character Variable: char ch; stores the user-input character.

 

User Input: scanf("%c", &ch); reads a single character entered by the user.

 

Vowel Check with if Condition: Checks if ch is one of the vowels (a, e, i, o, u), both lowercase and uppercase.

 

Else Statement: If the character is not a vowel, it’s classified as a consonant.

 

Display Result: The program prints whether the character is a vowel or consonant.

 

This consonant and vowel program in C is a practical exercise in character classification using conditional checks. It helps build logic for text and string manipulation tasks.

 

 

Time Complexity Analysis

Time Complexity : O(1)

 

 

Space Complexity Analysis

Space Complexity : O(1)

 

Option 2: Vowel and Consonant Program in C Using switch

#include <stdio.h>

 

int main() {

   

    // Declare a character type variable

    char ch;

    printf("Enter a character: ");

    scanf("%c", &ch);

 

    // Using switch case for vowel or consonant

    switch (ch) {

        case 'a': case 'e': case 'i': case 'o': case 'u':

        case 'A': case 'E': case 'I': case 'O': case 'U':

            printf("%c is a vowel.", ch);

            break;

        default:

            printf("%c is a consonant.", ch);

    }

    return 0;

}

Run Code

 

Output:

Enter a character: o

o is a vowel.

 

Explanation:

This program checks if a character is a vowel in C program using switch-case. Each vowel (upper and lowercase) has a separate case. If none match, it defaults to “consonant.” This approach makes the program cleaner than using multiple if statements.

 

 

Time Complexity Analysis

Time Complexity : O(1)

 

 

Space Complexity Analysis

Space Complexity : O(1)

 

Option 3: C Program to Find Vowels and Consonants in String

#include <stdio.h>

#include <string.h>

 

int main() {

   

    // Declare a character type array

    char str[100];

    printf("Enter a string: ");

    gets(str);

 

    //Iterate over each element of the character array

    for (int i = 0; i < strlen(str); i++) {

        if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ||

            str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') {

            printf("%c is a vowel\n", str[i]);

        } else if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {

            printf("%c is a consonant\n", str[i]);

        }

    }

    return 0;

}

Run Code

 

Output:

Enter a string: WsCube

W is a consonant

s is a consonant

C is a consonant

u is a vowel

b is a consonant

e is a vowel

 

Explanation:

This C program to find vowels and consonants in a string checks each character in the input string and identifies it as either a vowel or a consonant, allowing text analysis and classification.

 

 

Time Complexity Analysis

Time Complexity : O(n)

 

 

Space Complexity Analysis

Space Complexity : O(n)

 

Option 4: C Program to Count Vowels and Consonants in String

#include <stdio.h>  

#include <string.h> 

 

int main() {

   

    // Declare a character array

    char str[100]; 

   

    // Counters for vowels and consonants

    int vowels = 0, consonants = 0; 

 

    printf("Enter a string: ");

   

    // Take input string from user

    gets(str); 

 

    // Loop through each character of the string

    for (int i = 0; i < strlen(str); i++) {

 

        // Check if the character is an alphabet (a-z or A-Z)

        if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z')) {

 

            // Check if the character is a vowel

            if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u' ||

                str[i] == 'A' || str[i] == 'E' || str[i] == 'I' || str[i] == 'O' || str[i] == 'U') {

 

                vowels++;  // Increase vowel count

 

            } else {

               

                // If not vowel, it is a consonant

                consonants++; 

            }

        }

    }

 

    printf("Vowels: %d\nConsonants: %d\n", vowels, consonants);

 

    return 0;

}

Run Code

 

Output:

Enter a string: WsCube tech

Vowels: 3

Consonants: 7

 

Explanation:

This C program to count vowels and consonants in a string iterates through each character, categorizing them as vowels or consonants and updating respective counters. It’s commonly used in text analysis for statistical purposes.

 

Time Complexity Analysis

Time Complexity : O(n)

 

 

Space Complexity Analysis

Space Complexity : O(n)

 

Option 5: Nearest Vowel Program in C

#include <stdio.h>

 

char nearestVowel(char ch) {

 

    // Convert uppercase letter to lowercase

    // for easier comparison

    if (ch >= 'A' && ch <= 'Z')

        ch += 32;

 

    // Return nearest vowel based on character range

    return (ch < 'e') ? 'a' :     // If character is before 'e', nearest vowel is 'a'

           (ch < 'i') ? 'e' :     // If before 'i', nearest vowel is 'e'

           (ch < 'o') ? 'i' :     // If before 'o', nearest vowel is 'i'

           (ch < 'u') ? 'o' :     // If before 'u', nearest vowel is 'o'

                        'u';      // Otherwise, nearest vowel is 'u'

}

 

int main() {

   

    char ch; 

 

    printf("Enter a character: ");

   

    // Take a single character input

    scanf("%c", &ch); 

 

    // Call function and display result

    printf("Nearest vowel to %c is %c", ch, nearestVowel(ch));

 

    return 0;

}

Run Code

 

Output:

Enter a character: g

Nearest vowel to g is e

 

Explanation:

This nearest vowel program in C finds the closest vowel to a given character alphabetically. It’s useful for tasks like text transformations, where vowel proximity matters.

 

Time Complexity Analysis:  Time Complexity : O(1)

 

Space Complexity Analysis: Space Complexity : O(1)

 

 

Program to make a simple Calculator

Option 1: Calculator Program in C Using switch case

#include <stdio.h>

 

int main() {

 

    // Declare variables for operator

    // and numbers

    char operator;

    double num1, num2;

 

    printf("Enter an operator (+, -, *, /): ");

    scanf("%c", &operator);

 

    // Take two numbers as input

    printf("Enter two numbers: ");

    scanf("%lf %lf", &num1, &num2);

 

    // Use switch-case to perform operation

    // based on operator

    switch (operator) {

 

        case '+':

       

            // Addition

            printf("%.2lf + %.2lf = %.2lf\n", num1, num2, num1 + num2);

            break;

 

        case '-':

       

            // Subtraction

            printf("%.2lf - %.2lf = %.2lf\n", num1, num2, num1 - num2);

            break;

 

        case '*':

       

            // Multiplication

            printf("%.2lf * %.2lf = %.2lf\n", num1, num2, num1 * num2);

            break;

 

        case '/':

       

            // Division (check for division by zero)

            if (num2 != 0)

                printf("%.2lf / %.2lf = %.2lf\n", num1, num2, num1 / num2);

            else

                printf("Division by zero is not allowed.\n");

            break;

 

        default:

       

            // Handle invalid operator

            printf("Invalid operator.\n");

    }

 

    return 0; 

}

Run Code

 

Output

Enter an operator (+, -, *, /): /

Enter two numbers: 900 10

900.00 / 10.00 = 90.00

 

Explanation

This C program for calculator uses switch-case statements to handle user input and determine the operation. Each arithmetic operation is mapped to a specific case, improving code readability and efficiency for multiple conditions.

 

This program is now complete, but you can check our C programs list to try more examples and improve your skills.

 

 

Time Complexity Analysis

Time Complexity : O(1)

 

 

Space Complexity Analysis

Space Complexity : O(1)

 

Option 2: C Program for Calculator Using if else

#include <stdio.h>

 

int main() {

 

    char operator;

    double num1, num2;

 

    printf("Enter an operator (+, -, *, /): ");

    scanf("%c", &operator);

 

    printf("Enter two numbers: ");

    scanf("%lf %lf", &num1, &num2);

 

    // Check operator using if-else statements

    if (operator == '+') {

 

        // Perform addition

        printf("%.2lf + %.2lf = %.2lf\n", num1, num2, num1 + num2);

 

    } else if (operator == '-') {

 

        // Perform subtraction

        printf("%.2lf - %.2lf = %.2lf\n", num1, num2, num1 - num2);

 

    } else if (operator == '*') {

 

        // Perform multiplication

        printf("%.2lf * %.2lf = %.2lf\n", num1, num2, num1 * num2);

 

    } else if (operator == '/') {

 

        // Perform division (no zero check here)

        printf("%.2lf / %.2lf = %.2lf\n", num1, num2, num1 / num2);

 

    } else {

 

        // Handle invalid operator input

        printf("Invalid operator.\n");

    }

 

    return 0; 

}

Run Code

 

Output

Enter an operator (+, -, *, /): *

Enter two numbers: 200 50

200.00 * 50.00 = 10000.00

 

Explanation

This calculator program in C using if-else evaluates the operation based on the operator entered by the user. The program performs addition, subtraction, multiplication, or division depending on the condition met. This approach is simple and intuitive for beginners learning conditional statements.

 

This example teaches some concepts, but not everything. For complete learning, follow a structured C tutorial.

 

 

Time Complexity Analysis

Time Complexity : O(1)

 

 

Space Complexity Analysis

Space Complexity : O(1)

 

Option 3: Simple Calculator Program in C Using Function

#include <stdio.h>

 

// Function to perform addition

double add(double a, double b) {

    return a + b;

}

 

// Function to perform subtraction

double subtract(double a, double b) {

    return a - b;

}

 

// Function to perform multiplication

double multiply(double a, double b) {

    return a * b;

}

 

// Function to perform division

double divide(double a, double b) {

    return a / b;

}

 

int main() {

 

    char operator;

    double num1, num2, result;

 

    printf("Enter an operator (+, -, *, /): ");

    scanf(" %c", &operator);

 

    printf("Enter two numbers: ");

    scanf("%lf %lf", &num1, &num2);

 

    // Use switch-case to call appropriate function

    switch (operator) {

 

        case '+':

 

            // Call addition function

            result = add(num1, num2);

            break;

 

        case '-':

 

            // Call subtraction function

            result = subtract(num1, num2);

            break;

 

        case '*':

 

            // Call multiplication function

            result = multiply(num1, num2);

            break;

 

        case '/':

 

            // Check for division by zero

            if (num2 != 0)

                result = divide(num1, num2);

            else {

                printf("Division by zero is not allowed.\n");

                return 0;  // Exit program

            }

            break;

 

        default:

       

            // Handle invalid operator

            printf("Invalid operator.\n");

            return 0;

    }

 

    printf("Result: %.2lf\n", result);

 

    return 0;

}

Run Code

 

Output

Enter an operator (+, -, *, /): +

Enter two numbers: 1043 383

Result: 1426.00

 

Explanation

This simple calculator program in C using functions defines separate functions for each arithmetic operation. This modular approach improves code reusability and readability, making it easier to extend the program.

 

 

Time Complexity Analysis

Time Complexity : O(1)

 

 

Space Complexity Analysis

Space Complexity : O(1)

 

Option 4: Simple Calculator Program in C Using Loop

#include <stdio.h>

 

int main() {

    char operator, choice;

    double num1, num2;

 

    do {

        printf("Enter an operator (+, -, *, /): ");

        scanf(" %c", &operator);

        printf("Enter two numbers: ");

        scanf("%lf %lf", &num1, &num2);

 

        switch (operator) {

            case '+': printf("%.2lf + %.2lf = %.2lf\n", num1, num2, num1 + num2); break;

            case '-': printf("%.2lf - %.2lf = %.2lf\n", num1, num2, num1 - num2); break;

            case '*': printf("%.2lf * %.2lf = %.2lf\n", num1, num2, num1 * num2); break;

            case '/':

                if (num2 != 0)

                    printf("%.2lf / %.2lf = %.2lf\n", num1, num2, num1 / num2);

                else

                    printf("Division by zero is not allowed.\n");

                break;

            default:

                printf("Invalid operator.\n");

        }

 

        printf("Do you want to perform another calculation? (y/n): ");

        scanf(" %c", &choice);

 

    } while (choice == 'y' || choice == 'Y');

 

    return 0;

}

Run Code

 

Output

Enter an operator (+, -, *, /): /

Enter two numbers: 22 9

22.00 / 9.00 = 2.44

 

Explanation

This C language calculator program uses a loop to allow multiple calculations without restarting the program. The user can continue performing operations until they choose to exit, making it interactive and user-friendly.

 

Time Complexity Analysis: Time Complexity : O(1)

 

Space Complexity Analysis: Space Complexity : O(1)

 

 

Scientific Calculator in C

Option 1: Scientific Calculator in C Using Switch-Case

Code:

#include <stdio.h>

 

// For mathematical functions like sqrt, pow, sin, etc.

#include <math.h>   

 

// Define constant value of PI

#define PI 3.14159265

 

int main() {

   

    // To store user choice

    int choice;

   

    // To store input numbers

    double num1, num2;

    

    // To store result of operation

    double result;         

 

    // Infinite loop to keep calculator running

    do {

       

        // Display menu

        printf("\n===== Scientific Calculator =====\n");

        printf("1. Addition\n2. Subtraction\n3. Multiplication\n4. Division\n");

        printf("5. Power (x^y)\n6. Square Root\n7. Sine\n8. Cosine\n9. Tangent\n");

        printf("10. Natural Log (ln)\n11. Log Base 10\n12. Exponential (e^x)\n");

        printf("13. Absolute Value\n14. Cube Root\n15. Modulus (fmod)\n");

        printf("16. Round\n17. Floor\n18. Ceil\n19. Exit\n");

 

        // Take user choice

        printf("Enter your choice (1-19): ");

        scanf("%d", &choice);

 

        // Decide input type (one number or two numbers)

        if (choice == 6 || (choice >= 7 && choice <= 14) || choice >= 16) {

           

            // Operations needing one number

            printf("Enter one number: ");

            scanf("%lf", &num1);

        }

        else if (choice >= 1 && choice <= 5 || choice == 15) {

           

            // Operations needing two numbers

            printf("Enter two numbers: ");

            scanf("%lf %lf", &num1, &num2);

        }

 

        // Perform operation using switch-case

        switch (choice) {

 

            // Addition

            case 1: result = num1 + num2; break;

           

            // Subtraction

            case 2: result = num1 - num2; break;

           

            // Multiplication

            case 3: result = num1 * num2; break;

 

            // Division with zero check

            case 4:

                if (num2 != 0)

                    result = num1 / num2;

                else {

                    printf("Error: Cannot divide by zero.\n");

                   

                    // Skip rest and go to next iteration

                    continue;

                }

                break;

 

            // Power

            case 5: result = pow(num1, num2); break;

           

            // Square root

            case 6: result = sqrt(num1); break;

           

            // Convert degree to radian

            case 7: result = sin(num1 * PI / 180); break;  

            case 8: result = cos(num1 * PI / 180); break;

            case 9: result = tan(num1 * PI / 180); break;

           

             // Natural log

            case 10: result = log(num1); break;

           

            // Base 10 log

            case 11: result = log10(num1); break;

           

            // e^x

            case 12: result = exp(num1); break;

           

            // Absolute value

            case 13: result = fabs(num1); break;

           

            // Cube root

            case 14: result = cbrt(num1); break;

           

            // Modulus

            case 15: result = fmod(num1, num2); break;

           

            // Round

            case 16: result = round(num1); break;

           

            // Floor

            case 17: result = floor(num1); break;

           

            // Ceil

            case 18: result = ceil(num1); break;           

 

            case 19:

                printf("Exiting Calculator.\n");

                return 0;

 

            default:

                printf("Invalid choice.\n");

                continue;

        }

 

        // Print result

        printf("Result = %.4lf\n", result);

 

    // Loop runs forever

    } while (1);

 

    return 0;

}

Run Code

 

Output:

===== Scientific Calculator =====

1. Addition

2. Subtraction

3. Multiplication

4. Division

5. Power (x^y)

6. Square Root

7. Sine

8. Cosine

9. Tangent

10. Natural Log (ln)

11. Log Base 10

12. Exponential (e^x)

13. Absolute Value

14. Cube Root

15. Modulus (fmod)

16. Round

17. Floor

18. Ceil

19. Exit

 

Enter your choice (1-19): 5

Enter two numbers: 5 5

Result = 3125.0000

 

Explanation:

This C program for scientific calculator supports 18 operations, including trigonometric, logarithmic, rounding, power, and modulus. For functions like sin, cos, and tan, degrees are converted to radians using PI / 180, ensuring accurate results (e.g., sin(90) = 1).

 

This is a perfect scientific calculator code in C language for academic projects and real-world use cases.

 

 

Time Complexity Analysis

Time Complexity : O(1)

 

 

Space Complexity Analysis

Space Complexity : O(1)

 

Option 2: C Program for Scientific Calculator Using Functions

Code:

#include <stdio.h>  

 

// For mathematical operations

#include <math.h>   

 

// Constant value of PI

#define PI 3.14159265 

 

// Basic arithmetic operations

double add(double a, double b) { return a + b; }

double sub(double a, double b) { return a - b; }

double mul(double a, double b) { return a * b; }

 

// Division with safe check

double divide(double a, double b) {

    return (b != 0) ? a / b : 0;

}

 

// Mathematical operations

double power(double a, double b) { return pow(a, b); }

double root(double a) { return sqrt(a); }

 

// Trigonometric functions (degree → radian)

double sine(double deg) { return sin(deg * PI / 180); }

double cosine(double deg) { return cos(deg * PI / 180); }

double tangent(double deg) { return tan(deg * PI / 180); }

 

// Logarithmic and exponential functions

double nat_log(double x) { return log(x); }

double log10_base(double x) { return log10(x); }

double exponential(double x) { return exp(x); }

 

// Other functions

double absolute(double x) { return fabs(x); }

double cube_root(double x) { return cbrt(x); }

double modulus(double a, double b) { return fmod(a, b); }

double round_val(double x) { return round(x); }

double floor_val(double x) { return floor(x); }

double ceil_val(double x) { return ceil(x); }

 

int main() {

   

    // User choice

    int choice;

   

    // Input values

    double x, y;     

 

    do {

       

        // Display menu

        printf("\n--- Scientific Calculator (Functions) ---\n");

        printf("1.Add 2.Subtract 3.Multiply 4.Divide 5.Power\n");

        printf("6.Sqrt 7.Sin 8.Cos 9.Tan 10.ln 11.Log10\n");

        printf("12.Exp 13.Abs 14.Cube Root 15.Mod 16.Round 17.Floor 18.Ceil 19.Exit\n");

 

        // Take input

        printf("Enter choice: ");

        scanf("%d", &choice);

 

        // Decide number of inputs required

        if (choice >= 6 && choice <= 14 || choice >= 16 && choice <= 18) {

            printf("Enter one number: ");

            scanf("%lf", &x);

        }

        else if (choice >= 1 && choice <= 5 || choice == 15) {

            printf("Enter two numbers: ");

            scanf("%lf %lf", &x, &y);

        }

 

        // Perform operations using function calls

        switch (choice) {

 

            case 1: printf("Result: %.4lf\n", add(x, y)); break;

            case 2: printf("Result: %.4lf\n", sub(x, y)); break;

            case 3: printf("Result: %.4lf\n", mul(x, y)); break;

 

            case 4:

                if (y != 0)

                    printf("Result: %.4lf\n", divide(x, y));

                else

                    printf("Error: Division by zero.\n");

                break;

 

            case 5: printf("Result: %.4lf\n", power(x, y)); break;

            case 6: printf("Result: %.4lf\n", root(x)); break;

            case 7: printf("Result: %.4lf\n", sine(x)); break;

            case 8: printf("Result: %.4lf\n", cosine(x)); break;

            case 9: printf("Result: %.4lf\n", tangent(x)); break;

            case 10: printf("Result: %.4lf\n", nat_log(x)); break;

            case 11: printf("Result: %.4lf\n", log10_base(x)); break;

            case 12: printf("Result: %.4lf\n", exponential(x)); break;

            case 13: printf("Result: %.4lf\n", absolute(x)); break;

            case 14: printf("Result: %.4lf\n", cube_root(x)); break;

            case 15: printf("Result: %.4lf\n", modulus(x, y)); break;

            case 16: printf("Result: %.4lf\n", round_val(x)); break;

            case 17: printf("Result: %.4lf\n", floor_val(x)); break;

            case 18: printf("Result: %.4lf\n", ceil_val(x)); break;

 

            case 19:

                printf("Exiting calculator.\n");

                return 0;

 

            default:

                printf("Invalid choice.\n");

        }

 

    // Infinite loop

    } while (1);

 

    return 0;

}

Run Code

 

Output:

--- Scientific Calculator (Functions) ---

1.Add 2.Subtract 3.Multiply 4.Divide 5.Power

6.Sqrt 7.Sin 8.Cos 9.Tan 10.ln 11.Log10

12.Exp 13.Abs 14.Cube Root 15.Mod 16.Round 17.Floor 18.Ceil 19.Exit

 

Enter choice: 6

Enter one number: 400

Result: 20.0000

 

Explanation:

This version of scientific calculator code in C uses modular programming, making it clean and maintainable. Each mathematical operation is written as a separate function, making the code easy to extend or test.

 

With proper degree-to-radian conversion, trigonometric functions now give correct results. This is a strong example of well-structured code for scientific calculator in C suitable for learning or real projects.

 

 

Time Complexity Analysis: Time Complexity : O(1)

 

Space Complexity Analysis: Space Complexity : O(1)

No comments:

Post a Comment