Average of first n odd naturals numbers?


Here we will see how to get the average of n odd natural numbers. The n is given by the user. To get the ith odd number we can use this formula 2*i+1. Here also we are using this formula. Let us see the algorithm to get the clear idea.

Algorithm

avgOddNaturalNumber(n)

Begin
   sum := 0
   for i in range 0 to n-1, do
      sum := sum + (2i + 1)
   done
   return sum/n
End

Example

 Live Demo

#include<iostream>
using namespace std;
float asciiAverage(string str){
   int sum = 0;
   for(int i = 0; i<str.size(); i++){
      sum += int(str[i]);
   }
   return sum/str.size();
}
main() {
   string str;
   cout << "Enter a string: ";
   cin >> str;
   cout << "ASCII average is: " << asciiAverage(str);
}

Output

Enter a string: Hello
ASCII average is: 100

Updated on: 30-Jul-2019

172 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements