In: Computer Science
Lab 5
a) Write a program that reads in an unsigned integer K and sums the first K many integers that are divisible by 7. You should output the sum on a formatted manner
b)Consider the following diamond it is an 11 by 11 diamond made with * signs. Write a program that takes as input positive odd integer K (greater than or equal to three and outputs a K by K diamond made with * signs
* *** * *** * **** * ***** ********** ***** * **** * *** * *** *
a)
#include <iostream>
using namespace std;
int main()
{
//variable declaration
unsigned int K;
int sum=0;
//display message
cout<<"Enter a number: ";
cin>>K;
for(int i=1; i<=K; i++)
{
//check if number is divisible by 7
if(i%7==0)
sum = sum + i;
}
//display sum
cout<<"Sum = "<<sum;
return 0;
}
INPUT:
Enter a number: 20
OUTPUT:
Sum = 21
b)
#include <iostream>
using namespace std;
int main()
{
//variable declaration
int K, space = 1;
cout<<"Enter odd integer greater than two: ";
cin>>K;
//validate the input
if(K%2==0 || K<3)
{
cout<<"Input is wrong";
return 0;
}
K = (K+1) / 2;
space = K - 1;
//print the upper half of diamond
for(int i = 1; i<=K; i++)
{
for(int s = 1; s<=space; s++)
cout<<" ";
space--;
for(int s = 1; s<= 2*i-1; s++)
cout<<"*";
cout<<endl;
}
space = 1;
//print the lower half of the diamond
for(int i = 1; i<= K - 1; i++)
{
for(int s = 1; s<= space; s++)
cout<<" ";
space++;
for(int s = 1 ; s<= 2*(K-i)-1; s++)
cout<<"*";
cout<<endl;
}
return 0;
}
INPUT:
Enter odd integer greater than two: 5
OUTPUT:
*
* * *
* * * * *
* * *
*