C Program to Print Fibonacci Series.

The Fibonacci series is a sequence of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. The series is represented as 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. In other words, each number in the series (after the first two numbers) is the sum of the two preceding ones.


In this article, we are going to print the Fibonacci series using C programming.

Algorithm to Print Fibonacci Series.

  • Input the number of terms 'n' from the user.
  • Initialize variables 'first' and 'second' as 0 and 1, respectively, representing the first two numbers of the series.
  • Print the first two numbers of the series, i.e., 0 and 1.
  • Use a loop to calculate and print the subsequent terms of the series.
  • In each iteration, calculate the next term as the sum of the 'first' and 'second'.
  • Update 'first' to the value of 'second' and 'second' to the value of the newly calculated term.
  • Repeat steps 4 to 6 'n-2' times, as the first two numbers are already printed. 

Below is the C program to display Fibonacci Series.

//c program for fibonacci sequqence.
#include <stdio.h>

int main() {
    int n, first = 0, second = 1, next;

    printf("Enter the number of terms in the Fibonacci series: ");
    scanf("%d", &n);

    printf("Fibonacci Series: ");

    // Print the first two terms
    printf("%d, %d", first, second);

    // Calculate and print the subsequent terms
    for (int i = 2; i < n; i++) {
        next = first + second;
        printf(", %d", next);

        // Update first and second for the next iteration
        first = second;
        second = next;
    }

    printf("\n");
    return 0;
}
Output:
Enter the number of terms in the Fibonacci series: 7
Fibonacci Series: 0, 1, 1, 2, 3, 5, 8

Time Complexity: The time complexity of the given C program to print the Fibonacci series is O(n), where 'n' is the number of terms in the series.

Space Complexity: The space complexity of the program is O(1), which means it uses constant space. 

C Program to Print Sum of Natural Numbers.

In this C programming, we are going to calculate the sum of n natural numbers using different methods. Before moving to the code part, let's first understand natural numbers.


What are Natural Numbers?

Natural numbers are a set of positive whole numbers starting from 1 and extending indefinitely, including 1, 2, 3, 4, and so on. They do not include zero or any negative numbers. 

Example:

Input: n = 10
Output: 55

Explanation: 
1 + 2 + 3+ 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55

Below are four different approaches we are going to use to find the sum of natural numbers:

Sum of Natural Numbers using while Loop.

In this approach we are using a while loop, we take input n from the user and calculate the sum of natural numbers from 1 to n.

C Code:
//C program to sum natural numbers using while loop
#include <stdio.h>

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

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

    while (i <= n) {
        sum += i;
        i++;
    }

    printf("Sum of natural numbers from 1 to %d is %d.\n", n, sum);

    return 0;
}
Output:
Enter a positive integer: 8
Sum of natural numbers from 1 to 8 is 36.

Time Complexity: O(n) as the while loop run n times.
Space Complexity: O(1) no extra space is required.

Sum of Natural Numbers using for Loop.

In this approach we are using a for loop, we follow the same process but use a for loop to iterate from 1 to n.

C Code:
//C program to find sum of natural numbers using for loop
#include <stdio.h>

int main() {
    int n, sum = 0;

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

    for (int i = 1; i <= n; i++) {
        sum += i;
    }

    printf("Sum of natural numbers from 1 to %d is %d.\n", n, sum);

    return 0;
}
Output:
Enter a positive integer: 11
Sum of natural numbers from 1 to 11 is 66.

Time Complexity: O(n) as the for loop runs n times.
Space Complexity: O(1) no extra space is required.

Sum of Natural Numbers using Recursion.

In this approach we are using recursion, we define a function sumRecursion that takes n as input. The function calculates the sum of natural numbers from 1 to n using recursion. The base case is when n becomes 0, and the function returns 0. Otherwise, it returns n + sumRecursion(n - 1).

C Code:
//C program to find the sum of natural numbers using Recursion
#include <stdio.h>

//recursive function
int sumFunction(int n) {
    int sum = 0;

    for (int i = 1; i <= n; i++) {
        sum += i;
    }
    return sum;
}

int main() {
    int n, sum;

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

    sum = sumFunction(n);

    printf("Sum of natural numbers from 1 to %d is %d.\n", n, sum);

    return 0;
}
Output:
Enter a positive integer: 12
Sum of natural numbers from 1 to 12 is 78.

Time Complexity: O(n) as the recursive function is called n+1 times.
Space Complexity: O(n) as we require extra stack space for a recursive function.

C Program to Check Given Year is Leap Year.

In this C program, we are going to check whether the given year is a leap year or not. But before writing code for this we first need to understand what is Leap Year? A leap year is a year that contains an extra day, February 29, making it 366 days instead of the usual 365 days. 


What is Leap Year?

Leap years occur once in four years to keep the calendar year synchronized with the astronomical year, which is approximately 365.2422 days long. Usually, a non-leap year contains 28 days in the month of February but a leap year contains 29 days in the month of February. 


Below are a few rules to check if the given year is a leap year or not:

  • The year must be evenly divisible by 4.
  • If the year is divisible by 100, it must also be divisible by 400.
Example:

Input: 2008
Output: 2008 is a Leap Year

Explanation: 
  • Check if the year is divisible by 4: 2008 % 4 = 0.
  • Since 2008 is divisible by 4, proceed to the next step.
  • Check if the year is divisible by 100: 2008 % 100 = 8.
  • 2008 is not divisible by 100, so not necessary to check its divisibility by 400.
  • Since 2008 is divisible by 4 and not by 100, it is a leap year.

Algorithm to Check Leap Year:

Step 1: Input the year from the user.
Step 2: Check if the year is evenly divisible by 4.
Step 3: If it is not divisible by 4, it is not a leap year.
Step 4: If it is divisible by 4, check if it is also divisible by 100.
Step 5: If it is divisible by 100, check if it is also divisible by 400.
Step 6: If it is divisible by 400, it is a leap year.
Step 7: If it is divisible by 100 but not by 400, it is not a leap year.
Step 8: If it is divisible by 4 and not by 100, it is a leap year.

C Code:
Below is the C program to check whether the year is a leap year or not:

//C program implementation to check leap year
#include <stdio.h>

int main() {
    int year;

    printf("Enter a year: ");
    scanf("%d", &year);
    
    //check leap year conditions
    if (year % 4 == 0) {
        if (year % 100 == 0) {
            if (year % 400 == 0) {
                printf("%d is a leap year.\n", year);
            } else {
                printf("%d is not a leap year.\n", year);
            }
        } else {
            printf("%d is a leap year.\n", year);
        }
    } else {
        printf("%d is not a leap year.\n", year);
    }

    return 0;
}
Output:
Enter a year: 2024
2024 is a leap year.

C Program to Count Vowels and Consonants.

Write a C program to count the number of vowels and consonants in a given string. Vowels are the letters 'a', 'e', 'i', 'o', and 'u' (both uppercase and lowercase), while consonants are all other letters of the alphabet.

Example:
Input: School
Output: Number of Vowels = 2
        Number of consonants = 4

Input: Programming
Output: Number of Vowels = 3
        Number of consonants = 8 

Vowel: A vowel is a type of speech sound produced by the vocal cords without any significant constriction or closure of the air passage. In the English alphabet, the letters 'a', 'e', 'i', 'o', and 'u' are considered vowels. (alert-success)
Consonant: A consonant is a speech sound in which the air is at least partially obstructed and does not flow freely through the vocal cords. In the English alphabet, all letters except 'a', 'e', 'i', 'o', and 'u' are considered consonants. (alert-success)


Step-by-step Algorithm.

