Program to Add All Numbers up To n using While loop

Program to Add All Numbers up To n using While loop

  • Write a program to Add All Numbers up To n using While loop in C
  • Write a program to Add All Numbers up To n using While loop in C++
  • Write a program to Add All Numbers up To n using While loop in Python
  • Write a program to Add All Numbers up To n using While loop in PHP
  • Write a program to Add All Numbers up To n using While loop in Java
  • Write a program to Add All Numbers up To n using While loop in Java Script
  • Write a program to Add All Numbers up To n using While loop in C#

Explanation:

Logic

  1. Take input for n (the upper limit).
  2. Initialize a variable sum to 0.
  3. Use a While loop to iterate from 1 to n.
  4. Add each number to sum during each iteration.
  5. Print the final value of sum.

Program to Add All Numbers up To n using While loop

#include <stdio.h>

int main() {
    int n, sum = 0, i = 1;
    printf("Enter the value of n: ");
    scanf("%d", &n);

    while (i <= n) {
        sum += i;
        i++;
    }
    printf("The sum of numbers from 1 to %d is: %d\n", n, sum);
    return 0;
}

#include <iostream>
using namespace std;

int main() {
    int n, sum = 0, i = 1;
    cout << "Enter the value of n: ";
    cin >> n;

    while (i <= n) {
        sum += i;
        i++;
    }
    cout << "The sum of numbers from 1 to " << n << " is: " << sum << endl;
    return 0;
}

n = int(input("Enter the value of n: "))
sum = 0
i = 1

while i <= n:
    sum += i
    i += 1

print(f"The sum of numbers from 1 to {n} is: {sum}")

<?php
$n = (int)readline("Enter the value of n: ");
$sum = 0;
$i = 1;

while ($i <= $n) {
    $sum += $i;
    $i++;
}
echo "The sum of numbers from 1 to $n is: $sum\n";
?>

import java.util.Scanner;

public class SumNumbers {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the value of n: ");
        int n = sc.nextInt();
        int sum = 0, i = 1;

        while (i <= n) {
            sum += i;
            i++;
        }
        System.out.println("The sum of numbers from 1 to " + n + " is: " + sum);
        sc.close();
    }
}

let n = parseInt(prompt("Enter the value of n: "));
let sum = 0, i = 1;

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

console.log(`The sum of numbers from 1 to ${n} is: ${sum}`);

using System;

class Program {
    static void Main() {
        Console.Write("Enter the value of n: ");
        int n = int.Parse(Console.ReadLine());
        int sum = 0, i = 1;

        while (i <= n) {
            sum += i;
            i++;
        }
        Console.WriteLine($"The sum of numbers from 1 to {n} is: {sum}");
    }
}

List of All Programs