Fundamental C - Program Structure
Written by Harry Fairhead   
Monday, 17 October 2016
Article Index
Fundamental C - Program Structure
The Flow of Control
Loops
Nesting

Cbookcover

Some Examples

Flow of control is the difficult part of learning to program. You now should understand the ideas that are behind it but you might be unsure how to use them. The only cure for this is to practice. There is nothing more to know but you need to put theory into practice. It is a bit like just learning where the notes are on a piano - you next need to practice some scales before moving onto a sonata. 

So we need some examples. 

At this stage it isn't easy to invent realistic examples of how to use control statements without introducing a lot more C.

However to close without seeing some real code in action isn't satisfying. So lets write a simple program that demonstrates the if, if else, for, while and do while loop.

These aren't realistic or convincing but they are simple.

Enter the code and try it out. Modify it and see if you are happy with the result. If you are a complete beginner to programming absorbing the way that control statements work is hard but once you have done it learning the rest of programing is easy. 

Demo projects

Start a new C project. We are going to enter some simple code snippets into the main program and see what they do. 

If

First we look at a simple if statement:

int total = 100;
if (total == 100) {
 printf("total= %d\n\r", total);
}

The command printf stands for "print formatted" and it will print the value of the integer variable total in the Output window which you can see in NetBeans' default layout just below the source listing. Don't worry too much about printf for the moment it will occupy enough of your future C life as a way to get simple output. 

If you type in and run the above what do you expect to see?

Answer: you should see 100 printed in the Output window. Now change total to be 99. Now you should see nothing at all printed.

If Else

An if ..else is fairly easy:

if (total == 100) {
 printf("value is 100");
} else {
 printf("value is not 100");
}

When you run this you will see "value is 100" printed.

What do you see if you change the value of total to 99?

You will see just the message "value is not 100".

Notice you only ever see one of the two messages.

For

In the case of the for loop:

for (int i = 1; i <= 10; i++) {
 printf("%d\n\r", i);
}

what do you expect to see printed?

Be exact.

The answer is 1 to 10 because each time thought the loop i increases by 1 until it reaches 11 when the loop ends without executing the body of the loop again i.e. with the value of i set to 11.

As an aside there is a long history of using i,j and k as counters in loops - the reason is that i is the first letter of integer and a counter or index in a for loop is always an integer. It was a convention started with the language Fortran. Today programmers still tend to use i,j and k as loop counters but it would be better to use a meaningful name. 

While

A good simple example of a while loop is perhaps the most difficult to find. One example is to just write a loop that counts just like a for loop.

For example, the following is the exact equivalent of the for loop example i.e. it prints 1 to 10:

int j = 1;
while (j <= 10) {
 printf("%d\n\r", j);
 j++;
}

This is the reason the for loop isn't really needed. Anything you can do with a for loop you can do with a while loop - but the for loop is usually easier.

Consider now a real situation where only the while loop will do - even if it is contrived.

How many times can a number be divided by two before it is less than or equal to one?

We can simulate this by writing a while loop that divides the given number and tests for it being greater than one:

int number = 10;
while (number > 1) {
 printf("%d\n\r", number);
 number = number / 2;
}

This is should be easy enough for you to follow though but notice that the statement number=number/2 can only be understood if you don't read the equals sign as a statement that the two sides are equal.

The statement says take the contents of number, divide it by 2 and store the result back in the variable number. If you run the program you will see it print 5 and 2 as after the 2 is printed the value is divided by 2 again with the result 1 and the loop ends.

You can do the same job with a do-while loop:

number = 10;
do {
 printf("%d\n\r", number);
 number = number / 2;
} while (number > 1);

The difference is that now the test is done at the end of the loop.

It is arguable that in this case the test being at the end makes it easier to see why and when the loop comes to an end. However the real difference between the two is that is you set number to one and run each loop the while loop prints nothing at all but the do loop prints one - its all a matter of where the test to end the loop is performed.

