C Exercises: Display the sum of n number of odd natural number
C For Loop: Exercise-8 with Solution
Write a C program to display the n terms of odd natural numbers and their sum.
like: 1 3 5 7 ... n
Pictorial Presentation:

Sample Solution:
C Code:
#include <stdio.h>
void main()
{
int i,n,sum=0;
printf("Input number of terms : ");
scanf("%d",&n);
printf("\nThe odd numbers are :");
for(i=1;i<=n;i++)
{
printf("%d ",2*i-1);
sum+=2*i-1;
}
printf("\nThe Sum of odd Natural Number upto %d terms : %d \n",n,sum);
}
Sample Output:
Input number of terms : 10 The odd numbers are :1 3 5 7 9 11 13 15 17 19 The Sum of odd Natural Number upto 10 terms : 100
Explanation:
for (i = 1; i <= n; i++) { printf("%d ", 2 * i - 1); sum += 2 * i - 1; }
In the said loop, the variable i is initialized to 1, and the loop will continue as long as i is less than or equal to the value of variable 'n'. In each iteration of the loop, the printf function will print the value of (2*i-1) to the console, followed by a space character.
Additionally, the value of (2*i-1) will be added to the variable 'sum' in each iteration of the loop.
The loop will increment the value of i by 1, and the process will repeat until the condition i<=n is no longer true.
Flowchart:

C Programming Code Editor:
Improve this sample solution and post your code through Disqus.
Previous: Write a program in C to display the multiplication table vertically from 1 to n.
Next: Write a program in C to display the pattern like right angle triangle using an asterisk
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
C Programming: Tips of the Day
How to get the current directory in a C program?
Have you had a look at getcwd()?
#include<unistd.h> char *getcwd(char *buf, size_t size); Simple example: #include<unistd.h> #include<stdio.h> #include<limits.h> intmain(){ char cwd[PATH_MAX]; if (getcwd(cwd, sizeof(cwd)) != NULL) { printf("Current working dir: %s\n", cwd); } else { perror("getcwd() error"); return1; } return0; }
Ref : https://bit.ly/3w9CoMS
- Weekly Trends
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join
- JavaScript functions Exercises
- Python Tutorial
- Python Array Exercises
- SQL Cross Join
- C# Sharp Array Exercises
We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook