Skip to main content

Featured

C++ Program to Perform Linear Search on a Vector

  C++ Program to Perform Linear Search on a Vector Introduction In this C++ program, we will learn how to perform a Linear Search on a vector. The program first takes the size of the vector and its elements as input. Then it asks the user for the element to search. If the element is found, it displays the index where it is located. Otherwise, it displays a message indicating that the element is not found. C++ Program #include<bits/stdc++.h> using namespace std; int main() { int num, search, found = 0; cout << "Enter the size of the vector:" << endl; cin >> num; vector<int> v(num); cout << "Enter " << num << " elements in vector:" << endl; for(int i = 0; i < num; i++) { cin >> v[i]; } cout << "Enter element that you want to search:" << endl; cin >> search; for(int i = 0; i < num; i++) { ...

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

๐ŸŒ™