Wednesday, 2 September 2026

Basic C Programs with Output for Beginners

Introduction to C Programming: Basic C Programs with Output for Beginners

C programming is one of the most popular and powerful programming languages for beginners. It was developed by Dennis Ritchie at Bell Laboratories. C is often called a foundation programming language because many modern programming languages such as C++, Java, and others have been influenced by C.

C programming is widely used in system programming, operating systems, embedded systems, application development, and software development. Learning basic C programs helps students understand important programming concepts such as variables, data types, input and output, operators, expressions, and conditional statements.

📑 C Programs Covered in This Tutorial

  1. Hello World Program in C
  2. Sum of Two Numbers in C
  3. Average of Three Numbers in C
  4. Arithmetic Operations on Two Numbers in C
  5. Simple Interest Program in C
  6. Temperature Conversion Program in C
  7. Maximum of Three Numbers Using Conditional Operator

1. Program to Display Hello Message in C

The following is a simple Hello World program in C. It uses the printf() function to display a message on the screen.

📌 C Program

#include <stdio.h>

int main()
{
    printf("Hello, Welcome to C Programming!");
    
    return 0;
}

💻 Output

Hello, Welcome to C Programming!

2. Program to Find Sum of Two Numbers in C

This C program takes two numbers as input from the user using the scanf() function and calculates their sum using the addition operator +.

📌 C Program

#include <stdio.h>

int main()
{
    int num1, num2, sum;

    printf("Enter first number: ");
    scanf("%d", &num1);

    printf("Enter second number: ");
    scanf("%d", &num2);

    sum = num1 + num2;

    printf("Sum = %d", sum);

    return 0;
}

💻 Sample Output

Enter first number: 10
Enter second number: 20
Sum = 30

3. Program to Find Average of Three Numbers in C

This program accepts three numbers from the user and calculates their average. The float data type is used to store decimal values.

📌 Formula

Average = (Number1 + Number2 + Number3) / 3

📌 C Program

#include <stdio.h>

int main()
{
    float num1, num2, num3, average;

    printf("Enter three numbers: ");
    scanf("%f %f %f", &num1, &num2, &num3);

    average = (num1 + num2 + num3) / 3;

    printf("Average = %.2f", average);

    return 0;
}

💻 Sample Output

Enter three numbers: 10 20 30
Average = 20.00

4. Program to Perform All Four Arithmetic Operations in C

This program performs the four basic arithmetic operations on two numbers: addition, subtraction, multiplication, and division.

📌 Arithmetic Operators Used in C

  • + for Addition
  • - for Subtraction
  • * for Multiplication
  • / for Division

📌 C Program

#include <stdio.h>

int main()
{
    float num1, num2;

    printf("Enter two numbers: ");
    scanf("%f %f", &num1, &num2);

    printf("\nAddition = %.2f", num1 + num2);
    printf("\nSubtraction = %.2f", num1 - num2);
    printf("\nMultiplication = %.2f", num1 * num2);

    if(num2 != 0)
        printf("\nDivision = %.2f", num1 / num2);
    else
        printf("\nDivision is not possible because divisor is zero.");

    return 0;
}

💻 Sample Output

Enter two numbers: 20 5

Addition = 25.00
Subtraction = 15.00
Multiplication = 100.00
Division = 4.00

5. Program to Find Simple Interest in C

This C program calculates simple interest by taking the principal amount, rate of interest, and time from the user.

📌 Simple Interest Formula

Simple Interest = (Principal × Rate × Time) / 100

📌 C Program

#include <stdio.h>

int main()
{
    float principal, rate, time, simpleInterest;

    printf("Enter Principal Amount: ");
    scanf("%f", &principal);

    printf("Enter Rate of Interest: ");
    scanf("%f", &rate);

    printf("Enter Time in Years: ");
    scanf("%f", &time);

    simpleInterest = (principal * rate * time) / 100;

    printf("Simple Interest = %.2f", simpleInterest);

    return 0;
}

💻 Sample Output

Enter Principal Amount: 10000
Enter Rate of Interest: 5
Enter Time in Years: 2

Simple Interest = 1000.00

6. Program for Temperature Conversion in C

This program converts temperature from Celsius to Fahrenheit.

📌 Temperature Conversion Formula

Fahrenheit = (Celsius × 9 / 5) + 32

📌 C Program

#include <stdio.h>

int main()
{
    float celsius, fahrenheit;

    printf("Enter temperature in Celsius: ");
    scanf("%f", &celsius);

    fahrenheit = (celsius * 9 / 5) + 32;

    printf("Temperature in Fahrenheit = %.2f", fahrenheit);

    return 0;
}

💻 Sample Output

Enter temperature in Celsius: 25

Temperature in Fahrenheit = 77.00

7. Program to Find Maximum of Three Numbers Using Conditional Operator in C

This program finds the largest number among three numbers using the conditional operator. The conditional operator ? : is also known as the ternary operator in C programming.

📌 Syntax of Conditional Operator

condition ? expression1 : expression2;

📌 C Program

#include <stdio.h>

int main()
{
    int a, b, c, max;

    printf("Enter three numbers: ");
    scanf("%d %d %d", &a, &b, &c);

    max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);

    printf("Maximum number = %d", max);

    return 0;
}

💻 Sample Output

Enter three numbers: 10 25 18

Maximum number = 25

📚 Summary of Basic C Programs

These basic C programs are useful for beginners who are learning C programming and preparing for programming practicals, assignments, viva questions, and coding practice.

Program No. C Program Name
1 Hello World Program in C
2 Sum of Two Numbers in C
3 Average of Three Numbers in C
4 Four Arithmetic Operations in C
5 Simple Interest Program in C
6 Temperature Conversion Program in C
7 Maximum of Three Numbers Using Conditional Operator in C

Program to Calculate the Area of a Circle

Aim

To write a C program to calculate the area of a circle.

Formula

Area of Circle = Ï€ × r × r

Where r is the radius of the circle and π = 3.14159.

C Program

#include <stdio.h>

int main()
{
    float radius, area;

    printf("Enter the radius of the circle: ");
    scanf("%f", &radius);

    area = 3.14159 * radius * radius;

    printf("Area of the circle = %.2f", area);

    return 0;
}

Sample Output

Enter the radius of the circle: 5
Area of the circle = 78.54

Online Area of Circle Calculator

Enter the radius below to calculate the area of the circle:




Example

If the radius of the circle is 5 units:

Area = Ï€ × r × r
= 3.14159 × 5 × 5
= 78.54 square units

C Program to Find Square Root Without Using sqrt() Function

In this C program, we will learn how to find the square root of a number without using the built-in sqrt() function. This is useful for beginners to understand how a square root can be calculated using a simple loop and approximation.

What is a Square Root?

The square root of a number is a value which, when multiplied by itself, gives the original number.

Example:

5 × 5 = 25
Therefore, √25 = 5

C Program

The following program finds the square root approximately without using sqrt().

#include <stdio.h>

int main()
{
    float num, i;

    printf("Enter a number: ");
    scanf("%f", &num);

    i = 0;

    while (i * i <= num)
    {
        i = i + 0.01;
    }
i=i-0.01;
    printf("Square root of %.2f is approximately %.2f", num, i);

    return 0;
}

How Does the Program Work?

Suppose the user enters:

25

Initially:

i = 0

The while loop checks whether:

i * i <= num

The value of i is gradually increased:

0.00
0.01
0.02
0.03
...
4.98
4.99
5.00

When i = 5:

5 × 5 = 25

Therefore, the square root is approximately 5.

What Does i = i + 0.01 Mean?

The statement:

i = i + 0.01;

means that 0.01 is added to the current value of i each time the loop runs.

For example:

i = 0
i = 0.01
i = 0.02
i = 0.03
...
i = 4.99
i = 5.00

What If We Use i = i + 0.1?

We can also write:

i = i + 0.1;

In this case, the value increases by 0.1 each time:

0
0.1
0.2
0.3
0.4
...
4.8
4.9
5.0

This makes the program faster because fewer iterations are required, but the answer is less precise.

0.1 vs 0.01

Increment Accuracy Speed
i = i + 1 Low Fast
i = i + 0.1 About 1 decimal place Faster
i = i + 0.01 About 2 decimal places Slower
i = i + 0.001 About 3 decimal places More iterations

Example Output

Enter a number: 25
Square root of 25.00 is approximately 5.01

The result may show 5.01 because the loop stops after the value becomes slightly greater than the actual square root.

Key Points

  • No sqrt() function is used.
  • The program uses a while loop.
  • i * i is used to check the square of the current value.
  • i = i + 0.01 gradually increases the value of i.
  • A smaller increment provides better approximation but requires more iterations.

Conclusion

This simple C program demonstrates how a square root can be approximated without using the built-in sqrt() function. It is a good beginner example for understanding loops, floating-point numbers, conditions, and approximation.

C Program to Calculate Electricity Bill

In this C program, we will learn how to calculate an electricity bill based on the number of units consumed. The program uses if-else conditions to apply different rates for different ranges of electricity consumption.

