[C language] Programming Exercises: Loops and Arrays (Chapter 6)


The long-awaited moment has come to do “homework” on the sixth chapter of Stephen Prata’s book “C Primer Plus”. We are waiting for as many as 18 exciting tasks.

1. Write a program that creates an array of 26 elements and places them in
It has 26 lowercase letters of the English alphabet. Also consider displaying the contents of this array.

The very first program gave me a club on the head 🙂 It didn’t work for a long time, it always started with b, then it didn’t work .. The result, my first pancake:

 #include <stdio.h>
 int main(void)
 {
 char alphabet[25];
 char letter = 'a'-1;
 int n;

 for (n=0; n<=25; n++)
        {
        letter+=1;
        alphabet[n] = letter;
        printf("Index [%d]=%c\n", n, alphabet[n]);
        }

 getchar();
 return 0;
 }

Further, I fixed it, in the process I remembered the sequence of work of increments:

#include <stdio.h>
 int main(void)
 {
 char alphabet[26];
 char letter;
 int n;

 for (n=0, letter = 'a'; n<26; n++)
        {
        alphabet[n] = letter++; // increment works afterwars!
        printf("Index [%d]=%c\n", n, alphabet[n]);
        }

 getchar();
 return 0;
 }

There are other solutions on the Internet, I decided to figure them out and bring them here .. So, the second approach, English (the spirit of the old school):

 #include <stdio.h>
 #define SIZE 26
 int main(void)
 {
 char alphabet[SIZE];
 char letter;
 int n;

 for (letter='a'; (letter - 'a') < SIZE; letter++)
        alphabet[letter - 'a'] = letter;

 for (n=0; n < 26; n++)
        printf("Index [%d]=%c\n", n, alphabet[n]);

 getchar();
 return 0;
 }

Third approach, Chinese, minimalistic:

 #include <stdio.h>
 #define SIZE 26
 int main(void)
 {
 char alphabet[SIZE];
 int n;

 for (n=0; n < 26; n++)
        alphabet[n] = 'a' + n;

 for (n=0; n < 26; n++)
        printf("Index [%d]=%c\n",n, alphabet[n] );

 getchar();
 return 0;
 }

2. Use nested loops to write a program that outputs the following sequence of characters:

$
$$
$$$
$$$$
$$$$$

Code:

 #include <stdio.h>
 int main(void)
 {

 int row, col, n;

 for (row = 0; row<5; row++)
        {
        for (col = 0; col <= row; col++)
                printf("$");
        printf("\n");
        }

 getchar();
 return 0;
 }

3. Use nested loops to write a program that outputs the following sequence of characters:

F
FE
FED
FEDC
FEDCB
FEDCBA

Note: If your system does not use ASCII or some other
encoding in which letters are represented in numerical order, you can use the following declaration to initialize a character array with the letters of the alphabet:
char lets[27] = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”;
Array indices can then be used to select specific letters, such as lets[O] for ‘A’, and so on.

 #include <stdio.h>
 int main(void)
 {

 int row, col;
 char letter;

 for (row = 0; row < 6; row++)
        {
        letter = 'F';
        for (col = 0; col <= row; col++)
                {
                printf("%c", letter--);
                }
        printf("\n");
        }

 getchar();
 return 0;
 }

4. Use nested loops to write a program that prints the following sequence of characters:

А
BC
DEF
GНIJ
KLMNO
PQRSTU

If your system does not use an encoding in which letters are represented in numerical order, see the note in exercise 3.

#include <stdio.h>
 int main(void)
 {

 int row, col;
 char letter = 'A';

 for (row=0; row<6; row++)
        {
         for(col=0; col<=row; col++)
                printf("%c", letter++);
         printf("\n");
        }

 getchar();
 return 0;
 }

5. 5. Write a program that prompts the user to enter an uppercase letter. Use nested loops to write a program that outputs a pyramid shape like the one below (instead of spaces, I put underscores to make it clearer for you – comment by Tangar):

____А
___АВА
__АВСВА
_ABCDCBA
ABCDEDCBA

This shape must expand up to the entered character. For example, the figure shown was the result of typing the character E. Hint: use an outer loop to process strings. Use three inner loops to form a string: one to manipulate spaces, one to print letters in ascending order, and one to print letters in descending order. If your system does not use ASCII or a similar encoding in which letters are represented in numerical order, see the note in exercise 3

But this task is very interesting, but it is much more difficult than the previous ones.

The first step is to break this task into “modules”. The first module is simply to put spaces with a ladder in the other direction, not the same as in the previous examples; Here is a task for you personally from me:

