Week 1
Week 1
com/file/59508971/2e6ced40
/week1.html
C Programming
Basic – week 1
For HEDSPI Project
Lecturers :
Cao Tuan Dung
Le Duc Trung
Dept of Software Engineering
Hanoi University of Technology
Introduction
• C Programming practice in UNIX
environment.
• Programming topics related to [Data
Structures and Algorithms]
• Compiler: gcc
• Editor: Emacs, K-Developper.
gcc syntax
• Parameter:
-Wall : turn on all alerts
-c: make object file
-o: name of output file
-g: debug information
-l: library
gcc –Wall hello.c –o runhello
./runhello
This week: Basic Data
Structures and Algorithms
• Topic:
– Array, String, Pointer Review
– Character based File operations in UNIX
– Programming Exercises
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 …
int main(void)
{
int i, A[10];
return 0;
}
Find the median element
• Continue the previous program by
displaying the median element of the
array.
• Median(A) ~ Average(A)
Exercise
• 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!”
int main(void)
{
int i = 0,
count[ALPHABET_LEN] = {0};
char c = '\0';
return 0;
}
Exercise (20 minutes)
• Implement a function that accepts
two integer arrays and returns 1 if
they are equal, -1 if they are
symetric, 0 otherwise
• Write a program that accepts two
arrays of integers from the user and
checks for equality
Solution
#include <stdio.h>
#define SIZE 5
return 0;
}
Home Exercise 1
• Redo the program which compares
two integer array that not use the
size parameter.
Strings
• An array of characters
• Used to store text
• Another way to initialize:
char str[] = "Text";
…. 's'
'H' '#'
'e' ''l'' 'f'
'l' 'd'
'o' 'y'
'' '4'
'w' '7'
'o' '$'
'r' '_'
'l' 'e'
'd' 'g'
'\0' 'd' '.' 'p' 'v' ….
str
Terminator
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[] = {'b', 'l', 'a', 'b', 'l',
'a', '\0'};
String and character related
function
• getchar()
– c = getchar()
• scanf
– scanf("%s", str);
• gets()
– gets(str);
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
– strcat(char s1[], char s2[])
concatenate to contents of s2 to s1, then store at s1
Exercise
• 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”
Homework K60
• Extend the function in previous
exercise by replacing two characters
by two string
• replace(“papa”, “pa”, “ba”) return
“baba”.
Solution
void replace(char str[], char replace_what,
char replace_with)
{
int i;
int main(void)
{
char str[STRING_LEN + 1];
char replace_what, replace_with, tmp;
Ptr
17
… 3 4 …
4
832 833 834 835 836 837 838 839 840 841
Referencing and
Dereferencing
int n;
int *iptr; /* Declare P as a pointer to int */
n = 7;
iptr = &n;
int main(void)
{
double num, fraction;
int integer;
return 0;
}
Exercise ICT54.2
• Write a program that uses random number generation to create
sentences. The program should use four arrays of
strings called article, noun, verb and preposition. The program
should create a sentence by selecting a word at random from each
array in the following order: article, noun, verb, preposition,
article and noun. As each word is picked, it should be
concatenated to the previous words in an array that is large
enough to hold the entire sentence. The words should be
separated by spaces. When the final sentence is output, it should
start with a capital letter and end with a period. The program
should generate 10 such sentences.
• The article array should contain the articles "the", "a", "one",
"some" and "any";
• the noun array should contain the nouns "boy", "girl", "dog",
"town" and "car";
• the verb array should contain the
verbs "drove", "jumped", "ran", "walked" and "skipped";
• the preposition array should contain the
prepositions "to", "from", "over", "under" and "on".
Exercise
• 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
Solution
void replace_char(char *str, char c1, char c2)
{
if (str == NULL)
return;
++str;
}
}
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
‘main’ prototype
int main(int argc, char* argv[])
argc :
3
argv
:
p t 1
r e 7
o x 8
g t 0\
n \0
a
m
e
\0
Exercise
• 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
Solution
int main(int argc, char* argv[])
{
double width, height;
if (argc != 3)
{
printf("Wrong number of arguments!\n");
return 1;
}
width = atof(argv[1]);
height = atof(argv[2]);
return 0;
}
Homework: WordReplication
• Write a command line program that
replicates a word for n time. For
example
• replicate go 7 →gogogogogogogo
Exercise: Sentence Inverter
• Write a program that take a
sentences as a sequence of word in
command line and print them in
inverse order.
Homework
• Write a command line program that
calculates ex with two optional
syntax:
• E 50
• Or
• E 50 0.0003
Home work
• Write a command line program that
solve the second degree equation ax2
+ bx +c =0 with the following
syntax: sde a b c
• Example sde 1 2 1 return: x1=x2 =-
1
Homework
• Improve exercise from week 1 that it
can take command line arguments.
• replace bachkhoahoabinh oa ii
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;
4 major operations
• Open the file
FILE *fptr;
if ((fptr = fopen("test.txt", "r")) ==
NULL){
printf("Cannot open test.txt file.\n");
exit(1);
}
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/da
ta.txt”
– It may be a character array that contains the file name:
char file_name[] = “junk.txt”;
main(void) {
FILE *fptr1, *fptr2;
char filename1[]= "lab1a.txt";
char filename2[]= "lab1.txt";
int reval = SUCCESS;
if (argc != 3) {
prn_info(argv[0]);
exit(1);
}
ifp = fopen(argv[1], "r"); /* open for reading */
ofp = fopen(argv[2], "w"); /* open for writing */
double_space(ifp, ofp);
fclose(ifp);
fclose(ofp);
return 0;
}
Solution for homework
void double_space(FILE *ifp, FILE *ofp)
{
int c;
main() /* FILE_COPY.C */
{
char in_name[25], out_name[25];
FILE *in_file, *out_file, *fopen ();
int c;
printf("File to be copied:\n");
scanf("%24s", in_name);
printf("Output filename:\n");
scanf("%24s", out_name);
…
if( in_file == NULL )
printf("Cannot open %s for reading.\n",
in_name);
else {
out_file = fopen (out_name, "w");
if( out_file == NULL )
printf("Can't open %s for
writing.\n",out_name);
else {
while( (c = getc( in_file)) != EOF )
putc (c, out_file);
putc (c, out_file); /* copy EOF */
printf("File has been copied.\n");
fclose (out_file);
}
fclose (in_file);
}
}
…