Step 1: Input the string from the user.
Step 2: Initialize variables to store the counts of vowels and consonants, initially set to 0.
Step 3: Traverse each character of the string.
Step 4: Check if the character is an alphabet (a-z, A-Z).
Step 5: If the character is a vowel (either lowercase or uppercase), increment the vowel count.
Step 6: If the character is a consonant (neither a vowel nor a space), increment the consonant count.
Step 7: Display the final counts of vowels and consonants.


C code to count the number of vowels and consonants in the given string.

//C program to count vowels and consonants
#include <stdio.h>
#include <ctype.h>

int main() {
    char str[100];
    int vowels = 0, consonants = 0, i = 0;

    printf("Enter a string: ");
    fgets(str, sizeof(str), stdin);

    while (str[i] != '\0') {
        // Convert character to lowercase
        char ch = tolower(str[i]); 

        // Check if the character is an alphabet
        if ((ch >= 'a' && ch <= 'z')) {
            // character is a vowel, increment the vowel count
            if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
                vowels++;
            } else {
                // character is a consonant, increment the consonant count
                consonants++;
            }
        }
        i++;
    }

    printf("Number of vowels: %d\n", vowels);
    printf("Number of consonants: %d\n", consonants);

    return 0;
}
Output:
Enter a string: Good Life
Number of vowels: 4
Number of consonants: 4

Time Complexity: O(n) where n is the number of character the string contain.
Space Complexity: O(1) as no extra space is required to solve this problem.
Note: In the above code, we have used tolower() built-in function which is a part of ctype.h header file. It is used to convert characters to lowercase equivalents. (alert-passed) 

C Program to Check Whether the Number is Even or Odd.

In this C program, we will determine whether a given number is even or odd. An even number is an integer that is exactly divisible by 2 without leaving a remainder, while an odd number is an integer that leaves a remainder of 1 when divided by 2. 

For Example:
2, 4, 6, 8, 10, etc are Even numbers.
1, 3, 7, 11, 13, etc are Odd numbers.

Steps to Check Whether a Number is Even or Odd:

Step 1: Take an Input number from the user.
Step 2: Use the modulo operator (%) to check if the number leaves a remainder of 0 when divided by 2.
Step 3: If the remainder is 0, the number is even. Otherwise, it is odd.
Step 4: Display the result indicating whether the number is even or odd.

C Program to check Even or Odd.

//C program to check even or odd number
#include <stdio.h>

int main() {
    int number;

    printf("Enter an integer: ");
    scanf("%d", &number);

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

    return 0;
}
Output:
Enter an integer: 10
10 is an even number.

In the above example code, the user enters an integer number, and then our program checks if the number is divisible by two or not. If the number is perfectly divisible by 2 then we say that the given number is Even else we say the given number is Odd.

C Program to Find Greatest Number Among Three.

Given three numbers a, b, and c. Your task is to write a C program to find the largest number among three given numbers. The program should take three integer inputs from the user and determine which number is the largest among them.

Example:

Input: a = 10, b = 5, c = 9
Output: Largest Number = 10

Input: a = -5, b = 2, c = 1
Output: Largest Number = 2

Steps to Find the Greatest Number Among Three:

Step 1: Input three numbers (num1, num2, num3) from the user.
Step 2: Compare the three numbers to find the greatest among them.
Step 3: Display the greatest number as the result.

C code to find the Greatest number using if-else.
//C program to find the greatest number among three
#include <stdio.h>

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

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

    if (a > b && a > c) {
        greatest = a;
    } else if (b > a && b > c) {
        greatest = b;
    } else {
        greatest = c;
    }

    printf("The greatest number among three is: %d\n", greatest);

    return 0;
}
Output:
Enter three numbers: 3 6 1
The greatest number among three is: 6


C Code to find the greatest number among three using Ternary Operator.
//C program to find the greatest number using ternary operator
#include <stdio.h>

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

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

    // ternary operator to find greatest
    greatest = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);

    printf("The greatest number is: %d\n", greatest);

    return 0;
}
Output:
Enter three numbers: 10 20 40
The greatest number is: 40