Use nested loops to write a program that outputs the following sequence of characters:

XXX
XX
X

At first, I wrote this rather asshole program:

#include <stdio.h>
 int main(void)
 {
 int row, col;
 int y=3;

 for (row=0; row<3; row++)
        {
        for (col=0; col<y; col++)
             {
             printf("x");
             }
        y--;
        printf("\n");
        }

 getchar();
 return 0;
 }

After I wrote this abracadabra, I decided to look for how it was done in the book and saw that the book has a similar example in listing 6.18. (program rows2.c). It’s funny that when I went through the above listing, everything seemed to be clear .. New wisdom: it’s clear how it works != be able to do it yourself. Based on this listing, I realized that I didn’t really master for loops; here’s how to correctly display the ladder with the letter X:

 #include <stdio.h>
 int main(void)
 {

 int row, col;

 for (row = 0; row < 3; row++)
         {
         for (col = row; col < 3; col++)
                 printf("X");
         printf("\n");
         }

 getchar();
 return 0;
 }

Output:

XXX
XX
X

Why this is so – it becomes clear when you write down on a piece of paper how things change. It becomes clear that with a decreasing number of elements in a line, it is more convenient to specify the “program flow” in the original statement, and not in the loop condition.

This example showed me for the first time how important it is to write it on a piece of paper before compiling a program, and not just rush into the coding embrasure. But let’s get back to our sheep – the pyramid program.

At first I started doing this program wrong. Well, how wrong .. Rather, not the way it should be. This is another wisdom – before programming, and even before you start thinking about the execution of individual modules, you need to think about the program in a conceptual way, at the level of an idea.

What I started doing is a triple nested loop. Damn it. Which didn’t work at all. As a result, I had a challenge – to make it work. But in the middle of the torment – I realized (when I was talking about Shtukentsia’s program) – that it was necessary to stupidly make the cycle not triple nesting, but double. This is what came out (this is an example of a prototype program that outputs X, not a sequence of letters):

#include <stdio.h>
 int main(void)
 {
 int row, space, down;

 for (row=0; row<5; row++)
        {
         for(space=row; space<4; space++)
                printf("_");
         for(down=row; down>=0; down--)
                printf("X");
         printf("\n");
        }

 getchar();
 return 0;
 }

Output:

____X
___XX
__XXX
_XXXX
XXXXX

There is one outer loop and two inner loops. Initially, out of stupidity, I put the third one (which outputs X) into the second one (the loop that outputs _) and tried to make it work …%)

So, now instead of X we put down the alphabet, and also add a quadruple loop that displays the alphabet in reverse order. Here I want to say about the most important lesson that I understood as I compiled this program – MODULARITY. It is necessary to break any task into small pieces; when you understand them – because already put everything together.

So, we display the alphabet, the first part:

#include <stdio.h>
 int main(void)
 {

 int row, space, down;
 char letter, a;

 printf("Enter the letter:\n");
 scanf("%c", &letter);

 for (row=0; row<5; row++)
        {
         for(space=row; space<4; space++)
                printf("_");
         for(down=row, a=letter; down>=0; down--)
                printf("%c", a++);
         printf("\n");
        }

 getchar(); getchar();
 return 0;
 }

This will give us:

____A
___AB
__ABC
_ABCD
ABCDE

Half the job is done. Now we need to display the alphabet in reverse, i.e. pyramid DCBA. We also do this in a separate test program:

#include <stdio.h>
 int main(void)
 {

 int row, space, down;
 char letter;

 for (row=0; row<5; row++)
        {
         for(down=row, letter='A'+row; down>=0; down--, letter--)
                printf("%c", letter);
         printf("\n");
        }

 getchar(); getchar();
 return 0;
 }

Output:

A
BA
CBA
DCBA
EDCBA

Now we combine this approach with the main program (I replaced the underscore with a space):

#include <stdio.h>
 int main(void)
 {

 int row, space, down, up;
 char letter, a, b;

 printf("Enter the letter:\n");
 scanf("%c", &letter);

 for (row=0; row<5; row++)
        {
         for(space=row; space<4; space++)
                printf(" ");
         for(down=row, a=letter; down>=0; down--)
                printf("%c", a++);
         for(up=row, b=letter+row-1; up>0; up--, b--)
                printf("%c", b);
         printf("\n");
        }

 getchar(); getchar();
 return 0;
 }

Yay, pyramid! This program took me more than one hour … But it was worth it – it was an epic battle 🙂

6. Write a program to display a table, each line of which represents an integer, its square and its cube. Prompt the user for the upper and lower limits of the table. Use a for loop.