What is an Electricity Bill?

An electricity bill is generally calculated according to the number of electricity units consumed. Different unit ranges may have different rates.

For this example, we will use the following rates:

Units Consumed Rate per Unit
0 – 100 units ₹5
101 – 200 units ₹7
201 – 300 units ₹10
Above 300 units ₹12

These rates are used only for learning the C programming concept. Actual electricity tariffs vary by electricity provider and consumer category.

C Program

#include <stdio.h>

int main()
{
    int units;
    float bill;

    printf("Enter electricity units consumed: ");
    scanf("%d", &units);

    if (units <= 100)
    {
        bill = units * 5;
    }
    else if (units <= 200)
    {
        bill = (100 * 5) + ((units - 100) * 7);
    }
    else if (units <= 300)
    {
        bill = (100 * 5) + (100 * 7) + ((units - 200) * 10);
    }
    else
    {
        bill = (100 * 5) + (100 * 7) + (100 * 10)
             + ((units - 300) * 12);
    }

    printf("Electricity Bill = Rs. %.2f", bill);

    return 0;
}

How Does the Program Work?

First, the program asks the user to enter the number of electricity units consumed.

Enter electricity units consumed: 250

The program then checks the number of units using if-else if-else statements.

Example: 250 Units

Suppose the consumer has used 250 units.

The calculation will be:

First 100 units:
100 × ₹5 = ₹500

Next 100 units:
100 × ₹7 = ₹700

Remaining 50 units:
50 × ₹10 = ₹500

Total Bill:
₹500 + ₹700 + ₹500 = ₹1700

Example Output

Enter electricity units consumed: 250
Electricity Bill = Rs. 1700.00

Understanding the Condition

The first condition checks whether the units are less than or equal to 100:

if (units <= 100)
{
    bill = units * 5;
}

If the units are between 101 and 200, the first 100 units are charged at ₹5 and the remaining units are charged at ₹7.

bill = (100 * 5) + ((units - 100) * 7);

Similarly, for units between 201 and 300, the program calculates the charges for the first 100 units, the next 100 units, and then the remaining units separately.

Why Do We Use (units - 100)?

Suppose the user enters 150 units.

The first 100 units are already charged at ₹5. Therefore, only the remaining 50 units need to be charged at ₹7.

150 - 100 = 50

Therefore:

100 × ₹5 = ₹500
50 × ₹7  = ₹350

Total = ₹850

Key Points

  • The program takes electricity consumption in units as input.
  • if-else if-else is used to select the appropriate slab.
  • Each electricity slab has a different rate.
  • The bill is calculated progressively for higher unit consumption.
  • %.2f displays the bill with two digits after the decimal point.

Conclusion

This C program is a useful beginner example for understanding if-else conditions, arithmetic operators, user input, and slab-based calculations. Similar logic can be used in programs for calculating water bills, telephone bills, income tax, and other charges.

C Program to Print Numbers from 1 to N Using While Loop

In this C program, we will take a number N from the user and print all the numbers from 1 to N using a while loop.

C Program

#include <stdio.h>

int main()
{
    int n, i = 1;

    printf("Enter the value of n: ");
    scanf("%d", &n);

    while (i <= n)
    {
        printf("%d ", i);
        i++;
    }

    return 0;
}

How the Program Works

  1. The user enters the value of n.
  2. The variable i is initialized to 1.
  3. The while loop checks whether i <= n.
  4. If the condition is true, the value of i is printed.
  5. The statement i++ increases the value of i by 1.
  6. The loop continues until i becomes greater than n.

Sample Output

Enter the value of n: 10
1 2 3 4 5 6 7 8 9 10

Dry Run

i Condition (i <= n) Output i++
1 1 <= 10 → True 1 2
2 2 <= 10 → True 2 3
3 3 <= 10 → True 3 4
... ... ... ...
10 10 <= 10 → True 10 11
11 11 <= 10 → False Loop stops -

Important Points

  • while is an entry-controlled loop.
  • The loop condition is checked before executing the loop body.
  • i++ is necessary; otherwise, the loop may become an infinite loop.
  • The program prints numbers starting from 1 up to the value entered by the user.

Conclusion

This is a simple example of using a while loop in C. It is useful for understanding initialization, condition checking, and incrementing a loop variable.

🎯 Practice is the Key to Learning C Programming!

These basic C programs help beginners understand important concepts such as input and output, variables, arithmetic operators, conditional operators, and mathematical calculations in C programming. Try changing the input values and experiment with these programs to improve your programming skills.

C If-Else Programs with Examples and Output

