Skip to main content

Featured

Merge Sort in C++

  Merge Sort in C++ Introduction Merge Sort is a popular sorting algorithm that follows the Divide and Conquer approach. It divides an array into smaller subarrays, recursively sorts those subarrays, and finally merges the sorted subarrays to produce a completely sorted array. In this tutorial, we will learn how to implement Merge Sort in C++ . The program divides the array into two halves using the mid index, recursively sorts both halves, and then combines them using the merge() function. Merge Sort has a time complexity of O(n log n) in the best, average, and worst cases. Table of Contents Algorithm C++ Program Input Sample Output Output Explanation Dry Run Flow of Execution Time Complexity Space Complexity Applications Key Points Interview Questions Frequently Asked Questions Keywords Conclusion Algorithm Start the program. Read the size of the array. Read the array elements from the user. Call the mer...

Sum of Numbers from 1 to n in C

Sum of Numbers from 1 to n in C

✅ C Program to Calculate Sum from 1 to n

#include <stdio.h>

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

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

    if (n <= 0) {
        printf("Please enter a positive number.\n");
        return 1;
    }

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

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

    return 0;
}
  

๐Ÿ“˜ Explanation:

✅ This program calculates the sum of all natural numbers from 1 to n.
✅ It uses a for loop to iterate from 1 to the given number n.
✅ On each iteration, it adds the value to a running sum variable.
✅ If the input is non-positive, it displays an error message.

๐Ÿงพ Sample Output:

Enter a positive number: 5
Sum of numbers from 1 to 5 is: 15
  

๐Ÿ”‘ Keywords:

Sum from 1 to n in C, C loop program, C addition logic, beginner C project, for loop in C, positive number sum

๐Ÿ“Œ Hashtags:

#CProgramming #ForLoop #BeginnerC #MathInC #SumOfNumbers #InterviewPrep #CodingBasics

Comments

Popular Posts

๐ŸŒ™