C Programming Basic - Week 1
C Programming Basic - Week 1
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;
}
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, 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;
\ }
Strings
• An array of characters
• Used to store text
• Another way to initialize:
char str[] = "Text";
…. 'H'
's' 'e'
'#' ''l'' 'f'
'l' 'o'
'd' 'y'
'' 'w'
'4' 'o'
'7' '$'
'r' '_'
'l' 'd'
'e' '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
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”
Solution
void replace(char str[], char replace_what,
char replace_with)
{
int i;
\
Solution
#define STRING_LEN 100
int main(void)
{
char str[STRING_LEN + 1];
char replace_what, replace_with, tmp;
Ptr
… 174 3 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
• 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;
}
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;
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);
}
}
…