The if-else statement is used in C programming to make decisions. It checks a condition and executes a particular block of code depending on whether the condition is true or false.

1. Check Whether Age is Greater Than 18 Using if-else

This program takes the age of a person and checks whether the person is greater than 18 years old.

#include <stdio.h>

int main()
{
    int age;

    printf("Enter your age: ");
    scanf("%d", &age);

    if (age > 18)
    {
        printf("You are greater than 18 years old.");
    }
    else
    {
        printf("You are 18 years old or younger.");
    }

    return 0;
}

Output

Enter your age: 21
You are greater than 18 years old.

2. Check Positive, Negative or Zero Using Nested if-else

A nested if-else means using one if-else statement inside another if-else statement.

#include <stdio.h>

int main()
{
    int num;

    printf("Enter a number: ");
    scanf("%d", &num);

    if (num >= 0)
    {
        if (num == 0)
        {
            printf("The number is zero.");
        }
        else
        {
            printf("The number is positive.");
        }
    }
    else
    {
        printf("The number is negative.");
    }

    return 0;
}

Output 1

Enter a number: 15
The number is positive.

Output 2

Enter a number: -8
The number is negative.

Output 3

Enter a number: 0
The number is zero.

3. Grade Checking Using else-if

The else-if ladder is useful when we have multiple conditions to check. The following program displays a grade according to the marks obtained.

#include <stdio.h>

int main()
{
    int marks;

    printf("Enter your marks: ");
    scanf("%d", &marks);

    if (marks >= 90)
    {
        printf("Grade A");
    }
    else if (marks >= 80)
    {
        printf("Grade B");
    }
    else if (marks >= 70)
    {
        printf("Grade C");
    }
    else if (marks >= 60)
    {
        printf("Grade D");
    }
    else if (marks >= 40)
    {
        printf("Grade E");
    }
    else
    {
        printf("Fail");
    }

    return 0;
}

Output

Enter your marks: 85
Grade B

4. Double Condition Using && (AND Operator)

The && operator is called the logical AND operator. Both conditions must be true for the complete condition to be true.

Example: A student is eligible for admission if the marks are 50 or more and the age is 18 or more.

#include <stdio.h>

int main()
{
    int marks, age;

    printf("Enter your marks: ");
    scanf("%d", &marks);

    printf("Enter your age: ");
    scanf("%d", &age);

    if (marks >= 50 && age >= 18)
    {
        printf("You are eligible.");
    }
    else
    {
        printf("You are not eligible.");
    }

    return 0;
}

Output

Enter your marks: 65
Enter your age: 20
You are eligible.

5. Double Condition Using || (OR Operator)

The || operator is called the logical OR operator. If at least one of the conditions is true, the complete condition becomes true.

Example: A student can participate if they have a valid ID card or a valid registration number.

#include <stdio.h>

int main()
{
    int id, registration;

    printf("Enter ID card status (1 for Yes, 0 for No): ");
    scanf("%d", &id);

    printf("Enter registration status (1 for Yes, 0 for No): ");
    scanf("%d", &registration);

    if (id == 1 || registration == 1)
    {
        printf("You can participate.");
    }
    else
    {
        printf("You cannot participate.");
    }

    return 0;
}

Output

Enter ID card status (1 for Yes, 0 for No): 0
Enter registration status (1 for Yes, 0 for No): 1
You can participate.

Summary

Concept Purpose
if-else Checks one condition and chooses between two alternatives.
Nested if-else Places an if-else statement inside another if-else statement.
else-if Checks multiple conditions one after another.
&& AND – both conditions must be true.
|| OR – at least one condition must be true.

1. Star Right-Angled Pyramid

C Program

#include <stdio.h>

int main()
{
    int i, j, n;

    printf("Enter number of rows: ");
    scanf("%d", &n);

    for(i = 1; i <= n; i++)
    {
        for(j = 1; j <= i; j++)
        {
            printf("* ");
        }
        printf("\n");
    }

    return 0;
}

Output

Enter number of rows: 5

*
* *
* * *
* * * *
* * * * *

2. Inverted Star Pyramid

C Program

#include <stdio.h>

int main()
{
    int i, j, n;

    printf("Enter number of rows: ");
    scanf("%d", &n);

    for(i = n; i >= 1; i--)
    {
        for(j = 1; j <= i; j++)
        {
            printf("* ");
        }
        printf("\n");
    }

    return 0;
}

Output

Enter number of rows: 5

* * * * *
* * * *
* * *
* *
*

3. Number Pyramid

C Program

#include <stdio.h>

