Programming in "C"
Lecture II
CSC 105
Sorin Draghici
Wayne State University
Summary

The structure of a C program
Declarations
Simple data types and modifiers
printf and scanf

The structure of a C program

include directives
declarations
variables
functions
function definitions

Example 1

#include

void main( void )
{
printf("Hello world\n") ;
}

Example 2

#include
int x=1,y=2 ;

int max(int x, int y) ;
void main(void)
{
printf("max is %d\n", max(x,y));
}
int max(int x, int y)
{
if (x>y)
return( x ) ;
else
return( y ) ;
}

The function definition includes:
return type, name, parameters
body
declarations
instructions

Example:

int max(int x, int y)
{
if (x>y)
return( x ) ;
else
return( y ) ;
}

Declaration Vs. Definition

The definition of a variable has the following effects:
the name of the variable is made known to the compiler
the compiler reserves an appropriate amount of space for the variable
the variable can be initialized

Example:
int x ;
int y = 0 ;

The declaration of a variable has the following effect:
the compiler is informed that a variable with such name and type has been or will be defined somewhere else

Example:
extern int x ;

Data types

Data Types: range and space necessary for each type (example)
Data typeDescriptionSpace necessary for storing a value of this type (in bytes)
charcharacter (e.g. 'A', 3) 1
intinteger (e.g. 3, 127)2
floatfloating point number (e.g. 3.14)4
doubledouble precision floating point (e.g 3.14159265, 1,000,000,000)8


Modifiers

short
long
signed
unsigned

Example:
int x ;
long int y ;
unsigned int z ;

Why do we use modifiers?

Modifiers are used to specify the range of values for a variable
Example:
unsigned char x ;
range [0, 255]

signed char x;
range [-128, 127]

printf & scanf

These functions are used to communicate with the user
printf( format, variables_to_be_printed )
scanf( format, addresses_of_variables )
where format is a string describing how we want the values to be written or read

Example (scanf, printf)

int x = 10 ;
printf("The result is: %d\n", x ) ;

The program will produce:

The results is: 10

int x;
scanf("%d", &x ) ;

The program will read a value; this value will be interpreted as integer and stored in variable x.

Descriptors

%d integer
%c char
%f float
%lf double (long float)
%u unsigned

Escape sequences (special characters) - see also Table 3.1 pag. 61:

\n new line (return)
\t tab (several spaces)
\' single quote
\" double quote
\\ backslash

Summary

The structure of a C program
Declarations
Simple data types and modifiers
printf, scanf and descriptors

Reading

Chapter 3 (pag. 46 - 78)
Chapter 4 (pag. 79 - 117)