Hi! Great day! Welcome to this course. Thank you for taking an interest in this course. Learning from this course will help you become an IT Professional.

C Anatomy

Upon reaching your home, you cleaned up the place, took out the manual, and opened it. Surprisingly, the book came with a preface before the actual lesson. From there, it writes:

“Before you learn how to code in C, you must first learn its foundations in order to fully understand how it works. For this reason, I, the author of this book, would like to introduce to you C’s parts and pieces that make it function as a whole: C’s basic program structure.”

The Basic C Structure

Before we get on to the different functions and statements used to program in C, we have to first understand the basic structure of the code that we need to make for it to run.

A basic C program consists of two main parts: its preprocessor directives and the main() function. Here is a sample program to illustrate each part:

//This is the preprocessor directive
#include <stdio.h>
 
//This is the main function
int main(void){
 
 
         return 0;
}

preprocessor is a program which, as the name suggests, is executed before the main code is processed. Mostly, this comprises of built-in header files or libraries that contain tons of functions that can be used when coding in C.

To call these, we use directives, which are keywords that start with a hash/pound (#). When it comes to calling built-in header files, we use #include and enclose the header file name in angle brackets, like this:

#include <filename.h>

The main() function, on the other hand, is the main part of code that is called by the compiler to execute the program. Hence, any code that is typed inside the main function’s curly braces () is where the program execution begins.

Did you know?

You can actually write the main() function without putting the word void inside its parentheses, and it will still work the same, like this syntax:

int main(){

    return 0;

}

Did you know?

The statement return 0; holds a very important role in your main() function.

If we write our main function as int main() and not void main(), we need to have a return value in the end. This return value is considered the “Exit Status” of the application, that is why we need to have that return 0; at the end of our code.

On most operating systems, returning 0 is a success status which means the program worked fine until the end, without errors. So don’t forget to put return 0 at the end of your code, okay?

Header Files

C has a standard library that contains tons of built-in header files which can be useful when coding, but these can only function if we call it using the #include directive.
Before we are able to use any function in C, we have to identify first which library is needed to use the function. Here are some of the most basic ones available:

<stdio.h>

Standard Input/Output Functions

<math.h>

Mathematical Functions

<string.h>

String Functions

<ctype.h>

Character Handling Functions

It is important to note that header files always end with a .h (from the “h” in the word “header file”) to indicate that it is indeed a header file. Moreover, built-in header files are always enclosed in angle brackets (<>), so keep this in mind whenever you need to use one, okay?\n\nThis lesson only gives you an overview of the common library/header files that are used in C, but we will get to know more about each of these libraries in the future lessons, like when and how to use them, so just continue learning and keep going!

Lesson Summary

Basic C Structure

SyntaxTerms

The C Structure
preprocessor directive
#include <filename.h>
main() program
int main(void){
         return 0;
}
The C Structure
preprocessor

a program which is executed before the main code is processed

directives

keywords that start with a hash/pound symbol (#)

main() function

the main part of code that is called by the compiler to execute the program

How to Talk

Upon reading an overview of the C structure, your excitement to learn has increased more than ever. With such excitement, you couldn’t wait another day and immediately flipped the page to the next chapter of the book. From there, it says:

“It is not flexible movements nor is it a perfect human face that makes a creature more human-like; it is its ability to speak and communicate with other humans. With it, the robot will now be able to talk with humans about its name, or even just about the food he likes to eat every morning (sipping a glass of gasoline in the morning, I guess?). Hence, we will be starting off with C’s own method of speaking – the printf() function.”

printf() Syntax

The printf() statement is a built-in output function in C that allows the computer to print out on the screen a certain text or number. When printing strings (or text), it follows the following syntax:

printf("dummy string");

where the text to be outputted is enclosed with a pair of double quotes (“), and all enclosed by parentheses and ending with a semicolon (;).

However, we cannot use the printf() function easily without including the header file that we need to use these standard input/output functions. To do that, we have to make use of preprocessor directives!

From the previous lesson, we have known that the header file for input and output functions is stdio.h and to call it, we have to use #include and put the header file name inside a pair of angle brackets. Hence, at the top of your code before the main() function, we shall include this in the code:

#include <stdio.h>

So, when we want to greet the world using a program in C, we can now do this:

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

Basically, this function can only print strings by default, but it could also print numbers as well if we do the follow the same method of printing as with strings – by enclosing it with double quotes, like this:

#include <stdio.h>
int main(){
         printf("1234");
 
         return 0;
}

Did you know?

Every single-lined statement in C, except for preprocessor directives, will always end with a semicolon, so don’t ever forget those little punctuations, or else you’ll get stressed out over failing to run you code successfully due to a syntax error! Here, let me show you what will happen if you forget one:

Code

#include <stdio.h>

int main(){

    printf(“Hello World!”)

}

When to Pause

Feeling happy about your learning on how to print using C, you then turned to the next page on the instruction manual. From there, it writes:

“Speaking is indeed a great skill of a robot and takes it a bit closer to being more human-like. However, humans get tired of speaking, too, and needs some time to pause or take a break before getting back to the topic. As such, if the robot talks endlessly for a long period of time, surely, it will sound monotonous and boring to others, and we wouldn’t want that to happen, do we?

Therefore, in order to let the robot learn how to take a break while speaking, we will program him with the use of C’s basic escape sequences.”

Definition

Before we go on about the kinds of escape sequences, let us describe what it does first. Escape sequences are special characters characterized by a backslash (\) and a letter or symbol beside it. It is used in printf() statements to show spaces, new lines, or show symbols that cannot be outputted using the normal way of printing.
There are a lot of escape sequences available in C, but we will only be tackling about the most basic ones.

Types

Each escape sequence has its own function when used in printing. Here are some basic ones that are made available for use in C:

\t

Prints a horizontal tab space

printf("Hello\tWorld!")
Hello     World!

\n

Prints the proceeding text to a new line

printf("Hello\nWorld!")
Hello
World!

\\

Prints a backslash

\”

Prints a double quote inside texts enclosed in double quotes

Reading the Situation

The robot you’ve programmed, Cody, now learns how to speak and pause like a human kiddo! But you notice that there is still something else missing in order to complete his speaking ability. Eager to find out what it is, you then turned to the last page of the current chapter of the manual:

“Speaking and learning to pause are two essential skills that your robot needs to be able to talk like human, but there is one last recipe that completes the basic human-like speaking skills, and that is the ability to readily choose what things are best to talk about in a situation, whether it be a number or a string. To be able to do that in C, we need to use format codes, or commonly known as placeholders.”

Definition

placeholder is basically a formatting specifier that will be replaced by a value corresponding to its data type. Basically, it’s like a blank that needs to be filled up with a value. When using placeholders in printf() statements, it follows the following syntax:

printf("placeholder", value);

Where the placeholder indicates the format specifier to be used, followed by a comma (,) that connects it to the value that substitutes the placeholder.

Types

There are six (6) basic types of placeholders that you can use in C, and these are the following:

%c

Represents a single letter or symbol. Examples: ‘a’, ‘A’, ‘-‘, ‘.’

info

Characters are always enclosed with a pair of single quotes (‘ ‘) as it is how C differentiates them from strings which are enclosed in double quotes (” “).

%s

Represents a group of characters. Examples: “dummy text value”,”prog is awesome”

%d

Represents a whole number (up to ±32767). Examples: 4, 32767, 1, 0, -5, -1, -32767

%ld

Represents a whole number (like integers), but in a more extended range (up to ±2147483647). Examples: 2147483646, 1234562, 32768, -123456, -23458751

%f

Represents a number with decimal points (only up to 7 decimal points). Examples: 3.241, 100.25, 3.3333333

%lf

Represents a number with decimal points (just like floating point values), but in a more extended range of values (up to 15 decimal points). Examples: 3.1412345678, 0.00000000000001

Cody

Did you know?

You can combine texts and placeholders in a printf() statement! Just type the placeholder normally as part of the entire string, but don’t forget to give it a value to be substituted, okay?

If you feel like experimenting, try this now!

#include <stdio.h>

int main(){

    printf(“The robot’s name is %s\n” , “Cody”);

    printf(“The first letter of Cody’s name is %c\n” , ‘C’);

    printf(“Its age is already %d\n” , 4);

    printf(“His owner is earning at least %.2f a month” , 7500.00);

    return 0;

}

Placeholders aren’t just meant to be used alone. You can also use two or more placeholders in one printf() statement! Just arrange the values according to the placeholder it will be substituting, separated by a comma.

Say for example, we want the robot to introduce itself in front of the class by telling its name and age. With this, we will be using two placeholders in one statement, just like this:

#include <stdio.h>
 
int main(){
         printf("Hi! My name is %s and I am %d years old from the date of my creation.", "Cody", 2);
 
         return 0;
}
Cody

Did you know?

You can indicate at least how many digits an integer is to be displayed using placeholders! By writing (“%03d”), you would control the display of a single digit into triple digits by adding zero to the lacking digits! (but of course, the value would not change)
However, it is good to note that this function would only indicate the minimum number of digits that is to be outputted. If there comes a six-digit number passing through this placeholder, it would output the same number since it exceeds the minimum number of digits to be displayed.

Still don’t believe me? Then have a go at it!

#include <stdio.h>

int main(){

    printf(“%03d\n”, 7);

    printf(“%03d”, 700000);

    return 0;

}

Did you know?

You can print fractional values (like float and double) with limited decimal places, too! By default, float and double floating point values will be displayed with 6 decimals, but that’s just lame and too long if it wasn’t need right?
Just use the syntax (“%.2f”) where the “.2” represents how many decimals will only be shown when printed.

Note that when you wish to print a number in C with lesser decimals than it already has, it will automatically round off the number to the nearest least printed decimal.

Try it out yourself!

#include <stdio.h>

int main(){

    printf(“Pi is equivalent to %.3f”, 3.1415926);

    return 0;

}

Lesson Summary

How to Print

SyntaxTerms

Print Syntax
printf()
printf
printf

*to use input/output functions in C, like printf(), we have to include the stdio.h library, hence, we have to type in #include<stdio.h> as one of the preprocessor directives in our program.

Escape Sequences
\t
printf
\n
printf
\\
printf
\’
printf
\”
printf

*these can be used anywhere inside the quotation marks of your printf() function and can be used multiple times as well.

Placeholders
%c
printf("%c", ‘letter/symbol’);
%s
printf("%s", "string text");
%d
printf("%d", integer);
%ld
printf("%ld", long integer);
%f
printf("%f", float);
%lf
printf("%f", double float);
Print Syntax
printf()

a built-in function in C that allows the computer to output a certain text or number

Escape Sequences
escape sequences

special characters characterized by a backslash (\) and letter or symbol beside it

Placeholders
placeholder

a formatting specifier in a printf() function that will be replaced by a value corresponding to its data type

char

shortened C term for character; refers to a single letter (uppercase or lowercase) or a symbol (including white space)

str

shortened C term for string; refers to a group of characters (word, sentence, etc.)

int

shortened C term for integer; refers to whole numbers (positive, zero, negative)

float

shortened C term for floating-point values; means numbers with decimals

No Dead Airs

Just a few days ago, your Cody acquired its human-like speaking ability! But what would happen if the robot is prompted to speak about common things, like its name or age? Wandering in thoughts, you took the manual from your side and began reading the second chapter. Starting off, it says:

“Being able to speak is one thing that makes a robot close to being human, but to speak instantly on basic things like its name, age, or an answer to a yes/no question, without taking too much time for such a thing, takes your robot to the next level at being human-like. But this cannot be achieved by merely typing in the data manually (that’s exhausting, you know), so this calls for the help of the “containers” of data in C – variables.”

Variable Declaration

Variables are objects that are used to store values. As an object, they act as containers or buckets where the data will be put into and stored. In C, declaring a variable uses this kind of syntax:

data_type varName

Variable declaration in C requires 3 parts: (1) the data type it will possess, (2) the variable name of your choice, and (3) a semicolon at the end.

Unlike other languages that allow their variables to change data types whenever the programmer wants to, C’s variable data types are defined upon declaration and will always hold that data type afterwards. There are tons of data types available in C, but here are the basic ones that you can use in variable declaration:

char

Character (a letter, symbol, or white space)

int

Integer (whole number ranging between ±32767)

long int

Long integer (whole numbers ranging between ±2147483647)

float

Floating point values (real numbers that can handle up to 7 decimals)

double

Double floating point values (real numbers that can handle up to 15 decimals)

We can also declare a variable and directly assign it to a value using the assignment operator, the equal sign (=), like this:

data_type varName = value;
Cody

Did you know?

If you wish to declare multiple variables of the same data type, you can actually just use one line declaration and separate each variable name with a comma, like this:

data_type varname1, varname2;

Or even initialize its values to your liking!

data_type varname1 = value, varname2 = value;

Don’t believe me? Then let’s try it in a real code!

#include <stdio.h>

int main(){

    int num1 = 4, num2 = 5;

    printf(“Num1 = %d, Num2 = %d”, num1, num2);

    return 0;

}

Note that a variable’s data type remains as it is once declared, so when you try to assign a letter to an integer variable, the character value will be converted into its integer equivalent. The same thing happens when you assign a float to an integer variable, since it will only take the whole number from the assigned value.

To elaborate, here’s what happens when you do those things:

#include <stdio.h>
 
int main(){
         int age = 'C';
         //it will print out the integer equivalent of the uppercase C instead
         //to start, since the integer equivalent of uppercase A is 65, 
         //then counting from there, uppercase C will be 67, like this:
         printf("%d", age);
 
         int gravity = 9.8;
         //for floats, it will print out only the whole number portion instead
         printf("%d", gravity);
 
         return 0;
}

To get a clearer view on the use of variables, let us take this one for example:

#include <stdio.h>
 
int main(){
         int age;
         age = 4;
 
         //let us try to use the variable in a sentence using placeholders, like this:
         printf("I'm Cody and I am already %d years old\n", age);
         printf("It has also been %d years since I have seen the world.", age);
 
         return 0;
}

As you can see, we can now reuse a variable as much as we want to! It is a very efficient way to use the same word over and over in different contexts without typing the word manually! It is important to remember though, that variables can only be printed using the printf() function using placeholders.

And what’s more, if you ever decide to change the age number on thousand lines of code, you will only change the value of the variable, and not each statement now! Efficient, ain’t it?

#include <stdio.h>
 
int main(){
         int age = 4;
         
you just need to change this code right here instead of typing in on tons of lines like those below! */
         printf("%d\n", age);
         printf("%d\n", age);
         printf("%d\n", age);
         printf("%d\n", age);
 
         return 0;
}
Cody

Did you know?

The texts after double slashes (//) and those in between a pair of slash asterisks (/*) that you see in the code above will not be read by the code, and these are what we call as comments.

Comments are very useful as they serve as guides to the code especially when you want to look at your code again after a long time, or if someone else tries to read the code you’ve written, it would easily be understood by anyone who looks at it again.

So try documenting your code once in a while to maintain your code for the future!

#include <stdio.h>
 
int main(){
         int age = 3;
         // This will not be executed since it is written as comment
         // printf("Current Age: %d", age); 
         // only the code below:
         printf("%d is my age", age);
 
         return 0;
}

It can also be used to conceal parts of your code instead of erasing it completely when testing other parts of code when debugging.

Changing Variable Values

Just like in other programming languages, we can change and overwrite the value assigned in C variables as well! The only thing we have to do is to follow the same syntax as when declaring a variable with an assigned value using the assignment operator, but without typing in the data type anymore, like this syntax:

varName = value;

For example, when we want to update the age that was initially assigned to the variable, we can do it like this:

#include <stdio.h>
 
int main(){
         int age = 3;
         printf("Current Age: %d\n", age); 
 
 
         age = 4;
         printf("Age a year after: %d", age);
 
         return 0;
}
Cody

Did you know?

You can also declare constant variables as well, using the const keyword! Declaring a constant variable using that follows this syntax:

const data_type CONSTANT_NAME = value;

Making constants can also be done using preprocessor directives! Just type in the #define directive, the name of the variable, and its value, together with other preprocessor directives before the main program, like this:

#define CONSTANTNAME value

By convention, the name of the constant variable must always be in uppercase letters to easily identify that the variable is indeed a constant.
These are mostly used when indicating fixed sizes or mathematical values, like PI or the value of gravity. Let’s try making constants now!

#include <stdio.h>

//constants-making method using preprocessor directive

#define PI 3.1415926

int main(){

    //constants-making method using const keyword

    const float GRAVITY = 9.8;

    printf(“Both %f and %f are constant values”, PI, GRAVITY);

    return 0;

}

Did you know?

You can’t change the value of a constant after you’ve declared them the first time in either of the methods that is mentioned above!
It is because it is treated as a constant in C, which means that it cannot be changed all throughout the code and will now be treated as a read-only variable.
If you indeed try to change it, you’ll encounter an error like the one below, so keep that in mind, okay?

int main(){

    const float GRAVITY = 9.8;

    GRAVITY = 10.2;

    return 0;

}

    return 0;

}

How Should I Name You?

You finally learned how to declare variables, and that takes Cody one step closer towards a more natural way of speaking! But when you become forgetful about what you did in your code, how would you be able to properly identify what variables to use when the need arises? Looking for answers, you turned to the next page of the manual again, and there lies the answer which states:

“Robots speak without lagging out when they have ready-to-use information stored in variables. But how would it identify what data is stored in those variables? This is why proper variable naming is important. With clear, distinct names, the robot and you as the programmer would not be confused anymore as to which variable to use. In C, we have to learn some naming conventions.”

Limits

You can name a variable anything as long as it makes sense to you, but it would definitely be much better if it resembles what the data it holds is all about.

NO: a = 15, asd1 = “Cody”
YES: age = 15, name = “Cody”

But when naming variables in C, there are restrictions and guidelines to follow in order to make the best out of it. Here are some that are worth mentioning:

1) Variable names will only compose of letters, numbers, and/or a single symbol, underscore (_). Moreover, all names must always start with a letter or an underscore (A-Z, a-z, _).

NO: 1num, my+name, $Dollars
YES: num1, my_name, Dollars, _Dollars

2) Avoid using lengthy names for a variable. As much as possible, just make sure that the first three letters of its name makes sense when you read it so that it will be easy to remember and easy to type as well.

