C Programming Tutorial Part 5 - Character variables

In the previous two tutorials, we discussed the basics of variables including how they occupy memory. But we mainly focused on integers and floats. In this tutorial, we will discuss about characters (or char type variables).

Variables of 'char' type occupy 1 byte (or 8 bits) in the memory.  As I mentioned earlier in case of 'int' and 'float,' you can check the amount of memory a character occupies on your system using the following C program:

#include <stdio.h>

int main (void)
{
printf("\n sizeof char in bytes is %u", sizeof(char));

return 0;
}

On my system, the following was the output:

 sizeof char in bytes is 1                                                                                               

Now comes the question of how to accept characters as input from user and how to print them in output. Well, for accepting characters in input, there's a dedicated function named 'getchar'. Similarly, to print individual characters, you have 'putchar'. The following piece of code should give you a better idea on how these functions work:

#include <stdio.h>

int main (void)
{
int c;
c = getchar();
putchar(c);

return 0;
}

The code above, when executed, first waits for user to input a character. After that, it simply outputs the same character on terminal.

It could be a bit surprising for you that the value 'getchar' returns is stored in an integer, but that's how it is (the function returns an int). But you can always compare the value returned by 'getchar' with a character. Here's an example:

#include <stdio.h>

int main (void)
{
int c;
c = getchar();
if(c == 'a')
{
printf("matched");
}
else
{
printf ("doesn't match");
}
return 0;
}

So here, if the user inputs 'a', then the program prints 'matched' in output. Else, you get to see 'doesn't match'. 

Oh, and yes, this is the first time we've used 'if' and 'else' statements. As you'd have understood by now, 'if' lets you execute a set of statements if a condition is true. When the 'if' condition fails, code execution automatically enters 'else' block. Note that you can use an 'if' statement without and 'else' statement, but vice versa is not valid.

Now, coming back to getchar and putchar, let's quickly discuss how these functions can be used to solve real life problems. Let's say you wanna count the number of lines a user provided as input to your program, then you can do that in the following way:

#include <stdio.h>

int main (void)
{
int c =0, counter=0;
c = getchar();
while(c != EOF)
{
c = getchar();
if(c == '\n')
counter = counter+1;
}
printf("\n The input contains %d lines \n", counter+1);
return 0;
}

To understand the above program, you must first know what EOF is. Well, EOF stands for End Of File. It's used to signify that user has done with entering input.

So when you, as a user providing input, are done with the process, you press ctrl+d (a couple of times). It's this action that produces a value equivalent to that of EOF, which can be checked in the program - just like we did.

Coming back to the program, you first check the first character of input to see if it's EOF. If it's not, you enter the while loop and continuously check each character until you get an EOF. During this whole process, whenever you get a newline character (\n), you increase the 'counter' variable.

After and EOF is detected, the while loop is terminated and we print the number of lines, which one more than the value of counter. 

The reason we add one to 'counter' in the 'printf' function is, the number of lines is always one more than the number of newline characters (or in layman terms, the number of times user pressed the 'Enter' key). Of course, this is assuming whenever user presses enter, they enter some text as well.

So if you give this program an input like the following:

Hello 
Welcome to HowtoForge
Thanks  

 The output would be:

The input contains 3 lines

Note that our code assumes user will provide at least one line. Couple of corner cases aren't handle intentionally to keep things simple. One is when the user provides EOF without providing any other character in input, and the other is when a line has been provided without providing a newline character. 

Calculating number of lines is just one example. You can also extend this code to calculate total number of words entered by the user. Consider this as an assignment and try to code it yourself. As a hint, I'd say consider spaces (' ') and tabs ('\t'), similar to the way we considered newlines ('\n') to calculate number of lines.

Conclusion

In this tutorial, we discussed a bit more on characters, including how to use them, accept them as input and print them in output. We also discussed an example where the getchar function helped us calculate number of lines in input. Do try out the assignment I gave in the last paragraph and let me know if you have any doubt or query.

Share this page:

0 Comment(s)