int main()
{
    int i, j, n;

    printf("Enter number of rows: ");
    scanf("%d", &n);

    for(i = 1; i <= n; i++)
    {
        for(j = 1; j <= i; j++)
        {
            printf("%d ", j);
        }
        printf("\n");
    }

    return 0;
}

Output

Enter number of rows: 5

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

These examples are useful for beginners learning decision-making statements in C programming.

4. Centered Star Pyramid

C Program

#include <stdio.h>

int main()
{
    int i, j, n;

    printf("Enter number of rows: ");
    scanf("%d", &n);

    for(i = 1; i <= n; i++)
    {
        for(j = 1; j <= n - i; j++)
        {
            printf(" ");
        }

        for(j = 1; j <= 2 * i - 1; j++)
        {
            printf("*");
        }

        printf("\n");
    }

    return 0;
}

Output

Enter number of rows: 5

    *
   ***
  *****
 *******
*********
Row 1 → " " Row 2 → " " Row 3 → " " Row 4 → " " Row 5 → ""8 Row 1 → 1 star Row 2 → 3 stars Row 3 → 5 stars Row 4 → 7 stars Row 5 → 9 stars Row 1: 4 spaces + 1 star * Row 2: 3 spaces + 3 stars *** Row 3: 2 spaces + 5 stars ***** Row 4: 1 space + 7 stars ******* Row 5: 0 spaces + 9 stars *********

5. Number Palindrome Pyramid

C Program

#include <stdio.h>

int main()
{
    int i, j, n;

    printf("Enter number of rows: ");
    scanf("%d", &n);

    for(i = 1; i <= n; i++)
    {
        for(j = 1; j <= n - i; j++)
        {
            printf(" ");
        }

        for(j = i; j >= 1; j--)
        {
            printf("%d", j);
        }

        for(j = 2; j <= i; j++)
        {
            printf("%d", j);
        }

        printf("\n");
    }

    return 0;
}

Output

Enter number of rows: 5

    1
   121
  12321
 1234321
123454321
```html

Switch Case in C Programming

The switch-case statement in C is used to select one option from multiple choices. It is useful when a program has several fixed choices.

Syntax of Switch Case

switch(expression)
{
    case value1:
        // statements
        break;

    case value2:
        // statements
        break;

    default:
        // statements
}

Program 1: Display Day Using Switch Case

Question: Write a C program to enter a number from 1 to 7 and display the corresponding day of the week using switch-case.

Solution

#include <stdio.h>

int main()
{
    int day;

    printf("Enter day number (1-7): ");
    scanf("%d", &day);

    switch(day)
    {
        case 1:
            printf("Monday");
            break;

        case 2:
            printf("Tuesday");
            break;

        case 3:
            printf("Wednesday");
            break;

        case 4:
            printf("Thursday");
            break;

        case 5:
            printf("Friday");
            break;

        case 6:
            printf("Saturday");
            break;

        case 7:
            printf("Sunday");
            break;

        default:
            printf("Invalid day number");
    }

    return 0;
}

Output

Enter day number (1-7): 3
Wednesday

Program 2: Simple Calculator Using Switch Case

Question: Write a C program to perform addition, subtraction, multiplication, or division using switch-case.

Solution

#include <stdio.h>

int main()
{
    float a, b;
    char op;

    printf("Enter first number: ");
    scanf("%f", &a);

    printf("Enter operator (+, -, *, /): ");
    scanf(" %c", &op);

    printf("Enter second number: ");
    scanf("%f", &b);

    switch(op)
    {
        case '+':
            printf("Result = %.2f", a + b);
            break;

        case '-':
            printf("Result = %.2f", a - b);
            break;

        case '*':
            printf("Result = %.2f", a * b);
            break;

        case '/':
            if(b != 0)
            {
                printf("Result = %.2f", a / b);
            }
            else
            {
                printf("Division by zero is not possible");
            }
            break;

        default:
            printf("Invalid operator");
    }

    return 0;
}

Output

Enter first number: 20
Enter operator (+, -, *, /): *
Enter second number: 5
Result = 100.00

Important Point: break Statement

The break statement is used to stop the execution of the switch after the matching case is executed.

If break is missing, the program may continue executing the next cases. This is called fall-through.

Example Without break

switch(choice)
{
    case 1:
        printf("One");

    case 2:
        printf("Two");

    case 3:
        printf("Three");
}

If the value of choice is 1, the output can be:

One
Two
Three

Therefore, break is normally used after each case.

```

C Programming Programs with Output

Learn important C programs with simple explanations, source code, and sample outputs. These examples are useful for beginners and practical examinations.

C Program: Check Leap Year

