Introduction to C
C Program Structure
Preprocessor Directives
Global Declarations
Function Definitions
int main () {
• Program defined by: Local Declarations
1. global declarations Statements
2. function definitions }
• May contain preprocessor directives
• Always has one function named main, may contain others
Parts of a Program
#include <stdio.h> Preprocessor Directive
int x; Global Declaration
int main () {
int y; Local Declaration
Function printf("Enter x and y: ");
scanf(&x,&y); Statements
printf("Sum is %d\n",x+y);
}
Declarations
• Global
• visible throughout program
• Local
• visible within function
Comments
• Text between /* and */
• Used to “document” the code for the human reader
• Ignored by compiler (not part of program)
• Have to be careful
• comments may cover multiple lines
• ends as soon as */ encountered (so no internal comments -
/* An /* internal */ comment */)
Comment Example
#include <stdio.h>
/* This comment covers
* multiple lines
* in the program.
*/
int main () /* The main header */ {
/* No local declarations */
printf(“Too many comments\n”);
} /* end of main */
Identifier
• Names used for objects in C
• Rules for identifiers in C:
• first char alphabetic [a-z,A-Z] or underscore (_)
• has only alphabetic, digit, underscore chars
• cannot duplicate a reserved word
• case (upper/lower) matters
Reserved Words
• Identifiers that already have meaning in C
• Examples:
• include, main, printf, scanf, if, else, …
• more as we cover C language
Variables
• Named memory location
• Variables declared in global or local declaration sections
• Syntax: Type Name;
• Examples:
int sum;
float avg;
char dummy;
Variable Name
• Legal identifier
• Not a reserved word
• Must be unique:
• not used before
• variable names in functions (local declarations) considered
to be qualified by function name
• variable x in function main is different from x in function f1
Valid/Invalid Identifiers
• sum
• 7of9
• c4_5
• x-name
• A_NUMBER
• student age
• longnamewithmanychars
• 1234a
• TRUE
• int
• _split_name
• AXYZ&
• Can create multiple variables of the
same type in one statement:
Multiple
int x, y, z;
Variable
Declaratio is a shorthand for
int x;
ns int y;
int z;
- stylistically, the latter is often
preferable
Multiple
Declarati
on • Can provide one value for variables
Initializati initialized in one statement:
int x, y, z = 0;
on • Each variable declared and then
initialized with the value
Integer Types/Values
Type Bytes Bits Min Val Max Val
short int 2 16 -32768 32767
int 4 32 -2147483648 2147483647
long int 4 32 -2147483648 2147483647
• With a fixed number of bits, only a
certain number of possible patterns
• 16 bits, 65,536 possible patterns
Why • 32768 negative numbers
Limited? • 1 zero
• 32767 positive numbers
• Overflow: attempt to store a value too
large in a variable (40000 in short int)
Character Type
• Type name: char
• Possible values: keys that can be
typed at the keyboard
• Representation: each character
assigned a value (ASCII values), 8
bits
• A - binary number 65
• a - binary number 97
• b - binary number 98
• 2 - binary number 50
String Literals
• No string type (more later)
• Contained between double quote chars (“)
• Examples:
“” - null string
“A string”
“String with newline \n char in it”
“String with a double quote \” in it”
Constants
• Literal constants - tokens representing values from type
• Defined constants
• syntax: #define Name Value
• example: #define MAX_NUMBER 100
• Memory constants
• declared similar to variables, type
and name
• const added before declaration
• Example:
Constant
s (cont) const float PI = 3.14159;
• Can be used as a variable, but one
that cannot be changed
• Since the value cannot be changed,
it must be initialized
• Command: printf - print formatted
• Syntax: printf(Format String, Data List);
• Format string any legal string
Formatte • Characters sent (in order) to screen
• Ex.: printf(“Welcome to\nCS 1621!\n”);
d Output causes
Welcome to
CS 1621!
to appear on monitor
Field Specifications
• Format string may contain one or more field specifications
• Syntax: %[Flag][Width][Prec][Size]Code
• Codes:
• c - data printed as character
• d - data printed as integer
• f - data printed as floating-point value
• For each field specification, have one data value after
format string, separated by commas
printf(“%c %d %f\n”,’A’,35,4.5);
Field
Specificati produces
on A 35 4.50000
Example (varies on different computers)
Can have variables in place of literal
constants (value of variable printed)
• When printing numbers, generally use
width/precision to determine format
• Width: how many character spaces
Width to use in printing the field (minimum,
if more needed, more used)
and
Precision • Precision: for floating point
numbers, how many characters
appear after the decimal point,
• width counts decimal point, number
of digits after decimal, remainder
before decimal
printf(“%5d%8.3f\n”,753,4.1678);
produces
Width/
753 4.168
Precision values are right justified
Example If not enough characters in width,
minimum number used
Put - after % to indicate value is left justified
printf(“%-5d%-8.3fX\n”,753,4.1678);
Left produces
Justificati 753 4.168 X
on (Flags) For integers, put 0 after % to indicate should
pad with 0’s
printf(“%05d”,753);
produces
00753
• Command: scanf - scan formatted
• Syntax:
scanf(Format String, Address List);
• Format string a string with one or more
Formatte field specifications
• Characters read from keyboard, stored
d Input in variables
• scanf(“%c %d %f”,&cVar,&dVar,&fVar);
attempts to read first a single character,
then a whole number, then a floating
point number from the keyboard
• Generally only have field specifications
and spaces in string
• any other character must be
matched exactly (user must type
Formatte that char or chars)
• space characters indicate white-
d Input space is ignored
(cont) • “white-space” - spaces, tabs,
newlines
• %d and %f generally ignore leading
white space anyway (looking for
numbers)
• %d and %f read until next non-
number char reached
• & - address operator
Address • Put before a variable (as in &x)
• Tells the computer to store the value
Operator read at the location of the variable
• More on address operators later
scanf(“%d%c %f”,&x,&c,&y);
and following typed:
-543A
Scanf
Example 4.056 56
-543 stored in x, A stored in c, 4.056 stored
in y, space and 56 still waiting (for next
scanf)
• Using output statements to inform the
Promptin user what information is needed:
g for printf(“Enter an integer: “);
scanf(“%d”,&intToRead);
Input • Output statement provides a cue to the
user:
Enter an integer: user types here