Microcontroller Embedded C Programming Lecture 19| Printf exercise solution

Printf exercise solution

 

 

Write a program that displays  David says, “programming is fun!”. The goal was to print a text or a string in double-quotes. 

 

Solution

When you use printf, you should always write your message inside the double-quotes; you should remember that. And our string was, “David says, “programming is fun!” “. This is our message. Now let’s terminate the statement with a semicolon. 

Let’s run this. Here you met with some errors(Figure 1). So, let’s check the error.

Figure 1. Exercise
Figure 1. Exercise

 

Error is expected )’ before ‘programming’. So, inserting a bracket before programming is not correct, that’s not what we wanted.

Here we are confusing the compiler by giving too many double-quotes. If you want to print a double quote, you have to use the associated escape sequence. 

So, we have to tell the compiler to consider a double quote as a normal character; otherwise, the compiler will consider it the beginning of the printf statement. So, we tell that by using the escape character. Our escape character is, you know, that is a backslash. Now we are to take the help of backslash. Give the backslash before the double quote, as shown in Figure 2. 

When you give the backslash before the double quote, the letter or character will be considered a normal printable character.

And after that, let’s give \n to go to the following line, and here let’s print “Good day !”.

 

Printf exercise solution - Print a text or a string in double-quotes
Figure 2. Using backslash double quote (\”)

 

From this article, you should understand that you have to use this escape sequence: backslash double quote(\”) to print a double quote.

 

Now, if you want a single quote, then you can use a backslash single quote(\’), no problem, as shown in Figure 3. 

Let’s run. You can see that it has been printed with a single quote.

Printf exercise solution - Print a text or a string in double-quotes
Figure 3. Using backslash single quote (\’)

 

Or you can omit the backslash and only use single quotes, no problem with that. So, both are the same. And it should work fine, shown in Figure 4.

Printf exercise solution - Print a text or a string in double-quotes
Figure 4. Omit the backslash and use the single quote

 

FastBit Embedded Brain Academy Courses

Click here: https://fastbitlab.com/course1

 

 

FastBitLab

The FastBit Embedded Brain Academy uses the power of internet to bring the online courses related to the field of embedded system programming, Real time operating system, Embedded Linux systems, etc at your finger tip with very low cost. Backed with strong experience of industry, we have produced lots of courses with the customer enrolment over 3000+ across 100+ countries.