NO: this_is_a_variable, anInteger, MyAge
YES: var_name, num, age

Cody

Did you know?

C is case-sensitive. In this sense, an uppercase letter and a lowercase letter are treated as two different characters!

Don’t believe me? Try this one to see it for yourself (take a good look at the name of the variables)!

#include <stdio.h>

int main(){

    char letter = ‘c’;

    char Letter = ‘C’;

    printf(“%c is different from %c”, letter, Letter);

    return 0;

}

Naming Styles

If there are rules and guidelines, then there are also different styles in naming variables! Feel free to use the style that best fits the data you will store in a variable. Here are a few common styles used:

Flat Case

All words are in lowercase but connected directly

varname

Camel Case

Uncapitalized first word, capitalized proceeding words (like a camel shape) and connected directly

varName

Pascal Case

All words are capitalized and connected directly

VarName

Snake Case

All words are in lowercase and connected by an underscore (_)

var_name

Macro Case

All words are in uppercase and connected by an underscore (_)

VAR_NAME

Whichever style you choose to use when naming variables, just stick to that one style to avoid confusion and to observe naming consistency, okay?

Lesson Summary

Variables

SyntaxTerms

Variable Declaration
variable declaration
data_type varName
data_type varName = value;
C comments
//single-line comments
/*multi-line comments*/
constants
const VARNAME = value;
#define VARNAME value