Explanation:

To find the greatest number among three given numbers, we compare the numbers in pairs. We first compare num1 and num2, then num1 and num3, and finally num2 and num3. The number that is greater than the other two in each comparison is the greatest number among the three.

C Program to Find Area of a Circle.

In this C program, we are going to find the area of a circle for which the radius is given. The area of a circle is the measure of the region enclosed by the circle. 

Area of Circle Formula:
Area (A) = π * radius^2

Example: 
Input: r = 5
Output: 78.5 sq units

Explanation: 
Area = 3.14 * 5 * 5
     = 3.14 * 25
     = 78.5 square units

Step-by-step Algorithm:

Step 1: Input the radius (r) of the circle from the user.
Step 2: Calculate the area (A) of the circle using the formula: A = π * r^2.
Step 3: Display the calculated area of the circle.

C program to Print Aread of a Circle.

//C implementation to find Area of a circle
#include <stdio.h>
#define PI 3.14

int main() {
    float radius, area;

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

    // area of the circle
    area = PI * radius * radius;

    printf("Area of the circle: %.2f square units\n", area);

    return 0;
}
Output:
Enter the radius of the circle: 5
Area of the circle: 78.50 square units

C Program to Calculate Compound Interest.

In this C program, we will calculate compound interest using user-provided inputs. Before learning the code part, let's understand compound interest and how to calculate it.


What is Compound Interest?

Compound interest is the interest that is added to the principal amount of an investment or loan at regular intervals. The interest is calculated not only on the initial principal amount but also on the accumulated interest from previous periods. As a result, the amount of interest earned keeps increasing with each compounding period.


Compound Interest Formula:

The formula to calculate compound interest is given by:

Compound Interest (CI) = P * (1 + R/n)^(n*T) - P

Where:
  • CI is the Compound Interest.
  • P is the Principal Amount (initial amount invested or borrowed).
  • R is the Annual Interest Rate in percentage (as a decimal).
  • T is the Time Duration in years.
  • n is the number of times the interest is compounded per year.
Example: 
Let's understand with one example. Suppose a person invests 10,000 rupees in a bank account that offers a 5% annual interest rate, compounded annually.
Given Data:
Principal amount (P) = 10,000 rupees
Annual interest rate (R) = 5% (or 0.05 as a decimal)
Time duration (T) = 3 years
Number of times interest is compounded per year (n) = 1 

Solution: 
CI = 10000 * (1 + 0.05/1)^(1*3) - 10000
   = 10000 * (1.05)^3 - 10000
   = 10000 * 1.157625 - 10000
   = 11576.25 - 10000
   = 1576.25 rupees

C program to find the Compound Interest.

// C program to calculate compound interest  
#include <stdio.h>
#include <math.h>

int main() {
    float principal, rate, time, compoundInterest;
    int n;

    // Input the principal amount
    printf("Enter the principal amount: ");
    scanf("%f", &principal);

    // Input the annual interest rate (as a decimal)
    printf("Enter the annual interest rate (as a decimal): ");
    scanf("%f", &rate);

    // Input the time duration in years
    printf("Enter the time duration in years: ");
    scanf("%f", &time);

    // Input the number of times interest is compounded per year
    printf("Enter the number of times interest is compounded per year: ");
    scanf("%d", &n);

    // Calculate the compound interest
    compoundInterest = principal * pow(1 + rate / n, n * time) - principal;

    // Display the calculated compound interest
    printf("Compound Interest: %.2f\n", compoundInterest);

    return 0;
}
Output:
Enter the principal amount: 10000
Enter the annual interest rate (as a decimal): 0.05
Enter the time duration in years: 5
Enter the number of times interest is compounded per year: 1
Compound Interest: 2762.81

Note: In the above program, enter the interest rate in decimal format, like 5 % interest rate is equal to 5/100 = 0.05 to get the correct result.

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson