This post will contain a series of simple C programming tutorials and examples. I think this will be helpful to the first years since they're on to this. For discussions on this post, kindly visit the
forum.
Print text on screen
#include<stdio.h>
#include<conio.h>
main(){
printf("Hello World!\n");
getch();
return 0;
}
You might be wondering why the
conio.h header file was included when our main goal was just to print some text on our screen. Well, let's try dissecting our code line by line.
printf("Hello World!\n");
This line is obviously what we want our program to do. The
printf() function uses the
stdio.h header file/library, now why would we need the
conio.h header file?
getch();
This little function makes us see our output. Why? When we run a program, it will automatically exit if we don't include the
getch() function. The
getch() takes a character without
printing it to the screen. Once a character is entered, only then will it exit by going to line 7. Therefore,
getch() will stop our program from exiting until it receives a character.
And the
getch() function fortunately uses the
conio.h header file.
If you try removing the
getch() from your program, you'll notice that once you run the program, it will exit automatically.
Well, that's basically how we output text on the screen using C.
Stay tune for more updates!
Next: Accepting input!
Accepting Input
To accept input from the keyboard, we use the
scanf() function which uses
stdio.h header.
Take a look at the example program:
#include<stdio.h>
#include<conio.h>
int main(){
char word[]; //variable to hold the input, array of chars
printf("Enter a word: ");
scanf("%s", &word); //stores the input to the 'word' variable
printf("You have entered: %s", word);
getch();
return 0;
}