*C variables can only be assigned to a value of the same data type. Meaning, you can only assign integers to an integer variable, and nothing else.

Naming Conventions
Flat Case
data_type varnamenumber1 = value;
Camel Case
data_type varNameNumber1 = value;
Pascal Case
data_type VarNameNumber1 = value;
Snake Case
data_type var_name_number_1 = value;
Macro Case
data_type VAR_NAME_NUMBER_1 = value;

*these are merely variable naming styles that you can use in C. However, when you choose a naming style, remember to always stick to that style and maintain naming consistency!

Variable Declaration
variable

objects/containers in C that are used to store values

assignment operator

refer to the single equal sign (=) which is used to assign a value to a variable

Naming Conventions
Flat Case

a variable naming style in which all words in the name are in lowercase but is directly connected

Camel Case

a variable naming style in which the first word of the variable name is all in lowercase, but all words after it are capitalized (like a camel’s back shape)

Pascal Case

a variable naming style in which all words in a variable name all capitalized and directly connected

Snake Case

a variable naming style in which all words in a variable name are in lowercase but connected by an underscore (_)

Macro Case

a variable naming style in which all words in a variable name are in uppercase and connected by an underscore (_)

Basic Math

Cody has finally stepped up on acting and sounding more human-like than from when he started! Now it shall master another basic element of speaking: numbers! And so, you opened the instructions manual to its fourth chapter which says:

“Words are enough for speaking, but when solving problems in school or in life in the future years, a robot must have the ability to do basic math and handle numbers! Well, computers are actually capable of simple and complex calculations, but it won’t ever work if the programmer does not know how to code it! Hence, in order for your learn math basics, we have to get familiar with some basic arithmetic operations in C.”

The Symbols

Just like your elementary mathematics, C also has its similar set of math operations, with an addition of some other set of symbols for specified purposes. Here are the following:

+

Adds numbers on either side of the operator (works on strings, too!)

printf("%d",2+4);
6

Subtracts the left operand from the right operand

printf("%d",2-4);
-2

*

Multiplies numbers on either side of the operator (works on strings, too!)

printf("%d",2*4);
8

/

Divides the left operand by the right operand (with 6 decimals if the numbers are floating point values and only the whole number if both are integers)

%

Divides left operand by right operand and returns the remainder

printf("%d",4/3);
1

info

Note: This modulo operator only works on integers (whole numbers).

Now, there are times when we wish to perform calculations on the value of a variable and then overwrite the value of the variable by the result it garnered. Normally, we can do so by doing these:

varName = varName + value;
varName = varName – value;
varName = varName * value;
varName = varName / value;
varName = varName % value;

But there is actually a shortcut to writing these codes, and that is through directly typing together the assignment operator and arithmetic operator to be used, like these:

+=

How it really works: var = var + value

Syntax:

var+=value;

-=

How it really works: var = var – value

Syntax:

var-=value;

*=

How it really works: var = var * value

Syntax:

var*=value;

/=

How it really works: var = var / value

Syntax:

var/=value;

%=

How it really works: var = var % value

Syntax:

var%=value;
Cody

Did you know?

When you wish to directly overwrite a variable while adding or subtracting one from it at the same time, you can use some help from increment and decrement operators! Instead of writing it like this:

varname = varname + 1;
varname = varname – 1;

You can now just type it like any of these!

varname++; //directly adds one to the varname value after this line of code
varname--; //directly subtracts one to the varname value after this line of code

With these, you can code with lesser words, right? Let’s test this code below to see if this really works!

#include <stdio.h>

int main(){

    int a = 4;

    a++;

    printf(“%d\n”, a);

    a–;

    printf(“%d”, a);

    return 0;

}

Like a Scientific Calculator

Being able to perform basic math would let Cody keep up with early elementary kids, but what would happen if it were to face complex math involving exponents, square roots, and the like? Surely, there must be some way. Pumped up from the piled-up curiosity in you, you then looked for help in the manual and found your answer on the third chapter’s second topic:

“If C has its ready-to-use basic operations, then there should also be built-in complex math operations as well! C does have some built-in functions that a scientific calculator has, all in one library. Therefore, today we shall learn how to let the robot access this library and use some basic math operations.”

The math.h file

Before we can use some of the functions that are found on a scientific calculator, we have to include the library where those functions are contained, into the code. C has tons of header files in store that can actually be used when needed (we already talked about the most common ones on the first chapter, remember?).

Let us first recall how to include a built-in header file into the C code. To do that, we shall write it just like including the stdio.h library, like this:

#include <filename.h>

And in our case, since we need some mathematical functions to be made available for use in C, based on the five basic header files mentioned in the first chapter, it has to be math.h. Hence:

#include <math.h>

With this, you can now use mathematical functions in your code!

When including header files in your code, it is good to note that we should only do so on the topmost part of the code by convention. Once it’s already typed in there, then it is good to use! We shall also only include header files only if we use them for good programming practice.

Basic Math Functions

The math.h header file contains a lot of advanced math functions that can be used for specific purposes. But for starters, here are some basic ones that are commonly used:

fabs()

Returns the absolute/positive value of num

Syntax:

fabs(float)
#include<math.h>
printf("%lf", fabs(-3.2));
3.2

pow()

Returns the value of the left operand (base) raised to the power of the right operand (exponent)

Syntax:

pow(base, exponent)
#include<math.h>
printf("%lf", pow(2,5));
32

sqrt()

Returns the square root of a number

Syntax:

sqrt(num)
#include<math.h>
printf("%lf", sqrt(64));
8

floor()

Rounds down a number to the largest integer less than or equal to the number

Syntax:

floor(num)
#include<math.h>
printf("%lf", floor(3.5));
3

ceil()

Rounds up the number to the smallest integer greater than or equal to the number

Syntax:

ceil(num)
#include<math.h>
printf("%lf", ceil(3.5));
4

Always remember that all results generated by these mathematical functions are double floating-point values, so don’t forget to use %lf when trying to print them out or store it in a double variable when needed, okay?

Cody