A leap year has 366 days. Use the following program to check a year.

Source Code

#include <stdio.h>

int main()
{
    int year;

    printf("Enter a year: ");
    scanf("%d", &year);

    if (year % 400 == 0 ||
       (year % 4 == 0 && year % 100 != 0))
        printf("Leap Year");
    else
        printf("Not a Leap Year");

    return 0;
}

Output

Enter a year: 2024
Leap Year

Explanation: The program uses the modulus operator (%) to check divisibility by 4, 100, and 400.


C Program to Check Palindrome Number

A palindrome number remains the same when its digits are reversed. For example, 121 reversed is also 121.

C Program

#include <stdio.h>

int main()
{
    int n, temp, digit, reverse = 0;

    printf("Enter a number: ");
    scanf("%d", &n);

    if (n < 0)
    {
        printf("Not a Palindrome");
        return 0;
    }

    temp = n;

    while (temp > 0)
    {
        digit = temp % 10;
        reverse = reverse * 10 + digit;
        temp /= 10;
    }

    if (n == reverse)
        printf("%d is a Palindrome", n);
    else
        printf("%d is not a Palindrome", n);

    return 0;
}

Output

Enter a number: 121
121 is a Palindrome

Explanation of the Code

  • n: Stores the number entered by the user.

  • temp: Stores a copy of the original number.

  • digit: Stores the last digit of the number.

  • reverse: Stores the number in reverse order.

How the program works:

  1. The user enters a number, such as 121.

  2. temp = n saves a copy of the original number.

  3. digit = temp % 10 extracts the last digit. For 121, the last digit is 1.

  4. reverse = reverse * 10 + digit adds the extracted digit to the reversed number.

  5. temp /= 10 removes the last digit.

  6. The loop repeats until temp becomes 0.

  7. Finally, the program compares n and reverse. If they are equal, the number is a palindrome.

else
        printf("Not a Prime Number");

    return 0;
}

Output

Enter a number: 7
Prime Number

Explanation:

  • The loop checks numbers from 1 to n.

  • If n is divisible by a number, count increases.

  • If count equals 2, the number is prime; otherwise, it is not prime.

C Program to Find Factorial of a Number

  • The factorial of a positive integer is the product of all integers from 1 to that number. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. The factorial of 0 is 1.

    C Program

    #include <stdio.h>
    
    int main()
    {
        int n, i;
       long fact = 1;
    
        printf("Enter a number (0 to 20): ");
        scanf("%d", &n);
    
        if (n < 0 || n > 20)
        {
            printf("Enter a number between 0 and 20");
        }
        else
        {
            for (i = 1; i <= n; i++)
                fact *= i;
    
            printf("Factorial of %d = %llu", n, fact);
        }
    
        return 0;
    }

    Output

    Enter a number (0 to 20): 5
    Factorial of 5 = 120

Basic C Programs with Output – Fibonacci Series and Arrays

  • In this tutorial, we will learn four basic C programs with simple explanations and outputs. These programs are useful for beginners who are learning C programming.

1. C Program to Print Fibonacci Series

Explanation

  • The Fibonacci series is a sequence of numbers in which each number is the sum of the previous two numbers. The series starts with 0 and 1.

    For example: 0, 1, 1, 2, 3, 5, 8, 13...

Program

  • #include <stdio.h>
    
    int main()
    {
        int n, a = 0, b = 1, c, i;
    
        printf("Enter number of terms: ");
        scanf("%d", &n);
    
        printf("Fibonacci Series: ");
    
        for(i = 1; i <= n; i++)
        {
            printf("%d ", a);
            c = a + b;
            a = b;
            b = c;
        }
    
        return 0;
    }
    

Output

  • Enter number of terms: 7
    Fibonacci Series: 0 1 1 2 3 5 8
    

Explanation of the Code

    • a = 0, b = 1 initializes the first two numbers.
    • scanf() accepts the number of terms from the user.
    • The for loop repeats until the required number of terms is printed.
    • c = a + b calculates the next number.
    • a = b and b = c update the values for the next iteration.

2. C Program to Input and Display a One-Dimensional Integer Array

Explanation

  • A one-dimensional array stores multiple values of the same data type under a single name. Each element is accessed using an index, starting from 0.

    In this program, the user enters five integers, and the program displays all the elements.

Program

  • #include <stdio.h>
    
    int main()
    {
        int a[5], i;
    
        printf("Enter 5 numbers:\n");
    
        for(i = 0; i < 5; i++)
        {
            scanf("%d", &a[i]);
        }
    
        printf("Array elements are:\n");
    
        for(i = 0; i < 5; i++)
        {
            printf("%d ", a[i]);
        }
    
        return 0;
    }
    

