Simple thing but important thing we should know in C programming
Simple things but important things we should know in C programming
We will discuss: the usage of tab key and spaces in C
First look at these examples:
![]() |
Example 1 |
![]() |
Example 2 |
You can see here, I got two outputs using tab and spaces. In the first example, I used spaces. Second example I used tabs.1st example C code is much more complex than 2nd example code. why?
The reason for that is when I use spaces, I have to count the spaces to get the right answer. but in the second example no need to do that to get the right answer.
Now, understand what is the difference:
First example:
for(k=1; k<=n-i; k++){
printf(" "); // 4 spaces
}
Now, check out how many spaces will be put on the output by for loop :
Row 1;
If n=7, i=1 then n-i=7-1=6. so, this loop will run 6 times. then all the spaces it will put in the output = 6 * 4= 24 spaces. So, what happened is that right? yes. it is right.
Row 6;
If n=7, i=6 then n-i=1. so, the above loop will run only one time. then all spaces it will put in the output = 1 * 4=4 spaces. it works nicely.
for(j=1; j<=i; j++){
if (multi<=8){
printf("%d ",multi); // 3 spaces
}else{
printf("%d ",multi); // 2 spaces
}
Using spaces to get the same output we have to include these conditions also. what does this condition do? it checks whether the number is greater than 8 or not (here you can put any one single number ex: ...-1, 0, 1, .. 7, 8, 9) it is going to print. if it is greater than 8 it means it will put only 2 spaces otherwise it puts 3 spaces. now you can see in this way we have to think about spaces.
Second example:
In this case, we do not need to count spaces. because tab spaces automatically change.so, try to use the tab key to put spaces in C programming.
Summary:
I explained about the usage of the tab key and spaces in C. So, what is the best to use? Actually, it depends on the situation. But if we can use the tab key that can make an easy way for us.no need to count spaces. Remember in this code you can put any positive number as an input but if you input a number greater than 7 this output is not beautiful it will break the pattern. because of these conditions working for two numbers outputs( ex: 1, 2, 4, 8, 16, 32, 64).So, if you want to input 8 or a big number as an input you have to implement this code.
Resources:
https://c8.alamy.com/comp/F2HYA9/c-programming-showing-software-design-and-programmer-F2HYA9.jpg
Comments
Post a Comment