Why Use C?
C is a very powerful, all-purpose programming language, one of the oldest and most widely used, developed in the 1970s and still used to create operating systems and sophisticated programs. C was initially used for system development because it produces code that runs nearly as fast as assembly language; its modern versions are Objective-C and C++. Uses include operating systems, language compilers, assemblers, text editors, print spoolers, network drivers, databases and language interpreters.
Software Needed for a C Program
C code needs to be compiled by an Integrated Development Environment (IDE), made up of a text editor and compiler: for Windows, Dev C++, tuoC or CodeBlocks; for Mac, XCode; for Linux, gcc.
Basic C Code
#include <stdio.h>
int main()
{
/*my first program in C */
printf("Hello, World! \n");
system("PAUSE");
return 0;
}
#include <stdio.h>is a preprocessor command that loads the library needed for functions like printf() and system().int main()tells the compiler this is the “main” function that all C programs run, returning an integer when finished.- Braces
{ }mark everything that belongs to the function. /* ... */marks a comment, ignored by the compiler.printf()displays its contents on the user’s screen;\nmoves the cursor to a new line.- A semicolon
;denotes the end of a line/statement. system("pause")orgetchar()waits for a keystroke before closing the window.return()indicates the end of the function.
Using Variables
Variables store data from computations or user input, and must be declared before use with a data type followed by a name, e.g. float x; char name; int a, b, c, d;. Variables of the same type can be declared on one line, separated by commas, and must be declared at the start of each code block.
C Input and Output
The inbuilt functions scanf and printf are used for input and output. scanf("%d", &x); reads keyboard input into variable x (%d for integer, %f for float, %c for character, %s for a string), and the & tells scanf where to find the variable to change. printf("Integer value %d", x); displays text and values on screen, where %d/%f/%c are replaced by the arguments that follow.
Example: a program that asks for a number, reads it, and prints it back:
#include <stdio.h>
int main()
{
int x;
printf("Enter a number: ");
scanf("%d", &x);
printf("You entered %d", x);
system("PAUSE");
return 0;
}