0% found this document useful (0 votes)
3 views12 pages

C Basic Programming Q1 - Week 4 & 5

This document is a lesson on basic C programming, specifically focusing on the printf() function for outputting text and numbers. It covers the syntax for using printf(), the importance of including the <stdio.h> header file, and introduces escape sequences for formatting output. Additionally, it explains the use of placeholders for different data types in printf() statements, including formatting options for decimal places.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

C Basic Programming Q1 - Week 4 & 5

This document is a lesson on basic C programming, specifically focusing on the printf() function for outputting text and numbers. It covers the syntax for using printf(), the importance of including the <stdio.h> header file, and introduces escape sequences for formatting output. Additionally, it explains the use of placeholders for different data types in printf() statements, including formatting options for decimal places.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

BASIC C PROGRAMMING – HOW TO PRINT

(Lesson 2)
COMPUTER PROGRAMMING 10 – WEEK 5 & WEEK 6
Topic 1

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 be able to use this standard output function. Let's try doing just that!
BASIC C PROGRAMMING – HOW TO PRINT
(Lesson 2)
COMPUTER PROGRAMMING 10 – WEEK 5 & WEEK 6
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:

Code
main.c
keyboard_arrow_leftkeyboard_arrow_right
#include<stdio.h>

int main() {
printf("Hello World!");

return 0;
}

restoreplay_arrowExecute Code
Run the code above and see the output! Try changing the text inside the double quotes
to something else and see that it still works perfectly fine.

Did you know?


Almost every single-lined statement in C, except for preprocessor directives (the one
where we include the libraries), usually ends 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. Try running the code below.
Code
main.c
keyboard_arrow_leftkeyboard_arrow_right
BASIC C PROGRAMMING – HOW TO PRINT
(Lesson 2)
COMPUTER PROGRAMMING 10 – WEEK 5 & WEEK 6
#include<stdio.h>

int main() {
printf("Hello World!")

return 0;
}

restoreplay_arrowExecute Code
To fix the program above, just add a semicolon at the end of the printf line of code.
Once you've done that, try running the code again and see that there are no more
errors.
Sample Problem 1
Hello, Programmer!
Let’s try to make Cody emphasize his name when speaking! The code needed to do
that is already prepared for you. To see the magic happen, run the code by clicking on
the Run Code button now!

Code
main.c
keyboard_arrow_leftkeyboard_arrow_right
#include<stdio.h>

int main() {
printf("My name is 'Cody'.");

return 0;
}
BASIC C PROGRAMMING – HOW TO PRINT
(Lesson 2)
COMPUTER PROGRAMMING 10 – WEEK 5 & WEEK 6
Topic 2

When to Pause
Feeling happy about your learning on how to print in 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 along with 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
BASIC C PROGRAMMING – HOW TO PRINT
(Lesson 2)
COMPUTER PROGRAMMING 10 – WEEK 5 & WEEK 6
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!")
Output:
Hello World!
\n
Prints the proceeding text to a new line
printf("Hello\nWorld!")
Output:
Hello
World!

\\
Prints a backslash
printf("Hello\\World!");
Output:
Hello\World!

\"
Prints a double quote inside texts enclosed in double quotes
printf("\"Hello World!\"")
Output:
"Hello World!"
Sample Problem 1
Give me Some Space!
When you want to let your words breathe when speaking, and to avoid sounding like a
robot (even if you already are), you have to give your words some space, even just a
little. But if you'd like to take longer pauses when speaking, you could use some help
with the tab escape sequence.

Say, for example, you want to announce something, and you'd like to put some
excitement with pauses, you do it like this!
BASIC C PROGRAMMING – HOW TO PRINT
(Lesson 2)
COMPUTER PROGRAMMING 10 – WEEK 5 & WEEK 6
Code
main.c

keyboard_arrow_leftkeyboard_arrow_right

#include<stdio.h>

int main() {

printf("Are you ready\tto be the next\tCoding Hero?");

return 0;

restoreplay_arrowExecute Code

Sample Problem 2
Making a Haiku
You know what's the good thing about being human-like? Being creative! And one proof
of being creative is writing a poem. For starters, let's teach Cody how to make a haiku!
It's a 5-7-5 syllable poem composing of three lines. Oh! Speaking of lines, we need
something to create them, and this calls for, the new line escape sequences!

Run to code to see the magic!

Code
main.c

keyboard_arrow_leftkeyboard_arrow_right

#include<stdio.h>

int main() {
BASIC C PROGRAMMING – HOW TO PRINT
(Lesson 2)
COMPUTER PROGRAMMING 10 – WEEK 5 & WEEK 6
printf("I love my Cody\nIt's part of my family\nIt makes me happy.");

return 0;

Topic 3

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:
BASIC C PROGRAMMING – HOW TO PRINT
(Lesson 2)
COMPUTER PROGRAMMING 10 – WEEK 5 & WEEK 6
"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

A 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. Hang in there, it's gonna
make sense in a while!
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
BASIC C PROGRAMMING – HOW TO PRINT
(Lesson 2)
COMPUTER PROGRAMMING 10 – WEEK 5 & WEEK 6
%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

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!


Code
main.c
keyboard_arrow_leftkeyboard_arrow_right
#include<stdio.h>

int main(void) {
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 %f a month", 7500.00);

return 0;
}

restoreplay_arrowExecute Code
Try running the code above and you'll notice something odd. Found it? That's right, the
last value where we used %f printed out a number with 6 decimal places. Just how do
we format that so that there's only two decimal places in the output?
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?
BASIC C PROGRAMMING – HOW TO PRINT
(Lesson 2)
COMPUTER PROGRAMMING 10 – WEEK 5 & WEEK 6
Just use the syntax ("%.2f") for float or ("%.2lf") for double 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!

Code
main.c
keyboard_arrow_leftkeyboard_arrow_right
#include<stdio.h>

int main(void) {
printf("Pi is equivalent to %.3f", 3.1415926);
return 0;
}

restoreplay_arrowExecute Code
Now, 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(void) {
printf("Hi! My name is %s and I am %d years old from the date of my creation.",
"Cody", 2);

return 0;
BASIC C PROGRAMMING – HOW TO PRINT
(Lesson 2)
COMPUTER PROGRAMMING 10 – WEEK 5 & WEEK 6
}

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, just the display)

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!


Code
main.c
keyboard_arrow_leftkeyboard_arrow_right
#include<stdio.h>

int main(void) {
printf("%03d\n", 7);
printf("%03d", 700000);

return 0;
}

restoreplay_arrowExecute Code
Sample Problem 1
How Much?
There will come a time where Cody will need to buy something at a grocery or a
convenience store with his human friends in the future, and for it to be able to recognize
the money format with cents in the country, he has to learn to limit his digits into two
decimal places, since it would be weird if he would just directly blurt out the amount of
BASIC C PROGRAMMING – HOW TO PRINT
(Lesson 2)
COMPUTER PROGRAMMING 10 – WEEK 5 & WEEK 6
money in 6 decimal places, right?

You can do this by simply using placeholders! In this case, since the value is a number
with decimals, we need to use %f, and then limit it to two decimals, therefore resulting to
a %.2f placeholder.

Let's see how it works!

Code
main.c
keyboard_arrow_leftkeyboard_arrow_right
#include<stdio.h>

int main(void) {
printf("An apple costs P%.2f", 20.2525);

return 0;
}

You might also like