Output

  • Enter 5 numbers:
    10 20 30 40 50
    Array elements are:
    10 20 30 40 50
    

Explanation of the Code

    • int a[5] declares an integer array that can store five values.
    • The first for loop accepts five numbers from the user.
    • a[i] accesses the array element at index i.
    • The second for loop displays all five elements.
    • Array indexing starts at 0, so the indexes are 0, 1, 2, 3, and 4.

Simple C program

  • c
    #include <stdio.h>
    
    int main()
    {
        char name[] = "RAM";
    
        printf("%s", name);
    
        return 0;
    }

    Output:

    text
    RAM

    Although we wrote "RAM", C automatically stores a terminating '\0':

    R → A → M → '\0'

    When printf("%s", name) prints the string, it stops at the null character.

C Program to Input a Name and Print It as an Array of Characters

#include <stdio.h>

int main()
{
    char name[30];
    int i;

    printf("Enter your name: ");
    scanf("%29s", name);

    printf("Name as an array of characters:\n");

    for(i = 0; name[i] != '\0'; i++)
    {
        printf("%c\n", name[i]);
    }

    return 0;
}
Enter your name: RAHUL
Name as an array of characters:
R
A
H
U
L

3. C Program to Input and Display a One-Dimensional Character Array

Explanation

  • A character array stores characters such as letters and symbols. It can be used to store a name or a word.

    In this program, the user enters a word, and the program displays it character by character.

Program

  • #include <stdio.h>
    
    int main()
    {
        char name[30];
        int i;
    
        printf("Enter a word: ");
        scanf("%29s", name);
    
        printf("Characters are:\n");
    
        for(i = 0; name[i] != '\0'; i++)
        {
            printf("%c\n", name[i]);
        }
    
        return 0;
    }
    

Output

  • Enter a word: HELLO
    Characters are:
    H
    E
    L
    L
    O
    

Explanation of the Code

    • char name[30] declares a character array that can store up to 29 input characters plus the terminating null character '\0'.
    • scanf("%29s", name) reads a word from the user. It stops at whitespace.
    • The for loop continues until the null character '\0' is reached.
    • %c displays one character at a time.

    Note: This program accepts a single word. To accept a full name containing spaces, a function such as fgets() can be used.

4. C Program to Input and Display a Two-Dimensional Array

Explanation

  • A two-dimensional array stores data in rows and columns. It is useful for representing tables, matrices, and marks of students in different subjects.

    In this program, the user enters six numbers into a matrix containing two rows and three columns. The program then displays the matrix in table form.

Program

  • #include <stdio.h>
    
    int main()
    {
        int a[2][3], i, j;
    
        printf("Enter 6 elements:\n");
    
        for(i = 0; i < 2; i++)
        {
            for(j = 0; j < 3; j++)
            {
                scanf("%d", &a[i][j]);
            }
        }
    
        printf("The matrix is:\n");
    
        for(i = 0; i < 2; i++)
        {
            for(j = 0; j < 3; j++)
            {
                printf("%d\t", a[i][j]);
            }
    
            printf("\n");
        }
    
        return 0;
    }
    

Output

  • Enter 6 elements:
    10 20 30 40 50 60
    The matrix is:
    10      20      30
    40      50      60
    

Explanation of the Code

    • int a[2][3] declares an array with two rows and three columns.
    • The outer for loop controls the rows.
    • The inner for loop controls the columns.
    • a[i][j] accesses an element at row i and column j.
    • The first pair of loops accepts the six elements.
    • The second pair of loops displays the elements in matrix form.
    • printf("\n") moves the output to the next line after each row.

Conclusion

  • In this tutorial, we learned four basic C programming concepts:

    1. Fibonacci series using a for loop.
    2. One-dimensional integer arrays for storing numbers.
    3. One-dimensional character arrays for storing and displaying characters.
    4. Two-dimensional arrays for storing and displaying data in rows and columns.

    These programs help beginners understand loops, arrays, user input, and output in C programming.

More C Programming Practice

  1. Armstrong Number
  2. Odd or Even and Positive, Negative or Zero
  3. Factorial of a Number
  4. Prime Number
  5. Palindrome Number
  6. Number Pyramid
  7. Minimum and Maximum in a One-Dimensional Array

Practice Tip: Compile and execute every program. Change the input values to understand how the output changes.

4 Important Matrix Programs in C with Output

A matrix is a collection of elements arranged in rows and columns. In C programming, a matrix is represented using a two-dimensional array. For example, int a[2][2] represents a matrix containing two rows and two columns.

