In: Computer Science
Above code is to print the sum of first n odd integers
To explain this more clearly, below are the steps:
Step 1: Declare the variable N
N is the nth value user will enter from console
int n;
Step 2: Take input from user in console
Input is the N number , which determine how many odd integers we have to add .
Input is taken with the help of predefined function in C, scanf()
printf("Enter Nth number: ");
scanf("%d" , &n);
Step 3: Now , call the method pure() with one argument passed which is n. It will return the calculated sum of first n odd integers and return to the main function and will print in the console.
In main function , value will be printed in console using predefined function printf()
printf("Sum of first N odd integers is: %d", pure(n));
We have called the function, in the print statement and result
will be displayed directly in the console
Step 4: Inside function pure()
As the function is called, control moves to the function defination
It accepts the n value as argument, and store in variable num
Also, declare two variable with integer datatype; sum and oddIncrementor
sum initialized to 0, it will continously add the n odd integers and store in it
oddIncremetor initialized to 1, it will increment the value of integer by 2,
making odd digits, eg ; 1, 3 ,5 7
int pure(int num){
int sum=0;
int oddIncrementor=1;
Step 5:
A for loop is used to calculate N odd integers sum
Initialize the value of i to 0
Condition: i<num
that means, ;loop will iterate num times
Example: num is 5, according to condition, loop will executed 5 times.
i is incremented 1
If the condition is true, control moves inside the loop
It will add the oddincrementor value in the sum variable
oddincrementor value is incremeted by 2, so that next odd integer is stored in the variable
for(int i=0;i<num;i++){
sum+=oddIncrementor;
oddIncrementor+=2;
}
As the condition becomes false, control will exit out of loop and moves to next immediate statement
Step 6: It will return the calculated total sum value to function call
return sum;
Step 7: Exit the control out of program
return 0;
_____________________________________
Please find the code below in C language:
#include <stdio.h>
int pure(int num){
int sum=0;
int oddIncrementor=1;
for(int i=0;i<num;i++){
sum+=oddIncrementor;
oddIncrementor+=2;
}
return sum;
}
int main()
{
int n;
printf("Enter Nth number: ");
scanf("%d" , &n);
printf("Sum of first N odd integers is: %d", pure(n));
return 0;
}
Please find attached Code screenshot:
Please find attached output screenhot: