Learn C Programming - C Programming Professional Made easy (2015)

C Programming Professional Made easys (2015)

Chapter 4 Learn C Programming

After learning the basic elements and what the language is all about, time to start programming in C. Here are the most important steps:

Download a compiler

A compiler is a program needed to compile the C code. It interprets the written codes and translates it into specific signals, which can be understood by the computer. Usually, compiler programs are free. There are different compilers available for several operating systems. Microsoft Visual Studio and MinGW are compilers available for Windows operating systems. XCode is among the best compilers for Mac. Among the most widely used C compiler options for Linux is gcc.

Basic Codes

Consider the following example of a simple C program in the previous chapter:

#include <stdio.h>

int main()

{

printf("Hello People!\n");

getchar();

return 0;

}

At the start of the program,#include command is placed. This is important in order to load the libraries where the needed functions are located.

The<stdio.h> refers to the file library and allows for the use of the succeeding functionsgetchar() andprintf().

The commandint main () sends a message to the compiler to run the function with the name “main” and return a certain integer once it is done running. Every C program executes a main function.

The symbol{ } is used to specify that everything within it is a component of the “main” function that the compiler should run.

The functionprintf() tells the system to display the words or characters within the parenthesis onto the computer screen. The quotation marks make certain that the C compiler would print the words or characters as it is. The sequence\n informs the C compiler to place its cursor to the succeeding line. At the conclusionof the line, a; (semicolon) is placed to denote that the sequence is done. Most codes in C program needs a semicolon to denote where the line ends.

The commandgetchar() informs the compiler to stop once it reaches the end of the function and standby for an input from the keyboard before continuing. This command is very useful because most compilers would run the C program and then immediately exits the window. Thegetchar()command would prevent the compiler to close the window until after a keystroke .is made.

The commandreturn 0 denotes that the function has ended. For this particular C program, it started as anint, which indicates that the program has to return an integer once it is done running. The “0” is an indication that the compiler ran the program correctly. If another number is returned at the end of the program, it means that there was an error somewhere in the program.

Compiling the program

To compile the program, type the code into the program’s code editor. Save this as a type of *.c file, then click the Run or Build button.

Commenting on the code

Any comments placed on codes are not compiled. These allow the user to give details on what happens in the function. Comments are good reminders on what the code is all about and for what. Comments also help other developers to understand what the code when they look at it.

To make a comment, add a/* at the beginning of the comment. End the written comment with a*/. When commenting, comment on everything except the basic portions of the code, where explanations are no longer necessary because the meanings are already clearly understood.

Also, comments can be utilized for quick removal of code parts without having to delete them. Just enclose portions of the code in/* */, then compile. Remove these tags if these portions are to be added back into the code.

USING VARIABLES

Understanding variables

Define the variables before using them. Some common ones includechar,floatandint.

Declaring variables

Again, variables have to be declared before the program can use them. To declare, enter data type and then the name of the variable. Take a look at these examples:

char name;

float x;

int f, g, i, j;

Multiple variables can also be declared all on a single line, on condition that all of them belong tothe same data type. Just separate the names of the variables commas (i.e.,int f, g, i, j;).

When declaring variables, always end the line with a semicolon to denote that the line has ended.

Location on declaring the variables

Declaring variables is done at the startof the code block. This is the portion of the code enclosed by the brackets{}. The program won’t function well if variables are declared later within the code block.

Variables for storing user input

Simple programs can be written using variables. These programs will store inputs of the user. Simple programswill use the functionscanf, which searches the user’s input for particular values. Take a look at this example:

#include <stdio.h>

int main()

{

int x;

printf( "45: " );

scanf( "%d", &x );

printf( "45 %d", x );

getchar();

return 0;

}

The string&dinforms the functionscanf to search the input for any integers.

The command&placed before thexvariable informs the functionscanf where it can search for the specific variable so that the function can change it. It also informs the function to store the defined integer within the variable.

The last printf tells the compiler to read back the integer input into the screen as a feedback for the user to check.

Manipulating variables

Mathematical expressions can be used, which allow users to manipulate stored variables. When using mathematical expressions, it is most important to remember to use the “=” distinction. A single=will set the variable’s value. A== (double equal sign) is placed when the goal is to compare the values on both sides of the sign, to check if the values are equal.

For example:

x = 2 * 4; /* sets the value of "x" to 2 * 4, or 8 */

x = x + 8; /* adds 8 to the original "x " value, and defines the new “x” value as the specific variable */

x == 18; /* determines if the value of "x" is equal to 18 */

x < 11; /* determines if the "x" value is lower than 11 */

CONDITIONAL STATEMENTS

Conditional statements can also be used within the C program. In fact, most programs are driven by these statements. These are determined as either False or True and then acted upon depending on the results. The most widely used and basic conditional statement isif.

In C, False and True statements are treated differently. Statements that are “TRUE” are those that end up equal to nonzero numbers. For example, when a comparison is performed, the outcome is a “TRUE” statement if the returned numerical value is “1”. The result is a “FALSE” statement if the value that returns is “0”.

Basic conditional operators

The operation of conditional statements is based on mathematical operators used in comparing values. The most common conditional operators include the following:

< /* less than */

6 < 15 TRUE

> /* greater than */

10 > 5 TRUE

<= /* less than or equal to */

4 <= 8 TRUE

>= /* greater than or equal to */

8 >= 8 TRUE

!= /* not equal to */

4 != 5 TRUE

== /* equal to */

7 == 7 TRUE

How to write a basic “IF” conditional statement

A conditional “IF” statement is used in determining what the next step in the program is after evaluation of the statement. These can be combined with other types of conditional statements in order to create multiple and powerful options.

Take a look at this example:

#include <stdio.h>

int main()

{

if ( 4 < 7 )

printf( "4 is less than 7");

getchar();

}

The “ELSE/ELSE IF” statements

These statements can be used in expanding the conditional statements. Build upon the “IF” statements with “ELSE” and “ELSE IF” type of conditional statements, which will handle different types of results. An “ELSE” statement will be run when the IF statement result is FALSE. An “ELSE IF” statement will allow for the inclusion of multiple IF statements in one code block, which will handle all the various cases of the statement.

Take a look at this example:

#include <stdio.h>

int main()

{

int age;

printf( "Please type current age: " );

scanf( "%d", &age );

if ( age <= 10 ) {

printf( "You are just a kid!\n" );

}

else if ( age < 30 ) {

printf( "Being a young adult is pretty awesome!\n" );

}

else if ( age < 50 ) {

printf( "You are young at heart!\n" );

}

else {

printf( "Age comes with wisdom.\n" );

}

return 0;

}

The above program will take all the input from the user and will run it through the different defined IF statements. If the input (number) satisfies the 1st IF statement, the 1st printf statement will be returned. If it does not, then input will be run through each of the “ELSE IF” statements until a match is found. If after all the “ELSE IF” statements have been run and nothing works, the input will be run through the “ELSE” statement at the last part of the program.

LOOPS

Loops are among the most important parts of C programming. These allow the user to repeat code blocks until particular conditions have been met. Loops make implementing repeated actions easy and reduce the need to write new conditional statements each time.

There are 3 main types of loops in C programming. These are FOR, WHILE and Do… WHILE.

“FOR” Loop

The “FOR” loop is the most useful and commonly used type of loop in C programming. This loop continues to run the function until the conditions set for this loop are met. There are 3 conditions required by the FOR loop. These include initialization of the variable, meeting the condition and how updating of the variable is done. All of these conditions need not be met at the same time, but a blank space with semicolon is still needed to prevent the loop from running continuously.

Take a look at this example:

#include <stdio.h>

int main()

{

int y;

for ( y = 0; y < 10; y++;){

printf( "%d\n", y );

}

getchar();

}

The value of y has been set to 0, and the loop is programmed to continue running as long as the y value remains less than 10. At each run (loop), the y value is increased by 1 before the loop is repeated. Hence, once the value of y is equivalent to 10 (after 10 loops), the above loop will then break.

WHILE Loop

These are simpler than the FOR loops. There is only one condition, which is that as long as the condition remains TRUE, the loop continues to run. Variables need not to be initialized or updated, but can be done within the loop’s main body.

Take a look at this example:

#include <stdio.h>

int main()

{

int y;

while ( y <= 20 ){

printf( "%d\n", y );

y++;

}

getchar();

}

In the above program, the commandy++ will add 1 to the variable y for each execution of the loop. When the value of y reaches 21, the loop will break.

DO…WHILE Loop

This is a very useful loop to ensure at least 1 run. FOR and WHILE loops check the conditions at the start of the loop, which ensures that it could not immediately pass and fail. DO…WHILE loops will check the conditions when the loop is finished. This ensures that the loop will run at last once before a pass and fail occurs.

Take a look at this example:

#include <stdio.h>

int main()

{

int y;

y = 10;

do {

printf("This loop is running!\n");

} while ( y != 10 );

getchar();

}

This type of loop displays the message whether the condition results turn out TRUE or FALSE. The y variable is set to 10. The WHILE loop has been set to run when the y value is not equal to 10, at which the loop ends. The message was printed because the condition is not checked until the loop has ended.

The WHILE portion of the DO..WHILE loop must end with a semicolon. This is also the only instance when a loop ends this way.