Remember: The first index represents the row, and the second index represents the column. Array indexing starts from 0 in C.

Program 1: Input and Display a Matrix

This program accepts four numbers from the user and displays them in the form of a 2 × 2 matrix.

C Program

#include <stdio.h>

int main()
{
    int a[2][2], i, j;

    printf("Enter 4 elements:\n");

    for(i = 0; i < 2; i++)
    {
        for(j = 0; j < 2; j++)
        {
            scanf("%d", &a[i][j]);
        }
    }

    printf("Matrix is:\n");

    for(i = 0; i < 2; i++)
    {
        for(j = 0; j < 2; j++)
        {
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Output

Enter 4 elements:
1 2 3 4
Matrix is:
1 2
3 4

Program 2: Addition of Two Matrices

Matrix addition means adding the corresponding elements of two matrices. Both matrices must have the same number of rows and columns.

C Program

#include <stdio.h>

int main()
{
    int a[2][2], b[2][2], c[2][2];
    int i, j;

    printf("Enter 4 elements of first matrix:\n");
    for(i = 0; i < 2; i++)
        for(j = 0; j < 2; j++)
            scanf("%d", &a[i][j]);

    printf("Enter 4 elements of second matrix:\n");
    for(i = 0; i < 2; i++)
        for(j = 0; j < 2; j++)
            scanf("%d", &b[i][j]);

    for(i = 0; i < 2; i++)
        for(j = 0; j < 2; j++)
            c[i][j] = a[i][j] + b[i][j];

    printf("Sum of matrices:\n");
    for(i = 0; i < 2; i++)
    {
        for(j = 0; j < 2; j++)
            printf("%d ", c[i][j]);
        printf("\n");
    }

    return 0;
}

Output

Enter 4 elements of first matrix:
1 2 3 4
Enter 4 elements of second matrix:
5 6 7 8
Sum of matrices:
6 8
10 12

Logic: c[i][j] = a[i][j] + b[i][j]

Program 3: Transpose of a Matrix

The transpose of a matrix is obtained by changing its rows into columns and its columns into rows.

C Program

#include <stdio.h>

int main()
{
    int a[2][2], i, j;

    printf("Enter 4 elements:\n");

    for(i = 0; i < 2; i++)
        for(j = 0; j < 2; j++)
            scanf("%d", &a[i][j]);

    printf("Transpose of matrix:\n");

    for(i = 0; i < 2; i++)
    {
        for(j = 0; j < 2; j++)
            printf("%d ", a[j][i]);
        printf("\n");
    }

    return 0;
}

Output

Enter 4 elements:
1 2 3 4
Transpose of matrix:
1 3
2 4

Logic: a[j][i] swaps the row and column positions when displaying the transpose.

Program 4: Multiplication of Two Matrices

Matrix multiplication uses rows of the first matrix and columns of the second matrix. The number of columns in the first matrix must equal the number of rows in the second matrix.

C Program

#include <stdio.h>

int main()
{
    int a[2][2], b[2][2], c[2][2];
    int i, j, k;

    printf("Enter 4 elements of first matrix:\n");
    for(i = 0; i < 2; i++)
        for(j = 0; j < 2; j++)
            scanf("%d", &a[i][j]);

    printf("Enter 4 elements of second matrix:\n");
    for(i = 0; i < 2; i++)
        for(j = 0; j < 2; j++)
            scanf("%d", &b[i][j]);

    for(i = 0; i < 2; i++)
    {
        for(j = 0; j < 2; j++)
        {
            c[i][j] = 0;

            for(k = 0; k < 2; k++)
                c[i][j] += a[i][k] * b[k][j];
        }
    }

    printf("Product of matrices:\n");

    for(i = 0; i < 2; i++)
    {
        for(j = 0; j < 2; j++)
            printf("%d ", c[i][j]);
        printf("\n");
    }

    return 0;
}

Output

Enter 4 elements of first matrix:
1 2 3 4
Enter 4 elements of second matrix:
5 6 7 8
Product of matrices:
19 22
43 50

Logic: Each result element is calculated by multiplying the corresponding row and column elements and adding their products.

Conclusion

These four C programs help beginners understand two-dimensional arrays, nested loops, matrix addition, transpose, and multiplication. Practice each program by changing the input values and observing the output.

No comments:

Post a Comment

Dataware housing and data mining complete manual file(DWDM)

  XXX  UNIVERSITY Laboratory Manual   DATA WAREHOUSING AND DATA MINING   Practical Manual for Diploma S...