#include <stdio.h>
 int main(void)
 {
 int min, max;
 int sqrt, cube;

 printf("Enter the lower number:\n");
 scanf("%d", &min);
 printf("Enter the upper number:\n");
 scanf("%d", &max);
 printf("Number   Square   Cube\n");

 for (min; min <= max; min++)
            printf("%4d %7d %7d\n" , min, min*min, min*min*min);
        printf("\n");

 getchar(); getchar();getchar();
 return 0;
 }

7. Write a program that reads a word into a character array and then outputs that word in reverse order. Hint: Use the strlen() function (Chapter 4) to calculate the index of the last character in an array.

 #include <stdio.h>
 #include <string.h>
 int main(void)
 {
 char word[40];
 int i;

 printf ("Enter the word:\n");
 scanf("%s", word);

 for (i = strlen(word)-1; i>=0; i--)
        printf("%c", word[i]);

 getchar();getchar();
 return 0;
 }

8. Write a program that asks for two floating point numbers and prints their difference divided by their product. The program must process pairs of input numbers until the user enters a non-numeric value.

 #include <stdio.h>
 int main(void)
 {
 float n1, n2;

 printf("Enter two floating-point numbers:\n");

 while (scanf("%f %f" , &n1, &n2))
 {
        printf("result: %f\n",((n1-n2)/(n1*n2)));
        printf("Enter new values or any non-number to quit:\n");
 }

 getchar();getchar();
 return 0;
 }

9. Modify Exercise 8 so that the program uses a function to return the results of a calculation.

 #include <stdio.h>

 float calc (float n1, float n2);

 int main(void)
 {
 float n1, n2;

 printf("Enter two floating-point numbers:\n");

 while (scanf("%f %f" , &n1, &n2))
 {
        printf("result: %f\n", calc(n1, n2));
        printf("Enter new values or any non-number to quit:\n");
 }

 getchar();getchar();
 return 0;
 }

 float calc (float n1, float n2)
 {
 return ((n1-n2)/(n1*n2));
 }

10. Write a program that asks for the lower and upper limits of a sequence of integers, calculates the sum of all squares of integers from the square of the lower integer limit to the square of the upper integer limit, and then displays the result on the screen. The program should then prompt for further limit values ​​and display the response until the user enters an upper limit value that is less than or equal to the lower limit. The output of the program should look like this:

Enter the lower and upper integer limits: 5 9 
The sum of the squares of integers from 25 to 81 is 255 
Enter the following combination of limits: 3 25 
The sum of the squares of integers from 9 to 625 is 95 
Enter the following combination of limits: 5 5 
Job done

In my opinion, the condition of this program (or rather, an example of its output) is not very successful, it is difficult to understand what the program is doing from it. In general, here we mean not the sum of “25 to 81”, but “25 + 36 + 49 + 64 + 81”. Clear explanation 🙂

The code:

 #include <stdio.h>

 int main(void)
 {

 int min, max;
 int summ = 0;
 int m, M;

 printf("Enter min and max numbers:\n");

 scanf("%d %d", &min, &max);

 while (min != max)
        {
         for (m=min, M=max+1; m != M; m++)
                 summ += m*m;
         printf("Summ of squares of integer: %d %d\n", min, max);
         printf("The Summ of the squares from %d to %d is %d\n",
                min*min, max*max, summ);
         summ=0;                       
         printf("Enter next set of limits:\n");
         scanf("%d %d", &min, &max);
        }
 printf("Done!");

 getchar();
 return 0;
 }

11. Write a program that reads eight integers into an array and then outputs them in reverse order.

 #include <stdio.h>

 int main(void)
 {

 long i, n;
 int array[7];

 printf("Enter 8 integers:\n");

 for (i=0; i<8; i++)
         scanf("%d", &array[i]);

 for (i=7; i>=0; i--)
        printf("%d", array[i]);

 getchar(); getchar();
 return 0;
 }

12. Take a look at the following two infinite sequences:
1.0+1.0/2.0+1.0/3.0+1.0/4.0+…
1.0 – 1.0/2.0 + 1.0/3.0 – 1.0/4.0 +…
Write a program that subsums these two sequences until the given number of elements has been processed. Hint: The product of an odd number of -1 values ​​is -1, and the product of an even number of -1 values ​​is 1. Let the user enter the limit interactively; a zero or negative value must terminate the input. View subtotals for 100, 1000, and 10,000 items. Do these sequences also converge to some value?