Did you know?

The values generated by math.h functions are of data type double by default. However, if you wish to transform that value into some other data type, like making it an integer to perform math calculations and more, you can usetypecasting, like this:

(data_type)value

Just change the data_type in the syntax into the data type you wish to transform the value into, like int, float, char, or str! This is incredibly useful when we want to print out the results from math.h functions that are double by default, into integers! Come one, why don’t we try that out?

#include <stdio.h>

int main(){

    double a = pow(2,3);

//now, let’s typecast the value into an integer!

    printf(“%d”, (int)a);

    return 0;

}

Which to Solve First?

Cody is now one more step away from mastering number manipulation! Eager to know the last recipe to mastering this, you turned to the last page of the current chapter, which writes:

“Just like ordinary mathematics’ PEMDAS rule, C also follows a similar order of priority when calculating. This concept is a vital part of mastering number manipulation since it would greatly affect the results of calculations if this was not properly understood. Therefore, we must understand which operation need to be solved first, and in programming, we call this the order of precedence.”

The Order

Just like ordinary math, C also follows a similar order of precedence when performing the operations. To illustrate, we visualize the order as a staircase that needs to be taken step by step before being able to go to the bottom part, like this:

Mathematical Order Graph

Keep in mind that as shown in the illustration, those in the same box are of the same ranking in the order of precedence, that is, when faced with those operations in one event, the computer will read it directly from left to right (unless enclosed by a parentheses).

Sample Problem 1

Guess the Answer

Let’s try the usual math tricks using the combination of arithmetic operations and have a try at how the order of precedence works!

The rule is to pick any integer from 1-9 and perform the following:
a) Multiply it by 2
b) Add six to the result
c) Divide the result by 2
d) Subtract the result by the original number you have chosen.

And magically, it will always result to the number 3! However, it is important to not that we can only do this if we follow the method step by step, especially since the third step involves division, which is of higher precedence than the second step, addition. In here comes the great use of parentheses, like this one below:

#include <stdio.h>

int main(){

    int num = 4; //an example

    printf(“%d”, (num * 2 + 6) / 2 – num);

    return 0;

}

Lesson Summary

Arithmetic

SyntaxTerms

Basic Arithmetic Operators
Addition
var = num + num;
var += num;
Subtraction
var = num-num;
var -= num;
Multiplication
var = num*num;
var *= num;
Normal Division
var = num/num;
var /= num;
Modulo
var = int%int;
var %= int;
Increment Operators
var
var
Basic Math Functions
including math library
#include <math.h>
fabs()
fabs
sqrt()
sqrt(num);
pow()
pow(base, exponent);
floor()
floor(num);
ceil()
ceil(num);

*to use these functions, we have to import the math library in our program, hence we need to type in #include <stdio.h> on top of our code in C.

Basic Arithmetic Operators
Modulo

Divides left operand by right operand and returns the remainder

Order of Precedence
Order of Precedence

an order of operations to be followed when solving for mathematical operations in C with the following order: parentheses -> multiplication/division/modulo -> addition/subtraction

*for operations having the same precedence, we begin solving from the first operator of the same precedence on the left side, and on to the right.

Learn to Listen

After days of programming your Cody, it has finally mastered human speech! (with your code, of course) However, as what a human quote says, there is something better than speaking, and that is…what the fifth chapter is about, which you opened and read aloud:

“Speaking is one great human ability, but in order to live a harmonious life together in the human world, it would be strange if every human would just talk and do nothing else, right? That is why, as social beings, there is also another important ability that lets them understand other human beings – listening. And luckily, we have just the thing that we need in C: the scanf() function.”

The Syntax

The scanf() function works just like listening to another person in human sense, such that, it receives what the other person says. Similarly, in C, this function will allow the user to type in a specific data that is asked by the program. We shall also remember that since this is a standard input function, it will need the preprocessor directive, #include <stdio.h> for it to work.

By convention, we must create a variable that will store the value to be inputted using the scanf() function. After creating the variable that will serve as the container, we can now use the scanf function by following this syntax:

scanf("placeholder", &varName);

The syntax presented above looks like a printf() function using placeholders, right? It does actually function quite similarly, since the placeholder is dependent on the data type of the variable that it is representing. The biggest difference, however, is that the variable that is meant to replace the placeholder must have an ampersand (&) before typing in the variable name in order to store the inputted value to it.

The ampersand symbol (&), also known as the address operator, plays the most important role in this process as it allows the scanf() function to access the address of the variable, locate it, and store the value that will inputted by the user into the variable.

On most compilers that have terminals to run the code real-time, the scanf() function will only end once the user pushes the Enter key in the keyboard and then proceed to the next lines of code. However, CodeChum’s coding environment works differently, since our compiler requires you to type in your custom inputs first in the input area before you run the code for it to work as you expect it to be.

To explain further on CodeChum’s input mechanism, here’s a simple guide example on how it works

#include <stdio.h>

int main(){

    //declare the variable to be used in the scanf function first

    int num;

    //and then use it in scanf() to receive the inputted value!

    scanf(“%d”, &num);

    //now let’s see if the value is really stored inside the variable:

    printf(“The inputted number is %d”, num);

    return 0;

}

Did you know?

You can also take multiple inputs in one line using the scanf function! Well, it actually works just the same way, but with more than one placeholder and variables separated by space, like this syntax!

scanf("placeholder1 placeholder2 placeholder3", &varname1, &varname2, &varname3);

Taking multiple inputs in one line doesn’t have to be of the same data type. Just don’t forget to also type it with spaces too in the input area for the compiler to distinguish which is which, and oh, take note of the arrangement of inputs as well to avoid errors and miscalculations on your code!

Moreover, if you are planning to take multiple inputs in one line, especially of data type int and char, always remember to put spaces in between its placeholders inside the scanf() function to avoid mistakenly storing values when inputting your code. Spaces are characters as well, so if we do not put a space to separate the two, the program might think that the character to be stored is the space that you inputted to separate with the former value, which might cause mistakes in your program. So, remember to put spaces to separate placeholders in your code, okay?

Let’s try it out with the code below:

#include <stdio.h>

int main(){

    int num1;

    char letter;

    //put spaces in between %d and %c or in any placeholder when 

    //taking multiple inputs, ALWAYS.

    scanf(“%d %c”, &num1, &letter);

    //let’s see if it stored the values in the right variables

    printf(“Number: %d, Letter: %c”, num1, letter);

    return 0;

}

Lesson Summary

Asking For Input

SyntaxTerms

Input Syntax
input()
scanf(“placeholder”, &varName);
Input Syntax
scanf()

built-in function in C used to prompt the user to type some value in the program

Making Decisions

Cody is now able to speak and listen to humans, which means that he is now quite geared up to blend in to human society! But Cody is not fully-equipped though, since there are still a lot of things that it needs to learn, like making its own decisions based on certain circumstances. But how would it be possible for a robot to decide on its own? Looking for answers, you opened the instruction manual again and began reading the sixth chapter which wrote:

“Robots have the capacity to follow what the programmer has told it to do, but never the ability to decide solely without the programmer’s guidance. However, there is one other way to make decision-making possible for robots to do, and that is by preparing a set of conditions on its program, given the situation that it is faced with. To be able to do that, we have to begin with exploring C’s methods in making conditional statements.”

Conditional Operators

Before we head on to the different types of conditional statements available in C, we have to learn on some operators to be used first.

