C Programming Basic - Week 1
C Programming Basic - Week 1
Lecturers : Cao Tuan Dung Le Duc Trung Dept of Software Engineering Hanoi University of Technology
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
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.
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];
S 0 1 2 3 4 5 6 7 8 9
Examples:
list of students marks series of numbers entered by user vectors matrices
Example - reverse
#include <stdio.h> int main(void) { int i, A[10]; printf("please enter 10 numbers:\n"); for(i=0; i<10; i++) scanf("%d", &A[i]); printf("numbers in reversed order:\n"); for(i=9; i>=0; i--) printf("%d\n", A[i]); 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! The letter 'd' appears 1 time(s). The letter 'e' appears 1 time(s). The letter 'h' appears 1 time(s). The letter 'l' appears 3 time(s). The letter 'o' appears 2 time(s). The letter 'r' appears 1 time(s). The letter 'w' appears 1 time(s).
Strings
An array of characters Used to store text Another way to initialize: char str[] = "Text";
. str 'H' 's' 'e' '#' ''l'' 'f' 'l' 'o' 'd' 'y' '' 'w' '4' 'o' '7' '$' 'r' '_' 'l' 'd' 'e' 'g' '\0' 'd' '.' 'p' 'v' .
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'};
scanf
scanf("%s", str);
gets()
gets(str);
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.
example
Pointer - Declaration
type *variable_name;
Pointers
Here ptr is said to point to the address of variable c
C
172 173
A pointer is declared by adding a * before the variable name. Pointer is a variable that contains an address in memory. The address should be the address of a variable or an array that we defined.
7
174
3
175
4
176 177 178 179 180 181
Ptr
832 833
174 3
834 835
4
836 837 838 839 840 841
Exercises 1.4
Write a function that accepts a double parameter and returns its integer and fraction parts. Write a program that accepts a number from the user and prints out its integer and fraction parts, using this function.
printf(%d, *iptr); /* Prints out 7*/ *iptr = 177; printf(%d, n); /* Prints out 177 */ iptr = 177; /* This is unadvisable!! */
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
main prototype
int main(int argc, char* argv[])
main prototype
int main(int argc, char* argv[]) argc : 3 argv :
p r o g n a m e \0 t e x t \0 1 7 8 \0
When we want main to accept command line arguments, we must define it like this
argc holds the number of arguments that were entered by the caller argv is an array of pointers to char an array of strings holding the text values of the arguments
Exercise 1.5
Write a program that accepts two numbers as command line arguments, representing a rectangles height and width (as floating-point numbers). The program should display the rectangles area and perimeter
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 Read from a file program file
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); }
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;
mode "r" "w" "a" "r+" "w+" "a+"
NOTE: If the file path is not specified, the file is located in the same folder as the C program.
Closing a file
The fclose command can be used to disconnect a file pointer from a file. int fclose(FILE *stream);
Exercise 1.6
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
Exercise 1.7
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.
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.
Exercise 1.8
Redo the exercise 1.6 but the program will read and write one character line at a time.
Exercise 1.9
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. For example, one line in an input file The quick brown fox jumps over the lazy dog. should be output as follows. 44 The quick brown fox jumps over the lazy dog.
Homework
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. For example, the following content of a text file
This is sample file. Hello!
is output as follows.
1 This is sample file. 2 Hello!