The first solution turned out to be clumsy; besides with an error in the sign:

 #include <stdio.h>

 int main(void)
 {

 float n1 = 0;
 float n2 = 0;
 float z; // number of elements
 float x;

 printf("Enter number of elements to count:\n");

 scanf ("%f", &z);

 while (z > 0)
        {
        for (x=1.0; x<=z; x++)
                {
                // to check printf("x=%.1f z=%.1f\n", x, z);
                n1+=(1.0/x);
                }
        for (x=1.0; x<=z; x++)
                {
                n2-=(1.0/x);
                x+=1.0;
                n2+=(1.0/x);
                }
     printf("First result: %f,\n second result: %f\n", n1, n2);
     printf("Enter another number of elements or 0 to quit:\n");
     n1 = 0; n2 = 0;
     scanf ("%f", &z);
        }

 getchar();
 return 0;
 }

The second version, corrected and polished (indents have to be moved a little to fit):

 #include <stdio.h>

 int main(void)
 {

 float n1 = 0;
 float n2 = 0;
 float z; // number of elements
 float x; // counter for (for)
 float sign = 1;

 printf("Enter number of elements to count:\n");

 scanf ("%f", &z);

 while (z > 0)
        {
        for (x=1; x<=z; x++)
                {
                n1+=(1/x);
                n2+=(1/x)*sign;
                sign=(-sign);
                }
     printf("1 + 1/2 + 1/3 + 1/4 + ... 1/%.0f = %f\n", z, n1);
     printf("1 - 1/2 + 1/3 - 1/4 + ... 1/%.0f = %f\n", z, n2);
     printf("Enter another number of elements or 0 to quit:\n");
     n1 = 0; n2 = 0;
     scanf ("%f", &z);
        }

 getchar();
 return 0;
 }

Conclusion (hereinafter I will omit the word conclusion as it is clear):

Enter number of elements to count:
1 + 1/2 + 1/3 + 1/4 + ... 1/100 = 5.187378
1 - 1/2 + 1/3 - 1/4 + ... 1/100 = 0.688172
Enter another number of elements or 0 to quit:
1 + 1/2 + 1/3 + 1/4 + ... 1/1000 = 7.485478
1 - 1/2 + 1/3 - 1/4 + ... 1/1000 = 0.692646
Enter another number of elements or 0 to quit:
1 + 1/2 + 1/3 + 1/4 + ... 1/10000 = 9.787613
1 - 1/2 + 1/3 - 1/4 + ... 1/10000 = 0.693091

13. Write a program that creates an eight-element int array and puts the elements of the initial eight powers of 2 into it, and then prints the resulting values. Use a for loop to evaluate the elements of an array, and for variety, use a do while loop to display the values.

 #include <stdio.h>

 int main(void)
 {

 int array[8];
 int degree=1;
 int i;

 for (i=0; i < 8; i++)
        {
        degree*=2;
        array[i]=degree;
        }
 i=0;
 do {
 printf("[%d] = %d\n", i, array[i]);
 i++;
 } while (i<8);

 getchar();
 return 0;
 }
[0] = 2
[1] = 4
[2] = 8
[3] = 16
[4] = 32
[5] = 64
[6] = 128
[7] = 256

14. Write a program that creates two eight-element arrays of type
double and uses a loop to enter the values ​​of the eight elements of the first array. The program should accumulate in the elements of the second array the sums of the first array with a running total. For example, the fourth element of the second array must be equal to the sum of the first four elements of the first array, and the fifth element of the second array must be equal to the sum of the first five elements of the first array. (This can be done with nested loops, but given the fact that the fifth element of the second array is equal to the fourth element of the second array plus the fifth element of the first array, nested loops can be avoided and a single loop can be used to solve the problem.) Finally, use a loop to print the contents of both arrays, with the first array appearing on the first line, and each element of the second array placed directly below the corresponding element of the first array.

 #include <stdio.h>

 int main(void)
 {

 int n1[8], n2[8];
 int i;
 int summ=0;

 printf("Enter 8 values:\n");

 n2[0]=0;
 for (i = 0; i<8; i++)
        {
        scanf("%d", &n1[i]);
        summ+=n1[i];
        n2[i]=summ;
        }
 i=0;
 for (i = 0; i<8; i++)
        {
        printf("%5d", n1[i]);
        }
 i=0;
 printf("\n");
 for (i = 0; i<8; i++)
        {
         printf("%5d", n2[i]);
        }

 getchar(); getchar();
 return 0;
 }
Enter 8 values:
    5   15   25   11   12   13   14   15
    5   20   45   56   68   81   95  110

