1. Write a program that will
input an integer n
calculate the sum of the positive integers from 1 – n
output the sum
#include
using namespace std;
main()
{
Int n;
cin >> n;
cout << (n+1)*(n/2.0) << endl;
int sum = 0;
for (int I = 0; I < n; i++)
sum = sum + I;
counter; loop control variable; accumulator; flag
2. Write a program that will input an integer n, and determine if n is the sum of the positive integers 1 – k for some positive integer k.
2. Write a program that will input an integer n, and determine if n is the sum of the positive integers 1 – k for some positive integer k.
For example if n=6 it is the sum of the first 3 positive integers: 1+2+3, but if n=5, then there is no positive integer k such that n=1+2+ … +k.
Your program will print one of 2 messages:
If there is such a k, output the following message:
The number n is the sum of the first k positive integers.
For example, if your program inputs n=6, it should output the message:
The number 6 is the sum of the first 3 positive integers.
If there is no such k, output the following message: “There is no positive integer k such that n is the sum of the integers 1 through k.
For example, if your program inputs n=5 it should output the message:
There is no positive integer k such that 5 is the sum of the integers 1 through k.
Main()
{
Int n, sum = 0; cin >> n;
For(int I = 1; I <= n; i++)
{
Sum = sum + I;
If (sum == n)
{
Cout << “the sum of the nums 1 thru “ << I << “is” << n;
Break;
}
Else if (sum > n)
{
Cout << “there is no such sum “;
Break;
}
}
3. Assume that you have an array of 100 integers:
int a[100];
a. Write a loop that will add up the values stored at the even index positions in the array (i.e. 0,2,4, … ).
Int sum =0;
For (int I = 0; I < 100; I+=2)
Sum += A[I];
b. Write a loop that will add up the values stored at the even index positions in the array (i.e. 0,2,4, … ) but only if the value of the elements in those positions are even.
Int sum =0;
For (int I = 0; I < 100; I+=2)
If ( A[I] % 2 == 0)
Sum += A[I];
c. Write a loop that will add up the values stored at the odd index positions in the array (i.e. 1,3,5, … ) but only if the value of the elements in those positions are even.
Int sum =0;
For (int I = 1; I < 100; I+=2)
If ( A[I] % 2 == 0)
Sum += A[I];
4. Write a program that inputs an integer n, and outputs all the numbers that divide n. For example, if n=6, output : 1,2 3. Don’t output the number n itself.
For (int I = 0; I < n / 2; i++)
If (n % I == 0)
Cout << I << “ “;
5. Given the following 2 dimensional array with half the elements shaded black and half white.
int b[8][8]
Write a program segment that will sum up all the elements in the black boxes.
Sum = 0 ;
For (int I = 0; I < 8; I++)
For (int J = I%2; J < 8; J+=2)
Sum += A[I][J];
No comments:
Post a Comment