There are actually different kinds of operators in Python. To recall, we have already encountered the assignment operator (=) and the arithmetic operators (+,-,*,/,//,%,**), as well as the address operator (&).

However, there are two other important operators which will be widely used in making conditions in your program, and those are called conditional operators and logical operators.

Conditional operators are used to evaluate certain conditions if they are true or false. In C, the supported conditional operators are the following:

==

Returns TRUE if value1 and value2 are equal

Syntax:

value1 == value2

Returns TRUE if value1 is greater than value2

Syntax:

value1 > value2

>=

Returns TRUE if value1 is greater than or equal to value2

Syntax:

value1 >= value2

Returns TRUE if value1 is less than value2

Syntax:

value1 < value2

<=

Returns TRUE if value1 is less than or equal to value2

Syntax:

value1 <= value2

!=

Returns TRUE if value1 and value2 are not equal

Syntax:

value1 != value2



On the other hand, logical operators are useful when we need to evaluate two or more conditions before a code is proven to be true or not. Here are the following:

!

Returns TRUE if the condition is false

Syntax:

!condition

&&

Returns TRUE only if both conditions are true

Syntax:

condition1 && condition2

||

Returns TRUE if at least one of the conditions is true

Syntax:

condition1 || condition2
Cody

Did you know?

Every condition used in C works by the concept of Boolean values, which can only result as either 1 (True) or 0 (False). In some cases, any non-zero value is also regarded as True.

To test if it really is the case, let us use some conditional operators and print its result!

I’ve already made some samples for you, so feel free to try it out!

printf("%d", 10 > 5);

Now, let’s try assigning boolean values (0 and 1) and compare them with the use of some logical operators too!

#include <stdio.h>

int main(){

    int a = 1, b = 0;

    printf(“%d\n”, a && b);

    printf(“%d\n”, a || b);

    printf(“%d\n”, !a);

    printf(“%d”, !b);

    return 0;

}

The If() Syntax

When you want to decide on two options and your motive is just to act on either of the two, then the if() statement is right for the situation. If() statements are conditional statements that involve only one condition to be met in order for the code inside it to be performed.

This type of conditional statement follows the following syntax:

if (condition){
         // line of code;
}

Note that the line of code inside the curly braces of the if() statement will only be run if the condition put inside the parentheses is 1 (true); else, it will just skip those lines of code. Moreover, we must also remember to put our conditions in parentheses or else, we will encounter an error in our code!

For now, let us try out coding using this conditional statement:

#include <stdio.h>

int main(){

    int age;

    scanf(“%d”, &age);

    if (age < 18){

        printf(“Sorry, no beer for you yet, bud.”);

    }

    return 0;

}

But what if we wanted to say something if the if() statement’s condition turns false? Watch out for another conditional statement in the next topic, and keep moving forward!

Did you know?

You can actually remove the curly braces of the if() statement and it will work the same way! But there’s a catch to it though, since the condition would only apply to the first line after the if() statement. If there are multiple lines of code that should be run only when the condition is true, then it is required to put those curly braces when you code, or else, the only statement that will be affected by the condition is the first line after it. So it’s good programming practice to always put curly braces no matter how many lines in order to avoid logical errors!

Let’s consider this as an example to show you what I mean:

#include <stdio.h>

int main(){

    int a = 0, b = 2;

    if(a >b)

        printf(“YES\n”); //the only statement that will be affected by the condition if no curly braces are put

        printf(“GREATER”); //no matter if the condition is true or false, it will always be executed for that reason

    return 0;

}

Torn Between the Two

You have now “taught” Cody on how to make a decision when faced with one true condition! But how can he respond quickly on a situation where the condition is not true? To find out how, you flipped the next page of the sixth chapter of the instruction manual, which says:

“Deciding on one thing is easy, especially when you are only needed to respond when the condition given is true, but there are times when you need to act on something when the condition turns to be false as well, because when you are asked by a yes/no question, you can’t just stare blankly into space when your answer is no, right? Therefore, to make Cody act that way like humans do, we also have to teach him how to respond on false conditions with the use of C’s if statement counterpart: the else statement.”

The If Else syntax

We already know that when we want to run some lines of code only when the condition is true, we use a single if() statement. However, when we also have to run some code even if the if() statement’s condition is false, we have to add some else statement.

Else statements function just like the if() statement, but its condition is solely dependent on the if() statement’s condition; hence, it will only run the codes inside it when the condition of the if() statement is false.

To elaborate, it follows this syntax where there will always be an if() statement before it:

if (condition){
         //line of code
} else{
         //line of code
}

Thus, since it is dependent to the if() statement’s condition, the else statement can only function when preceded by an if() statement and cannot set a condition of its own.

So for example, when answering a yes/no question, you are now able to do so, like this one, when testing if the number is positive or not:

#include <stdio.h>
int main(){
         int num;
scanf("%d", &num);
 
if(num > 0){
         printf("Yes");
} else{
         printf("No");
}
 
         return 0;
}

Note that an else statement will only be used when you need to run some lines of code when a condition is false. If not needed, then do not write it in your code for good programming practice.

But what if the value to be inputted is zero in this case? It’s neither positive nor negative in nature. We shall know what can be done to solve this loophole in your code in the next topic ahead, so keep learning!

If Not That, Then What?

Cody’s getting better at making decisions, eh? But there is still more than what you have already learned when making decisions, and that is, when you encounter multiple options at the same time. Looking for answers, you found yourself looking at the third chapter of the book:

“Your robot’s now able to answer things when faced with a condition that can be either true or false, but what needs to be done when it is faced with more than one condition and only one has to be met? This calls for the help of one other conditional statement that offers the option of having another condition if the if() statement’s condition is false – C’s else if() statement.”

The Else If syntax

Else if() statements are conditional statements that are used to put another condition if the if() statement’s condition is not met. It quite functions like an if() statement as it can also have a condition of its own, but it is also like an else statement that needs an if() statement before it. Therefore, else if() statements cannot exist without a preceding if() statement.

It follows the following syntax:

if (condition){
         // line of code
} else if {
         // line of code
} else{
         // line of code
}

However, else if() statements can function well without an else statement after it, and can even be used multiple times when we need to have multiple conditions, like this syntax:

if (condition){
         // line of code
} else if {
         // line of code
}else if {
         // line of code
} else if {
         // line of code
} else{
         // line of code
}

Else if() statements are best used when faced with a problem that needs to be evaluated over several conditions, such as evaluating if an integer is positive, negative, or zero. In this problem, a mere if() else statement would not suffice as there is a special case on zero because it is neither negative nor positive. Hence, we have to utilize the use of else if() statements for it, like this:

#include <stdio.h>
int main(){
         int num;
         scanf(" %d", &num);
         if (num > 0){
                 printf("Positive");
         }else if (num == 0){
                 printf("Zero");
         }else {
                 printf("Negative");
         }
 
         return 0;
}

Remember that the condition inside an else if() statement will only be evaluated if the previous condition from an if() or a preceding else if() statement is false. Hence, by understanding this concept, we can now avoid repeating conditions that were already eliminated by the previous conditions given.

For example, in this code:

#include <stdio.h>
int main(){
         int num; 
         scanf(" %d", &num);
         if (num > 10){
                 printf("%d is greater than 10", num);
         }else if (num > 5){
                 printf("%d is greater than 5 but lesser than 10", num);
         }else {
                 printf("%d is lesser than 5", num);
         }
 
         return 0;
}

Looking at the conditions in there, if the first condition is evaluated as false, that would be the only time that the next condition is evaluated. Moreover, when the first condition is false if the number inputted is less than 10, we don’t have to rewrite a condition that tells that the number must be less than 10 since the first condition already proves that fact. By understanding that concept, we would now be able to make better conditions through these conditional statements.

Finding the One

Cody’s almost at the peak of mastering making decisions (with the help of your code, of course)! But there still is something more than meets the eye. Remembering that there is still one other type of conditional statement in Python, you began reading the last page of the current chapter:

“Your robot’s now able to answer things when faced with different types of conditions, right? But what could the best solution be if you are going to test a single value and run a code if the value is equivalent to the condition? Surely, having lots of if(), else if(), and else statements would do the trick, but it’s just too lengthy, don’t you think? That is why C offers one other conditional statement alternative that allows you to do so: using the switch() statement.”

The Switch() Syntax

Just like any other conditional statements, the switch() statement tests a single value on a number of conditions. However, the conditions that a switch statement can only deal with are those pertaining to equality of a set of values.

To put it simply, it allows us to test one value among many alternative values. Each of the alternative values that are to be compared with the value put under the condition of the switch() statement which we refer to as a case.

To elaborate, it follows the following syntax:

switch(value){
         case alt_value1: 
                 // line of code 
                 break;
         case alt_value2: 
                 // line of code 
                 break;
         case alt_value3: 
                 // line of code 
                 break;
         default: 
                 // line of code 
                 // default case is optional; can be removed
}

The switch() statement works by comparing the value to the alternative values of each case. If the alternative value equals to the value that is tested by the switch case, it will then proceed to executing the code after the case’s colon.

If no alternative value equals to the value, it will then execute the default case given at the end of the statements. It is good to know, however, that a default case is not required to be put in a switch() statement since it will work just fine even without it.

It is also important to put a break keyword after each case to ensure that when the condition is met for one case, it would not execute on the proceeding codes anymore, which saves runtime and prevents errors in code. The break keyword functions as a stopper to the switch code, so whenever the compiler encounters this inside the switch statement, it will stop the processes happening inside the switch statement and exit it, then proceed to the remaining lines of code after the switch() statement.

Cody

Did you know?

When you forget to put the break keyword after every case in a switch() statement, any other statements put in other cases after the case constant that makes the condition true will also be executed!

Here’s what will clearly happen when you do forget your break;

#include <stdio.h>

int main(){

    int num = 2;

    switch(num){

        case 1: printf(“1”);

        case 2: printf(“2”);

        case 3: printf(“3”);

        case 4: printf(“4”);

    }

    return 0;

}

For example, when we want to know the evaluation of a student based on its grade in letters, we can make a solution in a more efficient way using the switch statement, like this:

#include <stdio.h>
 
int main(){
         char grade;
         scanf(%c”, &grade);
 
         switch(grade){
                 case ‘A':
                          printf(“Excellent”);
                          break;
                 case ‘B':
                          printf(“Good”);
                          break;
                 case ‘C':
                          printf(“Satisfactory”);
                          break;
                 case ‘D':
                          printf(“Marginal”);
                          break;
                 case ‘F':
                          printf(“Inadequate”);
                          break;
         }
 
         return 0;
}

It is also important to remember that a switch statement can only evaluate a value that can either be a character or an integer. Other than that, it cannot work on other data types.

Cody

Did you know?

You can actually put more than one statement inside a case constant in a switch() statement! Just try to practice good indention to neatly see where each statement belongs to, and don’t forget the break keyword, too!

switch(num){
         case 1: 
                 // line of code
                 // line of code
                 break;
         case 2: 
                 // line of code
                 // line of code
                 // line of code
                 break;
}

Lesson Summary

Conditions

SyntaxTerms

If Syntax
if()
if (condition){
         // line of code
}
Else Syntax
if() else
if (condition){
         // line of code
} else {
         // line of code
}

*an else statement cannot function without an if statement before it.

Else If Syntax
if() else
if (condition){
         // line of code
} else if (condition){
         // line of code
} else {
         // line of code
}
Switch Statement
switch
switch(varName){
case val1:
         // line of code
         break;
case val2:
         // line of code
         break;
}

*the switch statement’s cases must always contain a break keyword inside it to ensure that when one condition is tested true, it will stop running the code there and exit the switch statement.

If Syntax
if()

a conditional statement that involves only one condition to be met in order for the code inside it to be performed

Else Syntax
else

a conditional statement that is used to perform lines of code when the condition of the preceding if() statement returns false

Else If Syntax
else if()

a conditional statement that is used to test a value for another condition if the if statement’s condition is not met

Switch Syntax
switch statement

a special conditional statement in C that works by comparing the value to the alternative values of each “case”

Until It Doesn’t Fit

At this point, Cody is now able to freely “decide on its own” with your application on conditional statements! Now we shall move on to making repetitive movements and decisions. In search for the next mission, you turned to the second-last chapter of the manual, which read:

“Don’t you wonder how it would be able to repeat something more quickly and efficiently? Up until now, the only way you can program your robot to do so is by duplicating statements manually. It works just fine, but just not when it has to be repeated a hundred times. To easily repeat statements requires our program to use a function in C that can perform repetitions at a given condition – a function we refer to as loops. There are a lot of types of looping structures, but for now we shall tackle the first one that deals with repeating steps until a condition is met, a kind of loop mostly known as a pre-checked loop – the while() loop.”

While Loop Syntax

Loops are like car wheels – they continue to turn around unless the driver steps on the brake whenever it arrives at the destination, pauses for a stoplight, or when a dog unexpectedly walks in front of the car. In the same light, loops in C work the same way like the car wheels, in which certain steps are done repeatedly until a certain condition is no longer met, or until a given sequence of numbers is finished.

There are three types of loops that are available in C: the while() loop, the do-while() loop, and the for() loop. Each loop in C works differently in some ways and are used for different purposes as well. To start off, we shall talk about the first type: the while() loop.

while() loop is used to execute lines of code inside it repeatedly until the condition it contains becomes false. Also known as a pre-checked loop, it functions in a way that it has to test if the condition is true before executing the lines of code inside it.

This is commonly used when the value you put in the condition statement is manipulated inside the loop until it reaches a value that falsifies the condition.

By convention, it follows the following syntax:

while (condition){
         line of code;
}

Basically, a while() loop’s structure looks and functions exactly like an if() statement, only that, it is executed repeatedly until it falsifies the condition.

However, it is important to note that just like an if() statement, when you use a variable in the condition of a while() loop, you have to declare and initialize it first before you can use it, or else you will encounter a name error, since the variable used in the condition does not exist yet unless declared.

To clearly see how a while() loop works, let us use it to count how many digits a number is. like this code below:

#include <stdio.h>
 
int main(){
         int num = 918; //a random number
         int ctr = 0; //counter for the number of digits
         while (num != 0){
                 ctr+=1; //increments by 1 if the num!=0
                 num/=10; //divides the number by 10 to decrease its value
         }
 
         printf("%d has %d digits", num, ctr);
 
         return 0;
}

Also remember that the value that you assign to the variable upon declaration must not directly falsify the condition given in the while() loop so that the while() loop will be executed.

A while() loop is mostly used to loop statements until a condition is false, but it could also work just like looping a sequence of numbers, for example, from 1 to 10! The key to doing this is by using an increment variable in the condition and increasing the value of it inside the loop, like this:

#include <stdio.h>
 
int main(){
         int main(){
         int i = 0;
         while (i < 10){
                 print("%d\n", i); 
                 //now we must increase the value of i to prevent forever loops
                 i+=1;
         }
 
         return 0;
}

Until You Say So

Cody has successfully acquired his first looping skill using while() loops! It really comes in handy when you want to manipulate a number repeatedly inside a loop or perform it for a given sequence with the help of incrementors. However, thinking about it, how can we loop something for an unknown number of times and stop when the user inputs something that will falsify its condition? Looking for answers, you find yourself reading the 2nd topic of the current chapter which states:

“If there are while() loops that check the condition of a loop before it executes the line of code inside it, also known as a pre-checked loop, then there are also post-checked loops in C, and these are what we will be discussing in this chapter: the do…while() loops.”

The Do While Syntax

do…while() loop serve the same purpose as the while() loop, as it will run the code repeatedly until the condition becomes false, only that, since this one is a post-checked loop, it guarantees that the code shall be executed first before testing the condition.

By convention, it follows the following syntax:

do{
         // line of code
}while (condition);

Hence, since it can execute the code before it tests its condition, we can now just declare the variable to be used in the condition without initializing it, considering that the value is to be changed inside the loop.

This is useful when we wish to ask for some random value from the user and loop that action until the user inputs a value that falsifies the condition, like this:

#include <stdio.h>
 
int main(){
         int num; //no need to initialize value anymore
         do{
                 scanf("%d", &num);
         }while(num >= 0);
 
         return 0;
}

Counting

Your Cody already knows how to repeat things until the condition becomes false, but how about repeating things until a given sequence is finished? Sure, a while() loop can do that, but is there really no other type of loop that simplifies that action? Eager to figure out the answer to your queries, you turned to the third chapter of the current lesson which states:

“You now know that while() and do…while() loops are used when you want to repeat something up until it falsifies the condition, but when you want to loop through a sequence of numbers in either ascending or ascending order, we need some other loop to do the trick. This calls for the help of C’s one last type of loop structure – the for() loops.”

For Loop Syntax

for() loop works the same as when using a while() loop to loop through a definite number of times while incrementing inside it, but this type of loop makes that code simpler, with all of its conditions put in just one statement.

Just like the while() loop, a for() loop requires you to use a counter variable, which is incremented for each loop iteration. Hence, we shall first declare a counter variable, and since its purpose is to count, it has to be an integer at all times. Hence:

int counterVar;

The counter variable can be set to any name, but most counter variables use at least a letter to represent it, like i, a, c, or a shorter term for counter, ctr.

It then follows a syntax like this one:

for (initialization; condition; incrementor){
         // line of code 
         // line of code
}

The first statement inside the for() loop’s parentheses is used to initialize the counter variable by assigning it to a number that will serve as the starting point of the loop. Upon entering the loop, this initialization will only happen once in the entire execution. It usually looks like this syntax below:

counterVar = startingNum;
Cody

Did you know?

In the latest version of C (that is currently used in CodeChum), you can actually just declare and initialize your counter variable in the for() loop’s parentheses! Just remember that the counter variable will always be an integer, so just put an int before the counter variable name, and initialize it to the starting value that you want to, like this!

for(int counterVar = startingNum; condition; incrementor){
}

The second statement will serve as the stopper of the loop, as it gives out the condition that has to stay true for the loop to work, until it falsifies the condition. However, the value that it has to test per loop iteration has to be the counter variable that we used for the loop and it has to always be compared by a number that will serve as the ending point of the loop. Moreover, since it is indeed a condition, just like conditional statements, it makes use of conditional operators (see Lesson 4) for the condition to work, like this one:

counterVar <= endingNum;

Now, the last part of the statement inside the parentheses of a for() loop is the most important part of the loop for it to avoid looping forever because of a static counter variable value, and that is what the incrementor does. In this statement, all we have to do is to increase or decrease the value of the counter variable for it to get closer to the value set in the condition, and finally terminate the loop. Since it is an incrementor, it shall utilize the increment operators that was discussed in the previous chapter. For example, if we want to increase the counter variable value by 1, we can use this kind of syntax:

counterVar

Always remember that all of the statements inside the for() loop’s parentheses, except the incrementor, end with a semicolon. If another symbol is to be put by mistake in place of the semicolon, it will instead generate an error, so always keep that in mind, okay?

So, this works well when you want your program to count off from a certain number to another, and it is commonly used when we want to loop a set of instructions for a fixed number of times.

Now that we have understood how it works, let us see how a for() loop makes the code more efficient than we thought it could be!

For example, when you wish to print all even numbers from 10 to 20, you can achieve the result by typing in the printf() function repeatedly and you have to memorize the even numbers, too:

printf("10\n");
printf("12\n");
printf("14\n");
printf("16\n");
printf("18\n");
printf("20");

But with a for() loop, what used to be 5 lines of printf() statements, can now be reduced to just one, like this!

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

Efficient, ain’t it?

Cody

Did you know?

You can also perform a loop inside a loop too! These are what we call as nested loops, where the inner loop(s) acts as an egg that is enclosed by the outer loop that acts as a nest to the inner loop(s). In C, it is usually treated like a table, where the outer loop is usually referred to as the row, and the inner loop, the column.

It follows the following syntax:

for(initialization; condition; incrementor){
         // optional line of code
         for(initialization; condition; incrementor){
         // line of code
         }
}

This works just like a normal loop, but the difference is that the inner loop must be executed first before re-looping the outer loop. Therefore, the outer loop can only repeat the lines of code inside it when the inner loop is done executing its own.

For example, let us try making a 6×6 rectangle using asterisks!

#include <stdio.h>

int main(){

    for(int row = 0; row < 6; row++){

        for(int col = 0; col < 6; col++){

            printf(“*”);

        }

    //let’s print a new line to make rows when printed

    printf(“\n”);

    return 0;

}

This method is incredibly useful when making two-dimensional patterns using C.

Did you know?

There are only two ways to loop a for() loop: in ascending order, or in descending order.

If you wish to loop in ascending order, the value you initialize to the counter variable must be of lesser value than the value you give to the condition.

Moreover, the only conditional operators you can use are those involving the less than sign(<), and that but paired with an equal sign (<=). The increment operator shall also be limited to addition (+) and multiplication (*) to increase the counter variable’s value.

For example, when we want to print from 1 to 10, we should do this:

#include <stdio.h>
 
int main(){
         for(int i = 1; i <= 10; i++){
         printf("%d\n", i);
}
 
         return 0;
}

However, when you want to loop it in descending order, the counter variable must be initialized to a value greater than the value in the condition statement, and it shall only use either the greater than(>) or the greater-than-or-equal-to (>=) conditional operators.

Moreover, it shall only use decrement operators involving subtraction (-) and division (/) to decrease the value of the initialized counter variable for every iteration.

Hence, if we would like to print from 10 to 1 instead, we can do this:

#include <stdio.h>
 
int main(){
         for(int i = 10; i >= 1; i--){
         printf("%d\n", i);
}
 
         return 0;
}

Understanding this concept will help you get more familiar with using for() loops in your code, so feel free to practice executing for() loops for better learning through experience, okay?

Stop and Skip

Cody has acquired the looping ability! Now it just needs a few more touches to master it. Looking for the last ingredient in using loops, you found what you were looking for in the last topic of the current lesson of the instruction manual and began reading:

“Loops are very handy for doing routines and repetitive actions for your bot, right? But oftentimes, when faced with a special condition, like an emergency or an exception, humans tend to stop their repeated actions or skip something, and that is what we need to teach your bot. In order to learn how to stop or skip at certain special conditions, we make use of the control statements in C that can only be mostly used inside loops – break and continue.”

How To Break

Loops normally stop when a condition becomes false (while and do..while loops) or when a sequence of values is terminated (for loops). However, when we want the loop to suddenly stop even without the normal way of terminating it, we use the keyword break. This helps when searching through values and breaking out from the loop even before it normally terminates.

Remember how the switch() statement utilizes the break keyword to stop it from executing further lines of code when it encounters one? It works the same with loops, but for good programming practice, it has to at least be inside conditional statements so that when that special condition becomes true, it will immediately terminate the loop.

For example, when we want to stop executing when the counter variable becomes 5, we can do it inside a for() loop using the break keyword:

for (int i = 0; i < 10; i++){
         if(i == 5){
                 break;
         }
 
         printf("%d ", i);
}

Using this method instead of looping through the entire string will increase efficiency of code and lessen the amount of time it takes the code to process everything, but remember to use it only when you need it, okay?

How To Continue

A break statement is used to stop a loop when it encounters a value that makes the condition false, but when we just want to ignore or skip the value when it makes the condition false and then go on with the loop until it ends, we use the keyword continue. This helps when we want to skip or leave out a certain value from becoming part of an execution or when we want to skip out on all other parts of code below this keyword before looping again.

For example, when we don’t want to print out multiples of 3 in our code, we can use continue to ignore multiples of 3 and then loop again, like this:

for (int i = 0; i < 20; i++){
         if(i % 3 == 0){
                 continue;
         }
 
         printf("%d ", i);
}

Remember that the continue statement only skips an execution of a loop based on a special condition but it does not fully terminate the entire loop unlike the break statement.

Lesson Summary

Loops

SyntaxTerms

While Loop
while()
while (condition){
         // line of code
}

*the value that we would test inside a while loop’s condition must be declared and initialized first to a random value (that will not falsify the condition first) to avoid error.

Do…While Loop
do…while()
do{
         // line of code
} while (condition);
For Loop
for
for (initialization; condition; incrementor){
         // line of code
}
Break and Continue
break
for (initialization; condition; incrementor){
         if(condition){
                 break;
         }
}
continue
for (initialization; condition; incrementor){
         if(condition){
                 continue;
         }
}
While Loop
while()

a loop used to execute lines of code inside it repeatedly until the condition becomes false

Do…While Loop
do…while()

serve the same purpose as the while() loop, but guarantees that the code shall be executed at least once before testing the condition

Break and Continue
break

used to stop a loop when it encounters a value that makes the condition false

continue

used when we just want to ignore or skip the value when it makes the condition false and then go on with the loop until it ends

How to Make an Array

What’s an Array?

As far as we have known, when we want to store multiple values of the same data type in a program, we can just have some remedy by making multiple variables to store each of them. However, it would be unimaginable to do so if we have to store a hundred of values in one sitting, right? What’s more, it would also cause a big headache when maintaining the code when we have to change something from each of the values. This is where arrays enter the scene to solve this type of problem.

An array is basically an ordered collection of values having the same data type. It functions like a big container, which has sub-containers that store each value that is put inside it, and has a fixed size once declared in the program. Since it is an ”ordered” collection of values, each value has its own index positions inside the array where it belongs to, with the position number starting from 0 until one less than the array size (array_size-1), in ascending order.

Therefore, we can think of arrays as something like this one:

Array Graph

Making an Array

In C, arrays are created by declaring it just like a normal variable, but with an addition of the array size beside the variable name. To illustrate, the most common way to make an array is by doing this:

data_type arrayName[size];

However, you can also make an array and assign it with its initial values as well! Just put the values inside a pair of braces () and separate it with commas (,), like this:

data_type arrayName[4] = {value, value, value, value};

Note that the size of the array put inside the square brackets must always be a positive integer and the number of values to be put inside an array must not go beyond its size for good programming practice.

Data Types of an Array

Unlike other programming languages that allow data type flexibility on its arrays, C is data type-specific, meaning, all values that are put inside an array must be of the same data type as the array itself.

A C array can be an ordered group of numbers, with its data type either in int, long int, float, or double. When initializing these values in an array, we can just simply write it as the normal array initialization, like these examples below:

int numArr[10] = {-1,2,-3,4,-5,6,-7,8,-9,0}; // same for long int
float numArr2[5] = {3.14, 9,8, 10.5, 0.4, -23.23}; // same for double

On the other hand, arrays could also be an ordered group of characters, commonly known as a string, with data type char. Arrays of this data types can also be initialized using the same method as with numbers, only that each characters must be enclosed with single quotes, like this:

char stringArr[10] = {'C','o','d','y'};

However, since these are considered strings, it could also be initialized by simply assigning it to a string of text enclosed with double quotes and it will work the same way as the former, like this:

char stringArr[10] = "Cody";

It is important to take good notice of the size of the string array, though, in order to prevent assigning texts with length beyond the assigned size to prevent errors.

Cody

Did you know?

For strings (array of characters), there are two special input and output functions that are made just for this data type. These are fgets (a.k.a file-get-string) and puts (a.k.a put-string).

The input function, fgets(), specializes in taking string inputs. This helps take care of the errors that might happen when using scanf() for getting the string, especially when the text you type in contains spaces. fgets() follows this syntax:

fgets(arrName, size, stdin);

In here, fgets() need to have three things inside its parentheses: the array name, its allocated size, and how it’s going to be taken as; in this case, it’s stdin(standard input) which meant using the keyboard for taking in the string value.

Puts(), on the other hand, is an output function made especially for string values, as it would directly print out the entire string inside the array just by putting in the name of the array inside its parentheses. However, it also allows direct string printing just like printf(). Puts() follows this syntax:

puts(arrName);
puts("string text");

The only difference between printf() and puts() when printing out strings, is that puts() generates a new line after the end of the string it prints out by default, and you can’t use placeholders or type anything else inside the puts() function.

To test out these amazing string functions for input and output, let’s try using those in real code, like this code below:

#include <stdio.h>

int main(){

    char strArr[100];

    fgets(strArr, 100, stdin);

    puts(strArr);

    return 0;

}

Did you know?

If an array is a string, you can also get its length by simply using the function strlen()! This is a string function found in the string.h library that allows you to generate the length of the string array! It follows this syntax:

strlen(arrName);

Just remember to put in #include <string.h> together with the other preprocessor directives that you need in order for this function to work. There are a whole lot more that this library can give you, so go ahead and search for other functions inside this library, too! Maybe it’ll come in handy soon.

Let’s try this code to see how strlen() works!

#include <stdio.h>

#include <string.h>

int main(){

    char strArr[100];

    fgets(strArr, 100, stdin);

    //since you can’t type anything else using puts(), 

    //you can print something else together with the array this way

    //using printf():

    printf(“String: %s\n”, strArr);

    printf(“Length: %d”, strlen(strArr));

    return 0;

}

An Array Element

Cody now knows how to make a array of things, just like a normal human! But did you know that you can actually access, change, or manipulate any item from an array of any data type? To know how to do it, you read the second topic of the last chapter of the manual which states:

“Arrays are so efficient that we can put similar things together if we need to, like a list of numbers or letters! But when we want to change something or know about the contents inside an array, there is one method in C where we can do just what we need: through accessing array indices.”

Adding an Element to a List

Arrays are an ordered group or list of values, and since it is an ordered list, each value that is stored inside of it is put in corresponding positions inside the array. In technical terms, these positions are what we call as indices.

Now, since each value inside an array has its own index position, accessing array values is now possible thanks to these array indices! Accessing array values using indices is as simple as this syntax below:

arrName[index_position]

We must always remember though, that an array index always start off with 0 and ends with its size-1. Therefore, in an array of 5 integers, we can only access from 0-4, and if we access more than that, we can get some random value instead, like this:

#include <stdio.h>
 
int main(){
         int arr[5] = {1,2,3,4,5};
         printf("%d\n", arr[0]);
         printf("%d\n", arr[1]);
         printf("%d\n", arr[2]);
         printf("%d\n", arr[3]);
         printf("%d\n", arr[4]);
         printf("%d", arr[5]);
 
         return 0;
}
Cody

Did you know?

Just like in variables, we can also overwrite values in lists by accessing its index position and then assigning it to a new value, like this:

arrName[index_position] = value;

So if we want to change the value of that certain part of the array, we can now easily do so by accessing it using its index position, like this:

#include <stdio.h>

int main(){

    int arr[5] = {1,2,3,4,5};

    printf(“Original Value: %d\n”, arr[2]);

    //let’s change 2 into 8 by applying the method above!

    arr[2] = 8;

    //now when we print it, that will now become 8.

    printf(“New Value: %d”, arr[2]);

    return 0;

}

Traversing the Array

You already know how to make and manipulate lists now, and you might think that your C journey has come to an end, but there is actually still one more thing you need to learn to program Cody more efficiently when it comes to storing and changing lists repetitively. Excited to read the final topic of the final chapter, you took the instruction manual and from there, it writes:

“You are now one step away from the goal which you started when you first read this manual, are you? Now, let me teach you the art of combining arrays and repetitive actions with the use of loops. This will be a very important concept especially when adding or manipulating values inside the array. Hence, let me introduce you to one final concept of list manipulation in C in repetition – the combination of loops and lists.”

Add Items to Array

We now know that we can add items to an array either by initializing it all together in one single line, but how can we add values in the array based on the inputted values from the user, one at a time?

This is where loops play an important role in making your task possible. For example, when we want to add values one by one, we can incorporate the concept of accessing index positions and continuous scanf() in a loop, like this:

#include <stdio.h>
 
int main(){
         int arr[10];
         //we start the loop at i = 0 since array index starts at 0
         for(int i = 0; i < 10; i++){
                 //we ask for input every iteration 
                 // and store it from arr[0] to arr[9] but instead of typing it
                 //everytime, we can efficiently do that through loops:
                 scanf("%d", &arr[i]);
         }
 
         //now let’s print to see if it really works!
         for(int i = 0; i < 10; i++){
                 printf("%d\n", arr[i]);
         }
 
         return 0;
}

Array Manipulation via Loops

There are times when you want to change each of the values inside an array and it can actually be done manually by accessing the value by index position then overwriting it, but it’s quite tiring to do that when you have more than 10 items on the list, right?

But with loops, doing so have never been easier.

For example, when we want to change the values of the array into the square of its original value, we can easily do it like this:

#include <stdio.h>
 
int main(){
         int nums[10] = {1,2,3,4,5,6,7,8,9,10};
         for(int i = 0; i < 10; i++){
                 nums[i] *= nums[i];
                 printf("%d\n", nums[i]);
         }
 
         return 0;
}

Lesson Summary

Arrays

SyntaxTerms

Ways to Make an Array
Array Declaration
data_type listName [size];
data_type listName [size] = {val1, val2,val3};
Accessing Array Elements via Indices
Array Indexing
arrName [index_position];
arrName [index_position] = value;
ctype.h Function
including ctype.h library
#include <ctype.h>
isalpha()
isalpha(value)
isalpha(varName)
isdigit()
isdigit(value)
isdigit(varName)
isalnum()
isalnum(value)
isalnum(varName)
isspace()
isspace(value)
isspace(varName)
ispunct()
ispunct(value)
ispunct(varName)
isupper()
isupper(value)
isupper(varName)
islower()
islower(value)
islower(varName)
toupper()
toupper(value)
toupper(varName)
tolower()
tolower(value)
tolower(varName)
Ways to Make an Array
array

an ordered collection of values having the same data type

Accessing Array Elements via Indices
index position

position of a character element in a string

*a string’s index position will always start with 0 and end with len(str_var)-1.

ctype.h Function
ctype.h

a C library that stores a wide array of functions that are specially made to classify and/or manipulate individual characters in C

Assignments:

Go to https://code.sololearn.com/c , sign up, sign in, and start coding to do the 4 assignments below then copy the codes and links then email it.

  1. Samurais are so awesome! I’d like to imitate their amazing sword skills some time but I just don’t have the courage to harm myself, so I’d just like to print out three forward slashes (/) to digitally imitate the samurai’s triple slash skill. Haha! Sounds easy, right? Then code it now!
  2. Let’s play a game of FizzBuzz! It works just like the popular childhood game “PopCorn”, but with rules of math applied since math is fun, right? Just print out “Fizz” when the given number is divisible by 3, “Buzz” when it’s divisible by 5, and “FizzBuzz” when it’s divisible by both 3 and 5! Let the game begin!
  3. Remember the game of FizzBuzz from the last time? Well, I thought of some changes in the game, and also with the help of loops as well. Firstly, you’ll be asking for a random integer and then loop from 1 until that integer. Then, implement these conditions in the game: a. – print “Fizz” if the number is divisible by 3: b. – print “Buzz” if the number is divisible by 5; c. – print “FizzBuzz” if the number is divisible by both 3 and 5; and d. – print the number itself if none of the above conditions are met
  4. I want you to make a array of numbers for me. All you have to do is make a program that will let me input any random integer in one line. Afterwards, it will then print out all the numbers I’ve inputted, on separate lines. Care to do that for me?