15. Write a program that reads an input line and then outputs it in reverse order. Input can be stored in an array of char values; the string is assumed to be no more than 255 characters long. Recall that you can use the scanf() function with the %c specifier to read a character at a time, and when you press a key, a newline character (\n) is generated.

With this simple-looking program, I had to tinker. My first solution turned out to be rather crooked:

 #include <stdio.h>
 int main(void)
 {

 char input [255];
 int i;

 printf("Enter something\n");

 scanf ("%c", &input[0]);

 for (i=0; input[i++] != '\n'; )
        scanf ("%c", &input[i]);

 for (i-=1; i>=0; i--)
        printf("%c", input[i]);

 getchar();
 return 0;
 }

This was an example of when you should not use for … With while it is much more convenient:

 #include <stdio.h>
 int main(void)
 {

 char input [255];
 int i=0;

 printf("Enter something\n");

 while (scanf ("%c", &input[i]), input[i] != '\n')
        i++;

 for ( ; i>=0; i--)
        printf("%c", input[i]);

 getchar();
 return 0;
 }

16. Daphne makes a deposit of $100 at a simple 10%. (That is, the annual growth of the deposit is 10% of the initial amount.) Deirdre invests $100 at a compound 5%. (This means that the annual increase in the deposit is 5% of the current balance, including the previous increase in the deposit.) Write a program that calculates how many years it takes for Deirdre’s account to exceed Daphne’s account. Print also the sizes of both deposits at that moment.

 #include <stdio.h>
 int main(void)
 {

 float dap = 100.0;
 float dei = 100.0;
 int year;

 for (year=0; dap >= dei; year++)
        {
         dap += (100.0*10)/100.0;
         dei += (dei*5)/100.0;
        }

printf("Year: %2d | Daphna: %.1f | Deidra: %.1f\n", year, dap, dei);

 getchar();
 return 0;
 }
Year: 27 | Daphna: 370.0 | Deidra: 373.3

17. Chucky Lucky won a million dollars (after paying all taxes), which he deposited into an account with an interest rate of 8% per annum. On the last day of each year, Chucky withdraws $100,000 from his account. Write a program that calculates how many years will pass before Chucky’s account runs out of money.

 #include <stdio.h>
 int main(void)
 {

 float s = 1000000.0f;
 int year=0;

 while (s > 0)
        {
         year++;
         s -= 100000.0f;
         s = (s*1.08f);
         printf("Year: %d, balance: %.1f\n", year, s);
        }

 printf("Bankrupt in %2d  years ($ %.1f balance)", year, s);

 getchar();
 return 0;
 }
Year: 1, balance: 972000.1
Year: 2, balance: 941760.1
Year: 3, balance: 909101.0
Year: 4, balance: 873829.1
Year: 5, balance: 835735.5
Year: 6, balance: 794594.4
Year: 7, balance: 750161.9
Year: 8, balance: 702174.9
Year: 9, balance: 650348.9
Year: 10, balance: 594376.9
Year: 11, balance: 533927.1
Year: 12, balance: 468641.2
Year: 13, balance: 398132.6
Year: 14, balance: 321983.2
Year: 15, balance: 239741.9
Year: 16, balance: 150921.2
Year: 17, balance: 54994.9
Year: 18, balance: -48605.5
Bankrupt in 18  years ($ -48605.5 balance)

18. Professor Robins joined the group on the social network. In the beginning, he had five friends. He noticed that the number of his friends increased in the following way. After the first week, one person left the number of friends, and the number of friends doubled. After the second week, two dropped out of friends, and the number of friends doubled. Generally speaking, after the Nth week, N people dropped out of friends, and the number of friends doubled. Write a program that calculates the number of friends at the end of each week. The program should keep counting until the number of friends exceeds Dunbar’s number. Dunbar’s number is a rough estimate of the maximum size of a cohesive social group in which each member knows all the other members and is aware of their relationships with each other. Its approximate value is 150.

#include <stdio.h>
 int main(void)
 {

 int friends = 5;
 int week;
 const int dunbar_number = 150;

 for (week=1; (friends - week)*2 < dunbar_number; week++)
        {
         friends = (friends - week)*2;
        }

 printf("At %d week Proffesson Robins had %d friends", week, friends);

 getchar();
 return 0;
 }
At 8 week Proffesson Robins had 146 friends

Phew! That’s all 🙂 It was not an easy fight, but it seems that you and I learned a little how to make cycles.

I will be glad to see your comments!


This entry was posted in C language (en). Bookmark the permalink.

Leave a Reply

🇬🇧 Attention! Comments with URLs/email are not allowed.
🇷🇺 Комментарии со ссылками/email удаляются автоматически.