Professional Documents
Culture Documents
Introduction to C
ICS Dept
KFUPM
1
Objectives
◼ To introduce the basics of imperative
programming using the C programming
language.
◼ To prepare you for basic imperative
programming.
◼ To prepare you for better understanding of
the other parts of the course.
2
Overview
◼ C versus Java
◼ Basic types in C
◼ Some simple programs
◼ Format specifiers
◼ More example programs
3
C versus Java
◼ Java is object-oriented, C is procedure-oriented
◼ Java classes help control name space, C has a single
name space
◼ Java has complex layered I/O, C has simple byte-
stream I/O
◼ Java has automatic memory management, with C you
do your own
◼ Java has no explicit pointers, C uses pointers (almost)
everywhere
◼ Java Strings are well-defined objects, C strings are
char[]
4
C Programs: General Form
preprocessor directives
int main(){
variable declarations;
statements;
}
Example:
#include <stdio.h>
int main(){
int x = 1;
printf(“Salaam Shabab\n”);
printf(“This is program %d\n”, x);
return 0;
}
5
Basic Data Types (some)
• int
• char
• double
• short
• Basic pointer types (associated with each basic
type)
6
Boolean Type
There is no bool keyword in C.
◼ Booleans in C are the same as integers
with a value of 0 for false or 1 for true.
char %c
int %d
float %f
double %lf
String %s
8
Format Specifiers (some)
#include <stdio.h>
int main(){ Your values are:
char c = 's';
A char: s
int i = 3;
float f = 3; A char: 115
char *s = "ICS 410"; An int: 3
A float: 3.000000
printf("Your values are:\n");
printf("A char: %c\n", c); A string: ICS 410
printf("A char: %d\n", c); Mixed: 0.000000 1074266112 s
printf("An int: %d\n", i);
printf("A float: %f\n", f);
printf("A string: %s\n", s);
printf("Mixed: %f\t%d\t%c\n", i,f,c);
return 0;
} 9
Operators
• Operators same as Java:
• Arithmetic
• int i = i+1; i++; i--; i *= 2;
• +, -, *, /, %,
• Relational and Logical
• <, >, <=, >=, ==, !=
• &&, ||, &, |, !
• Syntax same as in Java:
• if ( ) { } else { }
• while ( ) { }
• do { } while ( );
• for(i=1; i <= 100; i++) { }
• switch ( ) {case 1: … }
10
• continue; break;
Example
#include <stdio.h>
#define DANGERLEVEL 5
int main()
{
float level=1;
if (level <= DANGERLEVEL)
printf(“Low on gas!\n”);
else printf(“Good driver !\n”);
return 0;
}
11
Part - II
12
Overview
◼ Introduction to pointers
◼ Arrays and pointers
◼ Strings in C
◼ Pointers as function parameters
13
Pointers in C: An Introduction
◼ All variables of non-primitive types in Java references.
◼ C has no concept of ‘reference’, but has pointers instead
◼ A pointer is an address in memory of some ordinary data
◼ There is a pointer type associated with every type
Example 1:
#include <stdio.h>
int main(){
int x = 1;
int *xp;
xp = &x;
printf(“x = %d\n”, x);
printf(“*xp = %d\n”, *xp);
return 0;
}
14
Pointers: A Pictorial View
float f;
float *fp;
f fp any float
? ? ?
4300 4304 any address
fp = &f;
f fp
? 4300
4300 4304
15
Pointers: A Pictorial View (cont’d)
*fp = 3.2; /* indirection operator */
f fp
3.2 4300
4300 4304
f = 1.3;
f fp
1.3 4300
4300 4304
16
Example 2:Dereferencing pointers
#include <stdio.h>
int main(){
int i=3, j=7, *ip;
ip = &i;
*ip = 5;
ip = &j;
*ip += 11;
i += *ip;
printf("i = %d\n", i);
printf("j = %d\n", j);
printf("*ip = %d\n", *ip);
return 0;
}
17
Arrays and pointers
◼ Arrays in C are not objects: no methods, no
‘length’ field
◼ The name of an array is a constant pointer
18
Example 4: Arrays and pointers
#include <stdio.h>
int main(){
int i, j, *ip, myArray[5] = {2,3,5,7,11};
ip = &myArray[2];
for(i= 0; i<5; i++)
printf("myArray[%d] = %d\n", i, *(myArray+i));
*(ip+1) = 4;
*(ip-1) += 11;
j = *(ip-2);
for(i=0; i<5; i++)
printf("myArray[%d] = %d\n", i, *(myArray+i));
printf("j = %d\n", j);
return 0;
}
19
Example 5: Dynamic Arrays
#include <stdio.h>
int main(){
int i, j, size, *ip, *myArray;
printf("Enter array size:");
scanf("%d", &size);
myArray = (int *)malloc(size*sizeof(int));
printf("Enter the %d elements (separated by space: ",size);
for(i=0;i<size; i++){
scanf("%d", myArray+i);
}
ip = &myArray[2];
*(ip+1) = 4;
*(ip-1) += 11;
j = *(ip-2);
for(i=0; i<5; i++)
printf("myArray[%d] = %d\n", i, *(myArray+i));
printf("j = %d\n", j);
return 0; 20
}
Example 6: File I/O
#include <stdio.h>
int main(){
int i,n,hours;
long id;
float rate, wage;
char name[50], n2[50];
FILE *inputFile, *outputFile;
inputFile = fopen("employeeData.txt","r");
outputFile = fopen("employeeWage.txt","w");
if (inputFile) printf("File read!\n");
printf("How many employees do you have>");
scanf("%d", &n);
for(i=0;i<n;i++){
fscanf(inputFile, "%ld%[^0-9]%d%f",
&id,name,&hours,&rate);
wage = hours*rate;
fprintf(outputFile, "%ld\t%d\tSR%5.2f\t\tSR%5.2f\n",
id,hours,rate,wage);
}
return 0;
}
21
Strings in C
• Java strings are objects of class java.lang.String or
java.lang.StringBuffer, and represent sequences of characters
• Strings in C are just arrays of, or pointers to, char
• Functions that handle strings typically assume that strings are
terminated with a null character ‘\0’, rather than being passed a
length parameter
• Utilities for handling character strings are declared in <string.h>.
• For example:
• strcpy, strncpy, strcmp, strncmp, strcat, strncat, strstr,strchr
22
Example 7: Strings in C
#include <stdio.h>
int main(){
char name[] = {'i', 'c', 's', '3', '1', '3', '\0'};
char *dept = "ICS, KFUPM";
int i = 0;
printf("Course name = %s\n", name);
return 0;
23
}
Example 8: Strings Processing
#include <stdio.h>
#include <string.h>
int main() {
char first[80], second[80];
printf("Enter a string: ");
gets(first);
strcpy(second, first);
printf("first: %s, and second: %s\n", first, second);
if (strcmp(first, second) == 0)
puts("The two strings are equal");
else
puts("The two strings are not equal");
return 0;
} 24
Pointers and Functions
• What is the parameter passing method in Java?
25
References
◼ C does not have references or reference parameters.
◼ All arguments to C's free functions are passed by
value. To achieve the effect of call by reference,
pointers are used.
void swap(int x, int y) { void swap(int *x, int *y) {
int t ; int t ;
t=x;x=y;y=t; t = *x ; *x = *y ;
*y = t ;
} }
... ...
swap(a, b) ; swap(&a, &b) ;
26
Example 9:Pass By Value
#include <stdio.h>
int sum(int a, int b);
/* function prototype at start of file */
int main(){
int a=4,b=5;
int total = sum(a,b);
printf("The sum of 4 and 5 is %d\n", total);
}
int sum(int a, int b){ /* function definition */
return (a+b);
}
27
Example 10: Pass By Reference
#include <stdio.h>
int sum(int *pa, int *pb);
int main(void){
int a=4, b=5;
int *ptr = &b;
int total = sum(&a,ptr);
int main() {
int num1 = 5, num2 = 10;
swap(num1, num2);
printf("num1 = %d and num2 = %d\n", num1, num2);
}
void swap(int n1, int n2) { /* passed by value */
int temp;
temp = n1;
n1 = n2;
n2 = temp;
31
Overview
◼ Storage classes
◼ Structures
structtypes
union types
enum types
Type aliasing via typedef
32
Storage Classes: An Introduction
◼ For any variable declared in a program (e.g., int x =
11;), the compiler is told the following information about
the variable: its
type (preceded by an optional qualifier, e.g., int x;)
name
cell size (with an implicit address)
storage class
◼ A storage class affects the scope and life span of a
variable.
◼ A variable can either have an extern, an auto, a
register or a static storage class.
33
Storage Classes: An Introduction
◼ register and auto variables have a temporary, local
scope.
◼ auto is the default storage class for local variables.
auto can only be used within functions, i.e. local
variables.
◼ register is used to define local variables that should
be stored in a register instead of RAM.
◼ This means that the variable has a maximum size
equal to the register size (usually one word) and
can’t have the unary `&' operator applied to it (as it
does not have a memory location).
◼ register should only be used for variables that
require quick access - such as counters.
34
Storage Classes: An Introduction
◼ A local static variable has a permanent, local scope
◼ A global static variable has a permanent, file scope
◼ static can also be defined within a function. If this is
done, the variable is initialized at compilation time and
retains its value between calls.
◼ Because it is initialized at compilation time, the
initialization value must be a constant.
◼ A global extern has a permanent, global scope.
◼ extern refers to a global variable that is visible to ALL
object modules.
◼ An extern variable should not be initialized because all
extern does is point the variable name at a storage
location that has been previously defined.
35
Example 1: Storage Classes
#include <stdio.h>
int x = 71; /* Almost equivalently, static int x =
71; */
void func1(void) {
extern int x; /* Should not initialise! */
printf("In func1(), x = %d\n", x);
}
int main() {
int x = 23; /* Equivalently, auto int x = 23; */
printf("In main(), x = %d\n", x);
func1();
return 0; } 36
Example 2: Storage Classes
#include <stdio.h>
void func1(void); /* function declaration */
static count=10; /* Global static variable */
main() {
while (count--) func1();
}
void func1(void) {
/* 'x' is static and local to 'func1'. Its value
* is NOT reset on every invocation of
* 'func1' */
static int x=5;
x++;
printf(" x is %d and count is %d\n", x, count);
}
37
Example 3: Storage Classes
#include <stdio.h>
char *f(void);
int main() {
char *result;
result = f();
printf("%s",result);
return 0;
}
char *f(void) {
char name[13]="Amr Ali";
return(name);
}
38
Structures: Motivations
• Our programs so far used only the basic data types
provided by C, i.e., char, int, float, void and pointers.
• Programmers can define their own data types using
structures
• Structures can be used to conveniently model things
that would otherwise be difficult to model using arrays
• different structures (in the same program) can have the
same component name. A structure component name
can also be the same as an ordinary variable name
39
Structures: Motivations
• Arrays versus structures:
• arrays elements and structure components are
contiguously laid out in memory
• arrays are homogeneous, structures can be
heterogeneous
• arrays are passed to functions by reference
while structures have to be explicitly passed by
reference
• arrays (of the same type, of course!) cannot be
assigned to each other (why?) while structures
can
• array identifiers can be compared while
40
structure identifiers cannot
Creating Structures: the Tools
41
Creating Structures: Examples
enum Days {SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY};
struct date {
int day;
int month;
int year;
};
union mixed {
char c;
float num;
int age;
42
};
Example 4: Structures
struct date {
int day;
int month;
int year;
}
main() {
struct date today;
today.day = 17;
today.month = 11;
today.year = 1998;
46
Memory Allocation (2)
◼ Even more complicated structures like
arrays are allocated through malloc()
/* Here we're allocating space for 5 integers
*/
int *foo;
foo = (int *) malloc (sizeof(int) * 5);
foo[0] = 17;
foo[4] = 22;
47
Libraries
Libraries’ functions are included by specifying the name
of the
appropriate header file in an include statement:
#include <stdlib.h>
#include <string.h>
• Similar to C++ but the .h is required.
• Some of the most useful C libraries:
• stdio : printf, fprintf, sprintf, fgets, fputs
• string : strcpy, strcmp, strncmp, strtok, strlen
• stdlib : utility functions: atoi, atol,
• assert : useful in debugging: assert 48