Do/While literation statement help- c programming

1) Given an int variable n that has already been declared and initialized to a positive value , and another int variable j that has already been declared , use a do...while loop to print a single line consisting of n asterisks. Thus if n contains 5, five asterisks will be printed. Use no variables other than n and j.


2) Given int variables k and total that have already been declared , use a do...while loop to compute the sum of the squares of the first 50 positive integers and store this value in total. Thus your code should put 1*1 + 2*2 + 3*3 +... + 49*49 + 50*50 into total. Use no variables other than k and total.
Last edited on
1
2
3
4
5
6
7
int main()
{
int n;
int j;

// some sort of a loop here.
}


1
2
3
4
5
6
7
int main()
{
int k;
int total;

// some sort of a loop here.
}
Things I tried before :

1) First attempt:
1
2
3
4
5
6
j=1;
do{
printf(“*”);
j++;
}
while (j<=n);


Second attempt:
1
2
3
4
5
6
n = 5;
do {
printf("*");
j++;
}
while (j<n);


2) First attempt:
1
2
3
4
5
6
7
8
int k=1;
int total=0;

while (k<=50)
{
total=total+(k*k);
k++;
}


Second attempt:
1
2
3
4
5
6
7
8
k = 0;
Total = 0;

while ( k<= 50) 
{
total = total + k*k;
k++;
}

For the first question, your first attempt should've worked. I had the same homework problem. Look at the syntax.

For the second question, re-read the directions.
Last edited on
Hi @all

for 1) first attempt is ok, U can add :

printf("\n");

after the while to finish the line properly.


for 2), second attempt is useless. If k = 0; k*k = 0 and doesn't change total.
In first attempt, the variables have already been declared, so U should not re declare them.
It is required to use do while loop, not a while, so take care, even if the result remains the same.




Last edited on
Topic archived. No new replies allowed.