I. Introduction to Variables
Ah, the variables! If we were to make an analogy to explain this concept in programming, we could say that variables are like those little mysterious boxes that you may have used as a child to store your treasures. They can hold a multitude of things, and each one has its own label to remind you what's inside. In the world of coding, these “treasures” are information that we want to store and use later.
Imagine that you are a budding magician, preparing a magic trick. Before you go on stage, you need to prepare all your props, like bunnies, scarves or cards. You can't just throw them all in a big box and expect to quickly find them right in the middle of your performance. No no ! You store them neatly in separate boxes, each labeled so you know exactly where each accessory is. This way, during the show you can easily find what you need.
In programming, it's the same. We use these “boxes” (or variables) to store information like numbers, characters or even sentences. And like the magic trick, we want to make sure we can quickly access this information when we need it. This is why we give them specific names, or “labels”.
But why are they so essential, you ask? Well, without variables, our programs would be incredibly limited. Imagine trying to solve a math problem without being able to write down the numbers or intermediate results. That would be difficult, wouldn't it? Variables give us the flexibility and power we need to write programs that can accomplish all kinds of tasks, from the simplest to the most complex.
So, get ready! We'll dive into the fascinating world of variables and discover how they can make our C coding journey both magical and methodical. 🎩🔮
II. Declaration and Initialization
If you've ever been to a magician's workshop (or DIY workshop, let's be real), you must have seen all kinds of tools and gadgets. Before using them, you need to know what they are for and how to handle them. Similarly, before using variables in C, we must first declare and initialize them. Come on, let’s take the plunge!
Variable declaration
The statement is like telling the computer, “Hey, I'm going to need a box to put something in!” In the C world, this looks like:
int myNumber;
Here, int is the type of the variable (we'll come back to that in a moment) and myNumber is the name you give to your variable, its label if you will. It is thanks to this label that you will be able to access the box later.
Variable initialization
Now that you have your box, it's time to put something in it. This is called initialization. Let's take our previous box:
myNumber = 42;
Tadaaa! Your named box monNombre now contains the number 42. But wait, there's an even faster way to do both steps at once:
int myNumber = 42;
There you have it, declaration and initialization in a single line! Clever, isn't it?
Choosing the Right Type
Let's say you have a box intended to hold coins, but you're trying to fit a large magician's wand into it. This isn't really going to work, is it? Similarly, in programming, it is crucial to choose the right type for each variable. If you choose the wrong type, your program might behave unpredictably or even crash.
For example, if you want to store an integer, you would use int. But if you want to store a letter or character, you will use char. There's a whole universe of variable types that we'll explore soon, and each has its own role to play.
In summary, choosing the right type for your variables is like choosing the right costume for a magical performance. You want everything to be perfect so the show goes off without a hitch!
So, are you ready to explore this vast world of variable types? Get out your chopsticks (or, more accurately, your keyboards), and let's get started! 🧙♂️🔍
III. Types of Variables
Ah, variable types! Just as a magician needs to know the different types of tricks in his arsenal, a programmer needs to know the different types of variables at his disposal. Let's start with one of the most common: theint.
Integers (int)
🎩 What is a int ?
In the world of programming, int is the diminutive of “integer”, which means “whole number” in French. So when you declare a variable of type int, you're basically telling your computer, "Hey, I'm going to need a box to store an integer!" No commas, no periods, just a good old whole number, whether positive, negative or even zero.
int age = 30; // I'm sure some of you are surprised, huh? 😉
🔍 When to use int ?
Use int when you need to store integer values. Whether it's the age of a person, the number of pages in a book, the score of a game or the amount of ingredients for your magic potion, if it's a whole number, int is your friend.
📊 Range of values for a int
Here, the magic gets a little complicated. The range of values that a int can store depends on your system and compiler. However, generally, on a 32-bit system, a int can contain values ranging from -2,147,483,648 to 2,147,483,647. It's huge, isn't it? But, as with everything, it has its limits. If you go beyond this range, you may encounter unexpected behavior, a bit like trying to conjure a dragon into a small box. 🔥
If you know in advance that your numbers will always be positive and want to save space, you can also use unsigned int. As the name suggests, it can only store unsigned (positive) values, which doubles its maximum capacity, but makes it incapable of storing negative numbers.
That's it for the basics of integers in C. With this knowledge, you're well equipped to do arithmetic, count objects, and even gauge how many pointy hats you can stack before the tower collapses! 🎩🎩🎩
Next step ? Let's dive deeper into the wonderful world of variable types!
Putting it into practice with VS Code
1. Open VS Code.
If you haven't already done so, open the file where your “Hello, World!” program is located.
2.Let's integrate a variable int.
Just before the line printf("Hello, World!n");, add the declaration of a variable int to store an age, for example:
int age = 30;
3. Let's display the age.
Edit the line printf to display this age:
int age = 30; printf("Hello, World! I'm %d years old.\n", age);
Note: The %d is a place marker for an integer (int). When printf see %d, he knows he has to replace this %d by the value of the variable int provided, in this case, age.
4. Compile the program.
Open the VS Code built-in terminal (Terminal > Nouveau terminal). Place yourself in the correct directory if you have not already done so.
Type the following command to compile the file:gcc premier_programme.c -o mon_programmeThis compiles your source code and creates an executable file called “mon_programme".
5. Run the program.
In the terminal, type:./ (or simply mon_programmemon_programme if you are on Windows).
You should see something like this:Hello, World! I'm 30 years old.There you go, you've refreshed your memory on compilation and execution while integrating a new concept into your program! The good life, right? 🎉🍹
Remember, every time you change your code, you need to recompile it before running to see the changes. It's like cooking: after adding new ingredients to the recipe, you have to cook the dish again to enjoy the new taste! 🍳🥘
Floating Point (float and double) 🌊
Ah, the numbers! They're everywhere, from step counters to calculators. But what happens when we want to represent numbers that aren't so neat? For example, if you walked 2,5 kilometers or drank 1,75 liters of water, how can you express these fractions in programming? This is where floating point numbers come to the rescue!
1. What is a floating point number? A floating point number is a way to represent real numbers (those with decimal places). It's a bit like having a scale that can measure down to the lightest grams. Practical, isn't it?
2. Float vs Double: The balance of precision There are two main players here: float et double.
- float :
- Takes 4 bytes (32 bits) in memory.
- Has a precision of approximately 7 decimal places.
- Example: If you walked
3.141592kilometers today.
- Double :
- Takes up 8 bytes (64 bits) of space.
- Boasts accuracy up to 15 decimal places.
- Example: If you have been drinking
3.141592653589793liters of water. You really need to go to the bathroom.
But which type to choose? If precision is your game, double is your name. Otherwise, for most common uses, float is perfect.
3. Let’s dive into VS Code! 🛠️ Go back to our previous program where we talked about age. Now let's imagine that we also want to share how much water we drank today. Or, maybe the number of miles we walked. Let's use a float for that :
#include <stdio.h>
int main() {
int age = 20;
float kilometers_marches = 2.5; // It is good for your health!
printf("Hello, World! I'm %d years old.\n", age);
printf("I walked %.2f kilometers today.\n", walked_kilometers);
return 0;
}
Note: You see this %.2f in the printf? This is called a format specifier. Here it says we want to display a floating point number with 2 decimal places. If we had used %f alone, this would have displayed the number with 6 decimal places by default, which might be a bit too much to indicate distance traveled.
Don't forget to compile and run again with our favorite commands:gcc premier_programme.c -o mon_programme
./mon_programme
So how many miles have you covered today? 🚶♂️🚶♀️
Characters (chariot) 🅰️🅱️
Do you remember the last time you wrote a letter by hand? An A, a B, or even a capital Z? In programming, these letters, along with other symbols such as !, #, and $, are considered “characters”. But, how are these letters and symbols represented in computing? This is where the guy char comes in.
1. What is a character in programming? A character is a letter, number or symbol. In C we use the type char to store a character. For example, char maLettre = 'A'; stores the letter 'A' in the variable maLettre.
2. A little history: ASCII When we talk about storing characters in computing, we are referring to a system called ASCII code. ASCII stands for “American Standard Code for Information Interchange”. Each character has a unique number, called an ASCII code, assigned to it. For example, the ASCII code for 'A' is 65, and for 'a' it is 97.
Here's a little tip: If you want to know the ASCII code of a character, you can simply convert it to an integer using printf !
3. Let’s dive into VS Code! 🛠️ Let's take our previous program and add a character to it. Suppose we want to share our favorite letter with the world:
#include <stdio.h>
int main() {
int age = 20; // Declaring an integer variable / Declaration of an integer variable
float kilometers_walked = 2.5; // Declaring a floating-point variable / Declaring a floating-point variable
char favorite_letter = 'A'; // Assuming this is our favorite letter / Suppose that it is our favorite letter.
// Printing different types of variables
// Printing different types of variables
printf("Hello, World! I am %d years old.\n", age);
printf("I have walked %.2f kilometers today.\n", kilometers_walked);
printf("My favorite letter is %c. Its ASCII code is %d\n", favorite_letter, favorite_letter);
return 0;
}
Note: You'll notice two things here.
- First, we use the format specifier
%cto display a character. - Then when we use
%dwith ourchar, it converts the character to its corresponding ASCII code. Pretty cool, right?
Remember our familiar steps:gcc premier_programme.c -o mon_programme
./mon_programme
So! You now know the basics of storing characters in programming. Who would have thought that behind each letter there was a little digital secret? 🤫🔡
IV. Quick overview of scanf and printf
When we program, especially as beginners, we often need to see what our code is doing. It's there that printf intervenes. And sometimes we want our program to be able to receive information live, that is, while it is running. For this, we have scanf.
1. printf: Talk to user Function printf allows us to display information on the screen. It's like yelling at someone across the room. With it, you can display texts, variables and even calculations.
2. scanf: Listen to the user scanf is the opposite of printf. Rather than sending a message, he waits patiently to be spoken to. Using scanf, you can ask the user to provide you with information, such as their age or name.
3. The reality of embedded systems Now, before you jump for joy, I have something to tell you about printf et scanf. In the world of embedded systems, these two functions are not always used directly. For what ? Because embedded systems often have limited resources and operate differently from traditional PCs.
In embedded systems, there is often no screen to display messages or keyboard to enter data. Instead, they interact with the environment in specific ways (for example, using sensors or light indicators). Additionally, functions like printf can be resource-intensive, which can be problematic for devices that need to operate efficiently.
That said, to understand printf et scanf is an essential step for beginners. This gives you the power to interact with your program and understand what's happening internally. And once you master these concepts, moving on to more embedded system-specific mechanisms will be a breeze!
Little thought: Although we don't use them directly in-vehicle, these functions give us a solid foundation. It's like learning to walk before you run. You might think, “Why should I learn to walk if I want to run?” But without this fundamental step, running would be much more difficult. And the same goes for programming. Get to grips with the basics, and everything else will follow naturally.
Come on, let's keep exploring! Data types are fascinating, aren't they? 🧐🚀
V. Small practical example with VS Code 🛠️
1. Launch VS Code
If you haven't already, open VS Code.
2. Create a new file
Click the “New File” icon at the top left or use the shortcut Ctrl+N. Name it “interaction.c” when saving it.
3. Let's start coding!
Type or copy the following code:
#include <stdio.h>
int main() {
int age;
char firstname[30]; // An array to store the user's first name
printf("Hello! What is your name?\n"); // Corrected newline character
scanf("%s", firstname);
printf("Pleased to meet you, %s! How old are you?\n", first name); // Corrected newline character
scanf("%d", &age);
printf("Wow, %s! You are %d years old!\n", first name, age); // Corrected newline character
return 0;
}
4. Compilation and execution
Open the built-in terminal in VS Code (you can use the shortcut Ctrl + ~). Type the following command to compile your program:gcc interaction.c -o interactionThen, to execute it:./interaction
Follow the on-screen instructions, enter your first name and age when asked.
Some remarks on this example:
- Le
#include <stdio.h>at the beginning is essential. Without it you could not useprintfniscanf, because it is this header that contains their declarations. - When we use
scanfto retrieve a character string or a number, we use “format markers” like%sfor a string or%dfor an integer. These markers indicatescanfwhat type of data it should expect. - You may have noticed the little
&before “age” inscanf. This is the “address of” operator, and it is necessary here becausescanfneeds the address of the variable to store the value entered by the user.
I hope this example helps you better understand how printf et scanf and how to use them to interact with the user. In the world of programming, it is always useful to be able to obtain information from the user and provide it in return. Now imagine everything you could do with these new skills! 🚀🌌
VI. Scope of Variables: The Magical Domain of Variables 🌌🔮
Ah, the scope of variables! It is a fundamental concept, but also a source of mystery for many beginners. So, sit back, because we're going to demystify this.
What is the scope of a variable?
Imagine you own a castle (yes, a castle! 🏰). Inside this castle, you have different rooms: a throne room, a library, a secret room... Each room contains objects specific to that room.
In the world of programming, your program is that castle. “Parts” are functions or blocks of code, and “objects” are variables. The scope of a variable determines in which “room(s)” this variable is accessible, or visible.
Local Variables: Hidden Treasures 🏺
A local variable is like a treasure hidden in a specific room of your castle. You can use it and see it only if you are in this room.
In code terms, this means that a variable declared inside a function or block is accessible only inside that function or block.
#include <stdio.h>
int main() {
int myTreasure = 5; // This variable is local to the main function / This variable is local to the main function
printf("My treasure is worth: %d gold coins!\n", myTreasure);
return 0;
}
Here, monTresor is a local variable to the function main. You will not be able to use it outside of this function.
Global Variables: The Jewels of the Castle 🌍💎
Conversely, a global variable is like a precious jewel placed in the great hall of your castle. No matter what room you are in, you can see and use this gem.
In code, a global variable is declared outside of all functions, usually at the top of the file, and it is accessible anywhere in the program.
#include <stdio.h>
int castleJewel = 10; // This is a global variable / Ce est un variable global
int main() {
printf("The jewel is worth: %d diamonds!\n", castleJewel);
return 0;
}
Here, castleJewel is a global variable. It could be used in any function in this file.
Why is this so important?
Properly managing variable scope is essential to avoid bugs and make code more readable and organized. If you have a good understanding of where and how a variable can be used, you will have a much better handle on the flow of your program.
Remember: with great power comes great responsibility. Global variables, while useful, can make code more complex if used indiscriminately. Always try to limit their use.
And there you have it, dear apprentice code sorcerers! You have just unlocked the mystery of variables and their scope. Ready for more magical adventures? 🌠🔮📜
VII. Good Naming Practices: The Art of Naming Your Variables 🎨📜
If I told you “Go get the thing in the thing!” or “Hand me the thing!”, you would certainly be perplexed. Likewise, in programming, giving vague or imprecise names to our variables can create great confusion.
Naming your variables is like the first impression you make when you meet someone. You want to be clear, precise and, above all, memorable (in a good way!). So how to name your variables like a pro? Let's see that.
1. Clarity above all! 🔍
The name of a variable should indicate its function or usefulness. Think of it as a hint to yourself, or to someone else who might read your code in the future.
Bad example:int a = 5;Good example:int ageDuChien = 5;
In the good example, we immediately understand what this variable is for.
2. Avoid names that are too short or too long 📏
Too short, and the name risks being vague. Too long, and it becomes tedious to type and read.
Bad examples:Good example:
int x = 10;
int nombreDeJoursDepuisLeDebutDeLAnnee = 250;int joursEcoules = 250;
3. Use camelCase notation 🐫
The camelCase notation starts with a lowercase letter and capitalizes each following word. This is common practice in C.
Examples:int nombreDePommes;
float prixParArticle;
char lettreInitiale;
4. Be consistent! 🔄
If you start naming your variables a certain way, stick to that convention throughout your project.
5. Feel free to use comments 💬
If a variable name requires further clarification, add a brief comment next to it.
Examples:int p; // p représente la pression en Pascal
6. Avoid mysterious acronyms and abbreviations 🤐
Unless it is a widely recognized abbreviation, avoid abbreviating words. temp could mean “temperature” or “temporary,” which could cause confusion.
Why is this so crucial?
Good naming helps make code readable and understandable. You'll save time debugging, make collaboration easier, and most importantly, you'll be doing a favor for your future self (or other programmers) who revisit your code.
Think of it like writing a book. A book with memorable and relevant character names is always more enjoyable to read. The same goes for code! ✨📖✨
VIII. Summary and Practical Exercises: Put your Knowledge to the Test! 📚✍️
Congratulations! You have just navigated through the fascinating world of variables in C. Before diving into our exercises, let's take a moment to take a little memory trip.
(I.e. Summary:
- The variables are like mystery pockets, where we store our precious data for use later. It is crucial to declare and initialize our variables. Each variable has a type, which determines the nature and size of the information it can contain.
We explored several variable types:
intfor integers.floatetdoublefor floating point numbers.charfor the characters.
- scanf et printf are our tools for interacting with the user, although they are not always used in embedded programming.
- We also discussed the importance of scope of variables and good naming practices to make our code clear and professional.
🎯 Practical exercises:
- It's game time! 🎮
Create a little game where the user has to guess your age. Store your age in a variable and use
scanfto get a response from the user. Inform him if he is right or if he is far from the truth. - Currency Conversion (I.e.
Imagine that you have an amount in euros and you want to convert it into dollars. Create a program that asks the user to enter an amount in euros, then convert it to dollars using a conversion rate stored in a variable. Show the result.
- initials (I.e.
Ask the user to enter their first and last name. Then display his initials. (Tip: Use variable type
charto store initials.) - BMI calculator (I.e.
Body mass index (BMI) is a way to determine if someone is a healthy weight for their height. Ask the user their height (in meters) and weight (in kg), then calculate their BMI using the formula:
IMC = poids / (taille * taille). Show the result.
Remember, programming is like building a muscle. The more you practice, the stronger you become. So, put your knowledge to the test and have fun! 🌟🛠️🌟