Week 1
Week 1
Week 1
Basic – week 1
Array, String, Pointer, and File
1
Course Evaluation
§ Attendance + exercises: 30%
Introduction
• C Programming practice in UNIX
environment.
• Programming topics related to [Data
Structures and Algorithms]
• Compiler: gcc
• Editor: Emacs, K-Developper.
2
gcc syntax
• Parameter:
-Wall : turn on all alerts
-c: make object file
-o: name of output file
-g: debug information
-l: library
gcc hello.c –o runhello
./runhello
3
Array
• A block of many variables of the same
type
• Array can be declared for any type
– E.g. int A[10] is an array of 10 integers.
• Examples:
– list of students’ marks
– series of numbers entered by user
– vectors
– matrices
Arrays in Memory
• Sequence of variables of specified type
• The array variable itself holds the
address in memory of beginning of
sequence
• Example:
double S[10]; … 0 1 2 3 4 5 6 7 8 9 …
4
Example - reverse
#include <stdio.h>
int main(void)
{
int i, A[10];
return 0;
}
Exercise 1.1
• Write a program that gets an input line
from the user (ends with ‘\n’) and displays
the number of times each letter appears in
it.
The output for the input line: “hello, world!”
10
5
Exercise 1.2
• Implement a function that accepts
two integer arrays and returns 1 if
they are equal, 0 otherwise
• Write a program that accepts two
arrays of integers from the user and
checks for equality
11
Strings
• An array of characters
• Used to store text
• Another way to initialize:
char str[] = ”Hello world";
…. 's'
'H' '#'
'e' ''l'' 'f'
'l' 'd'
'o' 'y'
'' '4'
'w' '7'
'o' '$'
'r' '_'
'l' 'e'
'd' 'g'
'\0' 'd' '.' 'p' 'v' ….
str
Terminator
12
6
String
• In order to hold a string of N
characters we need an array of
length N + 1
• So the previous initialization is
equivalent to
char str[] = {‘H', ‘e', ‘l', ‘l', ‘o', ‘ ',
‘w', ‘o', ‘r‘, ‘l‘, ‘d‘, '\0'};
13
14
7
String and character related
function
– strlen(const char s[])
returns the length of s
– strcmp(const char s1[],
const char s2[])
compares s1 with s2
– strcpy(char s1[],
const char s2[])
copies to contents of s2 to s1
15
Exercise 1.3
• write a function that:
– gets a string and two chars
– the functions scans the string and replaces
every occurrence of the first char with the
second one.
• write a program to test the above function
– the program should read a string from the
user (no spaces) and two characters, then call
the function with the input, and print the
result.
• example
– input: “papa”, ‘p’, ‘m’
– output: “mama”
16
8
Pointer - Declaration
type *variable_name;
17
Pointers
– Here ptr is said to point to the address
of variable c
C
… 7 3 4 …
172 173 174 175 176 177 178 179 180 181
Ptr
… 174 3 4 …
832 833 834 835 836 837 838 839 840 841
18
9
Referencing and
Dereferencing
int n;
int *iptr; /* Declare P as a pointer to int */
n = 7;
iptr = &n;
19
Exercises 1.4
Write a function that accepts a double
parameter and returns its integer
and fraction parts.
20
10
Swap two integers
void swap(int *a, int *b){
int tg;
tg=*a; *a=*b;*b=tg;
}
main(){
int a =3, b=4;
swap(&a,&b);
printf("%3d%3d",a,b);
}
21
Exercise 1.5
• Write a function with the prototype:
void replace_char(char *str,
char c1,
char c2);
• It replaces each appearance of c1 by
c2 in the string str.
Do not use the [] operator!
• Demonstrate your function with a
program that uses it
22
11
Command line arguments
• Command line arguments are
arguments for the main function
– Recall that main is basically a function
– It can receive arguments like other
functions
– The ‘calling function’ in this case is the
operating system, or another program
23
‘main’ prototype
int main(int argc, char* argv[])
12
‘main’ prototype
int main(int argc, char* argv[])
command : ./test.out text 178
argc : 3
argv :
p t 1
r e 7
o x 8
g t \0
n \0
a
m
e
\0
25
Exercise 1.6
• Write a program that accepts two
numbers as command line
arguments, representing a
rectangle’s height and width (as
floating-point numbers).
• The program should display the
rectangle’s area and perimeter
26
13
File Handling
• C communicates with files using a
new datatype called a file pointer.
• File pointer:
– references a disk file.
– used by a stream to conduct the operation
of the I/O functions.
• FILE *fptr;
27
4 major operations
• Open the file
28
14
Opening a file
• fopen() function.
• FILE *fopen(const char *filename, const
char *mode);
FILE *fptr;
if ((fptr = fopen("test.txt", "r")) ==
NULL){
printf("Cannot open test.txt file.\n");
exit(1);
}
29
Opening a file
• filename: name of the file.
– It can be a string literal: “data.txt”
– It may contain the full path of the file:
“/root/hedspi/CProgrammingBasic/Lab1/dat
a.txt”
– It may be a character array that contains the file name:
char file_name[] = “junk.txt”;
30
15
Mode for text file
mode Description
31
32
16
Closing a file
• The fclose command can be used to
disconnect a file pointer from a file.
33
34
17
Reading and Writing Disk
Files
• In C, you can perform I/O operations in
the following ways:
– Read or write one character at a time.
35
36
18
Exercise 1.7
• Create a text file name lab1.txt with
the content as you want.
• Write a program to read from a text
file one character at a time, then
write it to a new file with the name
lab1w.txt
37
Exercise 1.8
• Write a program to read sentences from a
specified file one character at a time.
• Each capital letter is converted into a
lower-case letter, and each lower-case
letter is converted into a capital letter. The
new sentence is then written into another
file.
• Note that you must output numbers, the
signs as they are.
38
19
Read or write one line at a
time.
• Two functions: fgets() and fputs()
• char *fgets(char *s, int n, FILE *stream);
– s references an array that is used to store
characters
– n specifies the maximum number of array
elements.
• fgets() function can read up to n-1
characters, and can append a null
character after the last character fetched,
until a newline or an EOF is encountered.
39
40
20
Exercise 1.9
• Redo the exercise 1.7 but the
program will read and write one
character line at a time.
41
42
21
Exercise 1.10
Write a program to read two or more lines into an
array of character strings one by one from a
specified file and find the length of each line. You
must write the length of each line and character
string in the file.
43
Exercise 1.11
• Write a program to read a text file created with
emacs. Put a line number to the head of the line
and output the contents of the file to the
standard output. A text file name can be specified
as the argument to the program.
44
22
Execrise 1.12
• Write a program that copy one text
file to another.
45
23