Also notice the way indents are used to show where blocks of code start and end. The content of an if, else, for, while and do while should be indented.

And finally - nesting

This is a lightening overview of the basic ways you can build program in C - or any programming language for that matter.

This part of learning to program generalises to other languages. Once you have the basics of the default flow of control, conditionals and loops you can start to work on putting them together like basic building bricks used to create more complex things.

In general there are only two ways to put these building bricks together. You can put one after the other and then you have a conditional followed by a loop followed by a conditional.

A more complicated way of combining them is to put one structure inside another - nesting them. So you can have a loop inside a conditional inside a loop etc.

For example:

Suppose you want to print a message to say a number is odd or even. Then you might use something like 

for (int i = 1; i <= 10; i++) {
 if (i / 2 * 2 == i) {
  printf("even\n\r");
 } else {
  printf("odd\n\r");
 }
}

 

You can see that there is a for loop and within it is an if statement. The if statement is nested within the for loop and so repeated ten times. The only "tricky" part of the program is condition within the if statement. If you take an integer like 3 and divide it by 2 the result isn't a fraction but the exact number of times 2 goes into 3 i.e. 1. This is integer division. When you multiply this by 2 you get 2 which is not equal to 3 and the number is odd. If you repeat the procedure using an even number like 4 you get 4/2 is 2 and 2*2 is 4 which is equal to 4 and so the program print even. Integer division may not be accurate but it is often very useful in programming. In general if a number x is even then x/2*2 is x but if it is odd then it is smaller than x - try it.

The more control statements you nest the more complicated the program becomes and this is a bad thing. Over the years we have found ways of avoiding building complicated structures like this  - but this is moving on to future topics. For now simply make sure you understand the conditional and the loop; you will see both used a lot in following chapters.

 

Fundamental C: Getting Closer To The Machine

Now available as a paperback and ebook from Amazon.

  1. About C
      Extract Dependent v Independent
                  & Undefined Behavio
  2. Getting Started With C Using NetBeans
  3. Control Structures and Data
  4. Variables
      Extract Variables
  5. Arithmetic  and Representation
      Extract Arithmetic and Representation
  6. Operators and Expression
      Extract: Expressions
      Extract Side Effects, Sequence Points And Lazy Evaluation
      First Draft of Chapter: Low Down Data
  7. Functions Scope and Lifetime
  8. Arrays
      Extract  Simple Arrays
      Extract  Ennumerations
  9. Strings
      Extract  Simple Strings
     
    Extract: String I/O ***NEW!!
  10. Pointers
      Extract  Starting Pointers
      Extract  Pointers, Cast & Type Punning
  11. Structs
      Extract Basic Structs
      Extract Typedef
  12. Bit Manipulation
      Extract Basic Bits
      Extract Shifts And Rotates 
  13. Files
     Extract Files
     
    Extract Random Access Files 
  14. Compiling C – Preprocessor, Compiler, Linker
     Extract Compilation & Preprocessor

Also see the companion volume: Applying C

<ASIN:1871962609>

<ASIN:1871962463>

<ASIN:1871962617>

<ASIN:1871962455>

 

Related Articles

Getting Started With C Using NetBeans

Remote C/C++ Development With NetBeans

Raspberry Pi And The IoT In C

Getting Started With C/C++ On The Micro:bit

 

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on, Twitter, FacebookGoogle+ or Linkedin

Banner


Microsoft Introduces Vector Abstractions Library For .NET
21/11/2024

Microsoft has announced a preview release of the Microsoft Extensions VectorData Abstractions library, which can be used to help integrate vector stores into .NET applications and libraries.



The Feds Want Us To Move On From C/C++
13/11/2024

The clamour for safe programming languages seems to be growing and becoming official. We have known for a while that C and C++ are dangerous languages so why has it become such an issue now and is it  [ ... ]


More News

espbook

 

Comments




or email your comment to: comments@i-programmer.info

 



Last Updated ( Tuesday, 11 September 2018 )