Write a program to accept an integer N and print the sum of first N odd numbersInput Format:An integer range is given inputOutput Format:Print only calculated sum.Constraints:1 <= N <= 10^16 Sample Input 1:2Sample Output 1:4Sample Input 2:10Sample Output 2:100
Question
Write a program to accept an integer N and print the sum of first N odd numbersInput Format:An integer range is given inputOutput Format:Print only calculated sum.Constraints:1 <= N <= 10^16 Sample Input 1:2Sample Output 1:4Sample Input 2:10Sample Output 2:100
Solution
To solve this problem, we can use a loop to iterate through the first N odd numbers and calculate their sum. Here is the step-by-step solution:
- Read the value of N from the user.
- Initialize a variable named "sum" to 0 to store the sum of the odd numbers.
- Initialize a variable named "count" to 0 to keep track of the number of odd numbers encountered.
- Start a loop that iterates from 1 until the count reaches N.
- Inside the loop, check if the current number is odd by using the modulo operator (%). If the number modulo 2 is not equal to 0, it is odd.
- If the number is odd, add it to the sum variable and increment the count by 1.
- After the loop ends, print the value of the sum variable as the output.
Here is the code implementation in Python:
N = int(input("Enter the value of N: "))
sum = 0
count = 0
for num in range(1, N*2, 2):
sum += num
count += 1
if count == N:
break
print("Sum of first", N, "odd numbers:", sum)
This program prompts the user to enter the value of N, calculates the sum of the first N odd numbers, and then prints the result.
Similar Questions
Problem Statement:Find the sum of even numbers in the given range.Input Format:Accept two integer as inputOutput Format:Print the output as sum of even number available in the given rangeConstraints:1 <= INPUT <= 10^15Sample Input 1:10 20Sample Output 1:90Sample Input 2:30 33Sample Output 2:62
Write a program to accept an integer range and print the sum of number that are divisible by either 3 or 5Input Format:An integer range is given inputOutput Format:Print the calculated sum.Constraints:1 <= N <= 10^16 Sample Input 1:10Sample Output 1:33Sample Input 2:30Sample Output 2:225
Sum of EvenSend FeedbackProblem Statement:Write a program that takes a tuple as input and prints the sum of all the even numbers in the tuple.Input:A tuple containing integer elements.Output:The sum of all the even numbers in the tuple.Sample Input:(2, 3, 4, 6, 7)Sample Output:12
Write a program to print the odd values in the given rangeInput FormatTwo space separated integers - 'start' and 'end'Output FormatDisplay all the odd numbers between 'start' and 'end'Sample Input10 20Sample Output11 13 15 17 19
Write a C++ program to find the sum of even and odd n natural numbers
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.