1- Write algorithm (in pseudo-code) for the following problem:
sum of the series: 1 +2+3+…+N
2- Convert an algorithm to a flowchart diagram.
3- Counting the primitive operations of the algorithm.
4- Determine algorithm complexity.
5- Write a complete C++ program for the previous algorithm where the program should contain the following:
Display messages. Input any number; Display the series. Display the sum of the series.
1. Algorithm()
1 Taking user Input = n
2 Initialize : sum = 0
3 for i = 1 to n do
4 sum =sum + i
5 return sum
2.Flowchart
3.Primitive Operation
Primitive operations are basic computations within an algorithm. evaluating an expression, assigning a value to a variable,calling a method, returning from a method , all these are the examples of primitive operations.
for taking user Input we are assuming that , It takes 1 primitive operation.
Algorithm () |
Number of primitive operations: |
1 Taking user Input = n 2 Initialize : sum = 0 3 for i = 1 to n do 4 sum =sum + i 5 return sum |
1 ( let) 1 2n 4n (including increment counter) 1 |
total primitive Operation: 1+ 1+ 2n +4n + 1 = 6n +3
4.Complexity
Algorithm () |
complexity: |
1 Taking user Input = n 2 Initialize : sum = 0 3 for i = 1 to n do 4 sum =sum + i 5 return sum |
O(1) O(1) O(n) O(1) O(1) |
Total time complexity = O(1) +O(1) + {O(n) *O(1) } + O(1) = O(n)
5. C++
program :
#include <iostream>
using namespace std;
int main()
{
int n, sum = 0;
// taking user input
cout << "Enter the input : ";
cin >> n;
//Displaying the series
cout << "Series :";
for (int i = 1; i <= n; ++i) {
cout << i<<" " ;
}
//calculating sum of the series using for loop
for (int i = 1; i <= n; ++i) {
sum += i;
}
//Displaying the sum
cout << "\nSum of the Series = " << sum;
return 0;
}
Output:
Get Answers For Free
Most questions answered within 1 hours.