A loop lets you repeat a code (or a block of code) several times. Thus, you won’t have to retype your codes manually. Programmers often rely on “while” and for” loops when writing C programs. A “while” loop repeats your chosen code as long as a condition is “true”. The program will stop running your chosen code once the condition becomes false. The syntax of while loops is:
while (<the conditional statement>) {
<the code or code block you want to run>;
}
The “for” loops, on the other hand, lets you change the result of the conditional statement easily. The syntax for these loops is:
for (<the initial value>; <the testing value>; <the change value>) {
<the statement/s you want to run>;
} Here’s a basic example:
for (x=1; x<50; x++) {
printf(“%d”, x);
} This example will use “1” as the starting value. The loop will increase this value by 1 and print the resulting value on the screen. This “add then print” sequence will happen until the resulting value reaches 50. Thus, your screen should display numbers from 1 to 50. Important Note: The C language supports “loop nesting”. Nesting is the process of placing a loop inside another loop
The “if/else” Statement
The syntax for this statement is:
If (<your condition>) {
<the statement/s you want to run if your condition is satisfied>
} <else> {
<the statement/s to run if your condition isn’t satisfied>;
} Important Note: If you are working on a single statement, the curly braces are optional.
Comments in C
Main purpose of a comment is to provide information regarding the construct it is attached to. In the C language, you may use the following characters for commenting: “//” – Use this symbol for single-line comments. For example:
//This comment is awesome. “/* … */” – Use this symbol for multi-line comments. For instance:
/* This comment
covers multiple
lines. */
Lets type our first program.
Let’s use the constructs given above to create a simple C program. The program found below, known as “Hello World!”, prints a two-word message on the screen. Most programming lessons use this program as the starting point for a programmer’s development. To create your first program, you should:
1. Launch your favorite text editor (e.g. Notepad).
2. Type the following codes:
//helloworld.c //This is the name of your program.
#include <stdio.h> //You need this to print the message on the screen.
main () { //Just like other C programs, “Hello World!” requires a main() function.
Printf(“Hello World!”); //This statement tells the program to display a message on the screen.
} //This character terminates the program. Once you run this program, you will see “Hello World” on your screen.
Leave a Reply