1 First C Program 1
1 First C Program 1
Why learn C ?
• "Least common denominator" - good building block
for learning other languages
– Subset of C++
– Similar to JAVA
• Closeness to machine allows one to learn about
system-level details
• Portable - compilers available for most platforms
• Very fast
The first C program
#include <stdio.h>
void main ()
{
printf ("Hello, World! \n") ;
}
y = 3;
sum = x + y; /* adds x to y, places
value in variable sum */
printf( “%d plus %d is %d\n”, x, y, sum );
}
Comments
• Any string of symbols placed between the
delimiters /* and */.
• Can span multiple lines
• Can’not be nested! Be careful.
• /* /* /* Hi */ is an example of a comment.
• /* Hi */ */ is going to generate a parse error
Keywords
Reserved words that cannot be used as variable
names
OK within comments . . .
Examples: break, if, else, do, for, while, int, void
Exhaustive list in any C book
Identifiers
• A token (word) composed of a sequence of letters,
digits, and underscore (_) character. (NO spaces.)
– First character cannot be a digit
– C is case sensitive, so beware (e.g. printf
Printf)
• Identifiers such as printf normally would not be
redefined; be careful
• Used to give names to variables, functions, etc.
• Only the first 31 characters matter
Constants
• 0, 77, 3.14 examples.
• Strings: double quotes. “Hello”
• Characters: single quotes. ‘a’ , ‘z’
• Have types implicitly associated with them
• 1234567890999 too large for most machines
Simple Data Types
void
Integer types (signed or unsigned): char,
short int, int, long int
char is an 8 bit (=1 byte) number
Floating-point types: float, double, long
double
Char type
9
Input and Output
• printf : performs output to the standard output
device (typically defined to be the monitor)
– It requires a format string to which we can provide
• The text to print out
• Specifications on how to print the values
printf ("The number is %d.\n", num) ;
The format specification %d causes the value listed after
the format string to be embedded in the output as a
decimal number in place of %d.
Input
• scanf : performs input from the standard input
device, which is the keyboard by default.
– It requires a format string and a list of variables
into which the value received from the input
device will be stored.
• scanf ("%d", &size) ;
• scanf ("%c", &choice) ;
• scanf ("%f", &length) ;
Variables
• Variables hold the values upon which a program acts.
• The following declares a variable that will contain an
integer value.
int num_of_students ;