Website Logo

1. My First Program

By Shodan. December 10th, 2019. 9:57 PM

Check the guide's index here.
Objectives
  • Anatomy of a C Program
  • Instruction Blocks
  • Screen Writing Function - printf
  • C's Special Characteristics
  • Strings in C
  • Special Characters
  • Comments in C

Intro

A program is a sequence of code, organized in such a way that it allows you to solve a certain problem. A program can be developed in distinct modules or subprograms. This way, there'll have to be a well defined program writing criteria or format that indicates to the compiler which instruction or place it should start executing from, in the middle of all the code written by the programmer.

As an example, a program in Pascal starts its execution in the first instruction existent in the only BEGIN ... END block that is neither associated with a function nor a procedure. It is absolutely necessary that this BEGIN ... END block is unique and finds itself after all of the defined functions and procedures.

In COBOL's case, the execution begins in the first instruction existent following the PROCEDURE DIVISION line.

In C's case, there is a function in which are placed all of the instructions we want to be executed. This function is called main() and all of the code to be executed is placed inbetween curly brackets { }. To the set of existent code inbetween curly brackets, we call a Block.

Let's try writing our first program in C.


prog0101.c
1: main()
2: {
3: }

Note: the number of each of the lines serves only as reference. The only thing you should write, should you copy the could should be:
  • main()
    {
    }

Next you can create the corresponding executable/binary (prog0101(.exe)) and execute it.

$ ./prog0101
$

As you can observe, this program does one of the things I like to do most in life - absolutely nothing.

Let's obeserve each of the lines a bit closer.

The first line is composed of the word main, which is the place where all C programs start.

To indicate it is a function, the word main appears with parenthesis in front of it - main() -, because any C function followed by parenthesis.

The parenthesis with nothing in front of the function's name indicate that the function receives no information from the outside world.

It is necessary to never forget that C is Case Sensitive, which means, it differenciates upper case from lower case, so it's never the same thing to write main(), Main(), MAIN() or mAiN(). Every C instruction is written in lower case, and the usage of upper case should only be used when you want to use variables, messages or functions written by yourself.

The code being executed by the main() function is written between the curly brackets { }. In the case of our program, as we wrote no instructions inside, the program just starts and ends right after. And so, we wrote our first program in C.

Note: If your compiled displayed a WARNING with a message similar to "Function should return a value" or "main: no return value", it's because you're, mainly, using a C++ compiler. You can ignore the Warning, since there's no problem. But if you want it to disappear, before the main function, just write the word void.

In this case, the program should be written like:

void main()
{
}

Later, you'll understand why.

It's usual that our first program written in any language should be to show off the language to the world. Let's write one of the most known C programs ever.

prog0102.c
1: #include <stdio.h>
2: main()
3: {
4:    printf("Hello World\n");
5: }

After executing the program, it'll display the following output:

$ ./prog0101
Hello World$

This code is in all similar to the previous one, with the exception of a line of code inbetween the curly brackets.

Line 4: is responsable for displaying the message we want printed out.

Every time we want to use sets of characters, we need to place them inbetween double quotes so they'll be interpreted as a whole - "Hello World".

Being that C is a language with few reserved words, it's not surprising that C does not possess any imbeded I/O (Input and Output) mechanisms. It, instead, makes use of its powerful function library to provide these kinds of services.

One of the functions that allows to print out to the screen is the printf function = print + format. Being a function, it necessarily has to be written with parenthesis - printf. Inside those parenthesis is made a communication with the function. In this case, we pass the string (set of characters) that we want to print out - printf("Hello World").

In C, each instruction must be finished with a semicolon (;), and with that, this program's 4th line is printf("Hello World");

Note that the quote character (") is a unique character and cannot be substituted by either an apostrophe (') or two of them ('').

As it was said before, C has no I/O mechanisms built in. To solve that problem, we have to make use of a set of functions that exist in Function libraries. This means we need to add a set of other functionalities to this language that it, by default, does not provide.

To have access to this set of functions we need to include its definition in our program.

The line #include <stdio.h> is not C, but rather a directive that tells the compiler (most accurately, the pre-processor) it needs to add, to the compiling process, a file somewhere in your computer's disk called stdio.h, in a way that the compiler has access to a set of info about the functions it's going to use.

These files always have the .h extension because they have no code in them - only headers of the functions they represent. That's why they are usually called header files.

This way, the line #include <stdio.h> means "add the file stdio.h to my program exactly in this place". Since it's not a C instruction, it's not followed by a ;.

The file stdio.h allows access to all normal I/O functions. stdio means standard input/output.

#include <stdio.h>
Includes all Standard Input and Output functions.
main()
The program starts here.
{
Begins the instruction block.
  printf("Hello World");
Prints the string "Hello World" using the printf function.
}
Ends the instruction block.

The same program could have been written using this set of equivalent instructions:

#include <stdio.h>
main()
{
  printf("Hello");
  printf(" ");
  printf("World");
}

The result would be exactly the same. What we did was invoke the printf function several times with parts of the string we originally wanted to write.

C's compiler, GCC, is particularly liberal when it comes to the way we write our code. It can be written in any way programmers see fit. The previous program could have been written like this:

#include <stdio.h>
main         (   )  {
  printf(
"Hello"

);
  printf(  " "         )
;  printf(           "World"         );}

And we would have obtained the exact same output - because what matters is not the structure, but the content of the code. We conclude, from this, that blank spaces are ignored by the compiler.

The original program (prog0102.c) presents a slight problem, however. After printing out the message Hello World, the cursor is placed immediately after the word World and not on the next line, as would be normal. The reason why this happens is because no one told the program to change lines after writing that message on-screen.

So, how does C solve this problem?

Normally, programming languages present distinct functions or instructions for printing stuff out on the screen, followed by (or not) a new line. For example, Pascal has the instructions WRITE and WRITELN.

In the case of C, the philosophy of it is different. The printf function writes all of the sent characters between quotes. The problem we have is: how do we represent the act of changing lines?

Traditionally, that act is called a New Line, and, in C, is represented by the symbol \n.

This way, we need to alter our program to:

prog0103.c
1: #include <stdio.h>
2: main()
3: {
4:   printf("Hello World\n");
5: }

After being executed, this new program provides the expected output, leaving the line cursor in the line below the string we printed on screen. Note that we only wanted to change the line after printing out the string Hello World. To do so, the character indicating the change of line had to be written after Hello World, but it's a character like any other, so it's also part of the string.

$ ./prog0103
Hello World
$

The special character New Line is represented by two characters, \n. Now, New Line is a character like any other and can be written as many times as necessary.

The output originated by printf("Hello \n\nWor\nld\n"); would be:

Hello

Wor
ld

Problem: Writing a program in C that outputs the following:

C
is the greatest
Language

The solution, then, is simple.

prog0104.c
1: #include <stdio.h>
2: main()
3: {
4:   printf("C\n");
5:   printf("is the greatest\n");
6:   printf("Language\n");
7: }

or you can use just one printf():

prog0104.c
1: #include <stdio.h>
2: main()
3: {
4:   printf("C\nisthegreatest\nLanguage\n");
5: }

As you can verify, you don't even need to leave blank spaces before or after the \n symbol.

Let's suppose now that we wanted to write a program with the following output:

Today is a "BEAUTIFUL" day!!!

Our first try would be:

prog0105.c (Results in COMPILING ERROR)
1: #include <stdio.h>
2: main()
3: {
4:   printf("Today is a "BEAUTIFUL" day!!!\n");
5: }

Now, the above program will originate a compiling error. What we want to write must be all inbetween quotation marks, but in this case, the string we wanted to write will not, initially allow this. You'll end up creating two seperate strings and an unidentified object which will make the compiler ring out an error: "Today is a ", " day!!!\n" and the word BEAUTIFUL. This will originate a syntax error.

So here is our problem: If quotation marks are used to set the limits of strings, how can I write a string which itself contains quotation marks?

The solution is obtained by placing a backslash (\) before the quotation marks we want to write, so they're threated as normal characters, and not as the strings' limits.

prog0105.c
1: #include <stdio.h>
2: main()
3: {
4:   printf("Today is a \"BEAUTIFUL\" day!!!\n");
5: }

And, just like that, we have the desired output.

The Special Character \

The \ (backslash) symbol is used to take or give a special characteristic of some character. In the case of ", it takes it's trait as a string's limit, becoming normal quotation marks.

In the case of \n (and others), they give them traits that, in other forms, would be difficult or almost impossible to represent.

The complete list of characters that can be created by prefixing them with the backslash is presented below:

\7
Bell (computer's audio signal)
\a
Bell (computer's audio signal)
\b
Backspace
\n
New Line (changing line)
\r
Carriage Return
\h
Horizontal Tabling
\v
Vertical Tabling
\\
A way to represent backslashes (\) in strings
\'
Apostrophe (')
\"
Quotation mark (")
\?
Interrogation mark (?)
\000
Character whose ASCII code in Octal is 000
\xNN
Character whose ASCII code in Hexadecimal is NN
%%
Percentage symbol (%)

/* Comments */

On our daily lives, it's common to write notes about things we don't want to forget. How many of us went home, or to work with a paper napkin of some pastry shop or restaurant with some notes about what to do that day, or who to call at some time in the afternoon?

Sometimes, when you study from a book, when somethin's not presented in a clear way, we grab a pencil and take notes so that, next time, it's not that hard to understand something previously presented.

It's these notes we take every day that can also be particularly useful when we're writing a program. We usually call these notes Comments.

Comments are not destined to be interpreted by the compiler or by any other component of the development process. They're ignored by the compiler and the program will show no sign of them.

A comment in C is any set of characters contained inside the characters /* and */.

Since comments have no interference in a program's execution, they serve for nothing more than to document its code. Its objective is to ease the life of a programmer who has to look into a certain project in C, avoiding the trouble of having to understand all the code to understand what a determined set of instructions does.

With it, you can write a header for a program:

/* PROG0199.C : Comments & Co.      */
/* AUTHOR :     SHODAN THE HACKER   */
/* DATE:        15/12/2019          */

A comment can extend for more than one line, and it's actually common to use it like that:

/* PROG0199.C : Comments & Co.
 * AUTHOR :     SHODAN THE HACKER
 * DATE:        15/12/2019
 */

or, for extra points in style:

 /********************************
 * PROG0199.C : Comments & Co.    *
 * AUTHOR :     SHODAN THE HACKER *
 * DATE:        15/12/2019        *
  ********************************/

The horizontal and vertical asterisks have no meaning whatsoever and are there only to reinforce the comment's aesthetic presentation. What really matters is that the compiler ignores anything existing between the /* and */ symbols.

Comments can also be placed inside of expressions or instructions, which could increase the program's reading complexity, so do it at your own peril.

printf("Hello World" /* The \n is missing */) /* Note where the semicolon is */ ;

The only time when the /* and */ are not ignored by the compiler is when they're placed inside of a string.

printf("A comment in C begins with /* and ends with */\n");

In this case, /* and */ lose their special meaning and are treated as normal characters inside a string. The output would be:

A comment in C begins with /* and ends with */

Compilers don't generally allow the existence of comments inside of other comments

/* start of comment no. 1
    /* printf("Ola\n"); Internal Comment */
*/

because, following the rule of comments in C, the initial comment would end where the */ is found, ending the comment. The extension of the comment varies between the first appearance of /* and the first appearance of */, tetecting the end of a comment without the corresponding beginning.

Some compilers do, however, allow to compile using the "Nested Comments" option, verifying that there are comments inside other comments. This option is not recognized by ANSI.

And this cool and all, but all our programs make are display messages at this point. Show off information. But what if we want to make our program save information? Check Part 2 of this guide to find out how. ;)

< Introduction

2. Basic Data Types >

Check These Articles