Write program fragments (i.e., you do not need to write complete programs) with
ID: 3664754 • Letter: W
Question
Write program fragments (i.e., you do not need to write complete programs) with loops that compute: A)The sum of all even numbers between 2 and 100 (inclusive). B)The sum of all squares between 1 and 100 (inclusive). C)All powers of 2 from 2^0 up to 2^20 (inclusive). D)The sum of all odd numbers between a and b (inclusive), where a and b are integer variables with a b. E)The sum of all digits at odd positions (right-to-left starting at 1 as the right-most digit) of a numeric input. (For example, if the input is 432677, the sum would be 7 + 6 + 3 = 16.) F)The sum of all digits at odd positions (left-to-right starting at 1 as the left-most digit) of a numeric input. (For example, if the input is 432677, the sum would be 4 + 2 + 7 = 13.)
Explanation / Answer
A)
int main()
{
int i = 2;
int n = 100;
int sum=0;
while (i <= n)
{
if (i % 2 == 0)
{
sum += i;
}
i++;
}
cout << sum;
//use this, if using visual studio.
system("pause");
}
B)
int main()
{
int i = 2;
int n = 100;
int square;
int sum = 0;
while (i <sqrt(n))
{
square = i*i;
sum += square;
i++;
}
cout << sum;
//use this, if using visual studio.
system("pause");
return 0;
}
C.)
int main()
{
int i = 0;
int n = 20;
int square;
int sum = 0;
while (i <=n)
{
sum += pow(2, i);
i++;
}
cout << sum;
//use this, if using visual studio.
system("pause");
return 0;
}
D)
int main()
{
int a;
int b;
int sum = 0;
cin >> a;
cin >> b;
while (a <= b)
{
if (a % 2 != 0)
{
sum += a;
}
a++;
}
cout << sum;
//use this, if using visual studio.
system("pause");
return 0;
}
E)
int main()
{
int number;
cout << "number: ";
cin >> number;
int odd_digits_sum = 0;
while (number > 0)
{
int digit = number % 10;
odd_digits_sum += digit;
number /= 100;
}
cout << "Sum of odd digits: " << odd_digits_sum;
//use this, if using visual studio.
system("pause");
return 0;
}
F)
//Use this, if using visual studio.
#include "stdafx.h"
//Include header files
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
int main()
{
int number;
cout << "Enter any number: ";
cin >> number;
int length = to_string(number).length();
int sum = 0;
for (int i=1; i <= length; i++)
{
//Add odd place digit starting from left.
if (i % 2 != 0)
{
//Read leftmost digit
int digit = floor(number / pow(10, length - i));
sum += digit;
int l = pow(10, (length - i));
number = number % l;
}
//Remove even place digit
else
{
int digit = floor(number / pow(10, length - i));
int l = pow(10, (length - i));
number = number % l;
}
}
cout << "Sum: "<<sum<< endl;
//use this, if using visual studio.
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.