Sunteți pe pagina 1din 43

Introduction to C Programming

Introduction to C Programming
Individual Assignment
Name: Mohammad Reza Ganji TP032353
Intake Code: UC1F1310IT
Lecturer: Ms. Sathiapriya A/P Ramiah
Date Due: 5 August 2014

Introduction to C Programming

Contents
Table of Figures ............................................................................................................................................. 4
Assumptions:................................................................................................................................................. 5
Pseudocode ................................................................................................................................................... 6
Flow Charts ................................................................................................................................................. 11
Welcome ................................................................................................................................................. 11
Login Form .............................................................................................................................................. 12
Admin Menu ........................................................................................................................................... 13
New Registration..................................................................................................................................... 14
Delete ...................................................................................................................................................... 15
Edit .......................................................................................................................................................... 16
Search...................................................................................................................................................... 17
System Overview: ....................................................................................................................................... 18
Architectural Design:................................................................................................................................... 18
Execution Concept: ..................................................................................................................................... 18
Login Process: ......................................................................................................................................... 18
Main Menu:............................................................................................................................................. 19
Registration: ............................................................................................................................................ 19
Edit: ......................................................................................................................................................... 20
Delete: ..................................................................................................................................................... 21
Search...................................................................................................................................................... 21
Exit Program:........................................................................................................................................... 22
Test Procedures: ......................................................................................................................................... 22
Function Login(); ..................................................................................................................................... 22
Purpose and Procedure: ..................................................................................................................... 22
Input: ................................................................................................................................................... 22
Expected Output: ................................................................................................................................ 22
Function Menu(); .................................................................................................................................... 22
Purpose and Procedure: ..................................................................................................................... 22
Input: ................................................................................................................................................... 22
Expected Output: ................................................................................................................................ 22
Function reg();......................................................................................................................................... 23

Introduction to C Programming
Purpose and Procedure: ..................................................................................................................... 23
Input: ................................................................................................................................................... 23
Expected Output: ................................................................................................................................ 23
Function Delete(); ................................................................................................................................... 23
Purpose and Procedure: ..................................................................................................................... 23
Input: ................................................................................................................................................... 23
Expected Output: ................................................................................................................................ 23
Function Edit();........................................................................................................................................ 23
Purpose and Procedure: ..................................................................................................................... 23
Input: ................................................................................................................................................... 23
Expected Output: ................................................................................................................................ 23
Function Search(); ................................................................................................................................... 24
Purpose and Procedure: ..................................................................................................................... 24
Input: ................................................................................................................................................... 24
Expected Output: ................................................................................................................................ 24
Function Exit(); ........................................................................................................................................ 24
Purpose and Procedure: ..................................................................................................................... 24
Input: ................................................................................................................................................... 24
Expected Output: ................................................................................................................................ 24
C Concepts .................................................................................................................................................. 25
_CRT_SECURE_NO_DEPRECATE.............................................................................................................. 25
#include <stdio.h> ....................................................................................................................................... 25
#include <stdlib.h> ...................................................................................................................................... 30
#include <string.h>...................................................................................................................................... 33
Return Statement ....................................................................................................................................... 38
fflush() Function .......................................................................................................................................... 38
References .................................................................................................................................................. 43

Introduction to C Programming

Table of Figures
Figure 2 - Welcome Screen Diagram........................................................................................................... 11
Figure 3 - Login Form Diagram .................................................................................................................... 12
Figure 4 - Admin Menu Diagram ................................................................................................................. 13
Figure 5 - New Registration Diagram .......................................................................................................... 14
Figure 6 - Delete Function Diagram ............................................................................................................ 15
Figure 7 - Edit Function Diagram................................................................................................................. 16
Figure 8 - Search Diagram .......................................................................................................................... 17
Figure 9 - Login Process............................................................................................................................... 18
Figure 10 - Main Menu Sample ................................................................................................................... 19
Figure 11 - Registration Function Sample ................................................................................................... 20
Figure 12 - Edit Function Sample ................................................................................................................ 21
Figure 13 - Delete Function Sample ............................................................................................................ 21
Figure 14 - Search Function Sample............................................................................................................ 22

Introduction to C Programming

Assumptions:
In this module Introduction to C Programming, plenty of problems faced when coding c program. All
the lecturer and tutorial section are not enough for us to learn coding as we are still new in coding and
lack of knowledge about it. We even have to meet or ask lecturer personally when we facing error. To
ensure all the works go smoothly, we have to research all the online resources, finding books in library
and go through each lecturer slide provided.
In addition, coding error is the major cause that faced me. I might not be able to find the error if using
notepad++ as it will not showed the error. To correct all the errors, I have to find the error code from
the start to the end. However, Visual Studio will show the errors when coding. This is easier during the
coding. There are some common errors which are wrong spelling, error in arrangement, missing of
semicolon and variable entered.
Last but not least, c program is actually quick fun for me. I will perform a better program in the future by
having more lessons and experiences about coding.

Introduction to C Programming

Pseudocode
Int Main
Call login function
End
Login Function
Print Please Enter Admin Usename
Read username
Print please Enter Your Password
Read password
If username==usernamevalue&&password==passwordvalue
Call menu function
Else
Print Username and/or password does not exist. Please enter the correct information.\n\n\n
End if
End

Menu Function
Start
Print Menu \n\n ______________ \n 1. Add New Student \n 2. Edit an Existed Student\n 3. Delete an
Existed Student Informations\n 4. Search for a Student\n\n\n Please Choose an action
Read choose
start Switch choose
start Case 1
Call reg function
End case 1
start Case 2
Print Edit an Existed Student Information(s):

Introduction to C Programming
Call edit function
End case 2
start Case 3
Print Delete an Existed Student Information(s):
Call function delete
End case 3
start Case 4
call function search
end case 4
start case 5
end program
end case 5
switch default return
print Please choose an action from the menu.
End switch
End
Reg Function
Register pointer
Print please enter the student ID
Read StudentID
Print please enter the student Name
Read StudentName
Print please enter the student IC/Pass
Read IC
Print please enter the student Gender
Read Gender

Introduction to C Programming
Print please enter the student DateofBirth
Read Birth
Print please enter the student Phone
Read Phone
Print please enter the student Nationality
Read Nationality
Print please enter the student Course
Read Course
Write studentsFile, StudentID, StudentName,IC,Gender,Birth,Phone,Nationality,Course
Close file
Call menu function

Search Function
Register pointer
Print Please enter the TP to check:
Read TP
Add .txt to the end of TP
Search for tp.txt
If tp does not exist
Print No such file.
Else
Open the file as read only permission
Print TP number found and please review the student informations below
Print TPNUMBER, NAME, IC/PASSPORT, GENDER, CONTACT NUMBER, NATIONALITY, COURSE, DOB,
MOB, YOB
End if
Call menu function

Introduction to C Programming

Edit Function
Register pointer
Print Please enter the TP to Edit:
Read TP
Add .txt to the end of TP
Search for tp.txt
If tp does not exist
Print No such file.
Else
Open the file as read&write permission
Print please enter the student ID
Read StudentID
Print please enter the student Name
Read StudentName
Print please enter the student IC/Pass
Read IC
Print please enter the student Gender
Read Gender
Print please enter the student DateofBirth
Read Birth
Print please enter the student Phone
Read Phone
Print please enter the student Nationality
Read Nationality
Print please enter the student Course

Introduction to C Programming
Read Course
Write studentsFile, StudentID, StudentName,IC,Gender,Birth,Phone,Nationality,Course
End if
Close file
Call menu function

Delete Function
Print Enter the name of file you wish to delete
Read filename
Add .txt to the filename
If removing the filename == -1
Print Error in deleting a file
Else
Print The file has been successfully deleted.
End if
Call menu function

Introduction to C Programming

Flow Charts
Welcome

Start

Welcome

Login Page

Figure 1 - Welcome Screen Diagram

Introduction to C Programming

Login Form

Login
Form

Username

Password

Error

Authentication

Access Granted

Admin
Menu
Figure 2 - Login Form Diagram

Introduction to C Programming

Admin Menu

Admin Menu

If Case = 1

Add
New
Student

If Case = 2

Edit

If Case = 3

Delete

If Case = 4

Search

End

Exit

Figure 3 - Admin Menu Diagram

Introduction to C Programming

New Registration

Registration

TP Number

Student Name

Nationality

Course

IC/Passport
Date of Birth

Gender
Month of Birth

Contact
Number
Year of Birth

Figure 4 - New Registration Diagram

Admin
Menu

Introduction to C Programming

Delete

Delete

TP Number

Check TP Number
Existence

False

Admin
Menu

Figure 5 - Delete Function Diagram

True

Delete the TP file

Introduction to C Programming

Edit

Delete
True

TP Number

Check TP Number
Existence

TP Number

Student Name

Nationality

Course

IC/Passport
Date of Birth

False

Gender
Month of Birth

Admin
Menu
Contact
Number

Year of Birth

Figure 6 - Edit Function Diagram

Introduction to C Programming

Search

Start

Search

Input TP
Number

Search for TP
Number File

If Availability = 1

True

Print the File


Content

False

null

Admin Menu

Figure 7 - Search Diagram

Introduction to C Programming

System Overview:
This program has used simple and basic C programming codes for creating a program that
its usage is for Student Information Management System. This system will be used by the
administrative staff to maintain the records of students. The users should be able to register
new student, edit, delete and search information of students. Some of the following details
of each student are recorded:
- Student ID (unique)
- Name
- National Identification Card Number
- Gender
- Date of birth
- Contact Number
- Nationality
- Course

Architectural Design:
The program store the registered students information to the txt files and also edit, delete and
search the data in the txt files. Each TP number (student) has his own individual txt file with the
TPNUMBER.TXT format.

Execution Concept:
Login Process:
By starting the program and pressing the run button, the application will enter its main execution
loop. In the main loop the welcome message will be displayed and the user will be asked for its
user name and password.

Figure 8 - Login Process

The login user name of this program is user, and the password is pass.

Introduction to C Programming

Main Menu:

After inserting the correct user name and password by the admin staff, the main menu which is
consist of 4 main options to choose, that are: 1-Add New Student, 2- Edit an Existed Student, 3Delete an Existed Student Information(s) and 4- Seach for a Student, and one more option which
terminate the program and quit the loop, which is

Figure 9 - Main Menu Sample

Exit Program will be appear. Admin will be asked to insert the number of option that he has
chosen.

Registration:
By choosing number 1 Add New Student, the program show a pathway message that show you
which option did you choose, and then admin must enter all the student information that
including TP Number, Name, IC/Passport Number, Gender, Contact Number, Nationality,
Course, Date of Birth, Month of Birth, Year of Birth, and then if there is no error during entering
information in the program, the student txt file will create and application show a success
message of that.

Introduction to C Programming

Figure 10 - Registration Function Sample

Edit:
By choosing number 2 the program administrator can edit the available student information by
using his/her student ID, the first step admin should enter the TP number and then program
search the directory to find a .txt file with that tp number, if result is true then program ask
admin to enter new student informations.

Introduction to C Programming

Figure 11 - Edit Function Sample

Delete:
Admin can delete and student information from system by entering tp number. After admin
chose option number 3 from the main menu and entering a exited TP number program will
delete that student txt file.

Figure 12 - Delete Function Sample

Search
By choosing option number 4 admin can search whether the a student is exist or not.

Introduction to C Programming

Figure 13 - Search Function Sample

Exit Program:
Admin can quit from the system and terminate the main loop by selecting exit. It will discontinue
the program from running.

Test Procedures:
Function Login();
Purpose and Procedure:
Enables user to login into the main program and main menu.
Input:
It has been set in the program that username is user and password is pass
Expected Output:
When the user enter the correct username and password will be able to go to the main menu.
If user fails to type in correctly the combinations, system will ask to re-enter the username and
password.

Function Menu();
Purpose and Procedure:
Gives 5 options to the user so admin can register new student, delete, update and search in the
system or exit from the program.
Input:
User has to enter the number of the selected option to go through the operation.
Expected Output:
Admin should get the details of the selected option, if the user enter a wrong number system will
shown an error message and forward the admin to the main menu screen.

Introduction to C Programming

Function reg();
Purpose and Procedure:
Enables user to add new students to the program and fill up the informations of the new student.
Input:
Inputs for registering new students are TP Number, Name, IC/Pass, Gender, Contact Number,
Natonality, Course, Date of Birth, Month of Birth, and Year of Birth.
Expected Output:
When admin entered all the informations correctly, then program show him a message that is the
success message.

Function Delete();
Purpose and Procedure:
The purpose of this function is that it makes the administration able to delete some of registered
students from the system.
Input:
The required input for this function is the student tp number which admin has registered the student
with.
Expected Output:
System will search through the files to find the tp number and delete it, if it couldnt find it an error
will come up which says The user not found and will show the main menu to the user.

Function Edit();
Purpose and Procedure:
This function helps the user to update and change the information about registered students.
Input:
Admin by using student tp number can access to this function.
Expected Output:
Its expected that system after finding the student by tp number, give the user options that asks
students new information. If the tp number is not valid, The user not found error will come up.
Main Menu will be the last expected part to be shown.

Introduction to C Programming

Function Search();
Purpose and Procedure:
Search is a tool for admin to check a tp number is existed in the system or not.
Input:
Student TP Number
Expected Output:
If student is existed in the system it will return a report of all information in the txt file, if not
system print an error on screen that is "No such file."

Function Exit();
Purpose and Procedure:
Enable user to stop the program from running process and terminate the loop.
Input:
There is no input required for this function.
Expected Output:
Stop the program and doesnt allow to get any input.

Introduction to C Programming

C Concepts
_CRT_SECURE_NO_DEPRECATE
To disable deprecation, In an older copy of crtdefs.h at around line 316 the macro
'_CRT_INSECURE_DEPRECATE' is defined. What it is defined to be is controlled by the test '#ifdef
_CRT_SECURE_NO_DEPRECATE' and the text message associated with the macro is "This function or
variable may be unsafe. Consider using " #_Replacement " instead. To disable deprecation, use
_CRT_SECURE_NO_DEPRECATE. See online help for details."
Thus, I used _CRT_SECURE_NO_DEPRECATE to block any warning for unsecured codes.
Line 1
#define _CRT_SECURE_NO_DEPRECATE

#include <stdio.h>
The stdio .h header defines three variable types, several macros and various functions for performing
input and output.
Library Variables
Following are the variable types defined in the header stdio.h:
S.N.

Variable & Description

size_t
This is the unsigned integral type and is the result of the sizeof keyword.

FILE
This is an object type suitable for storing information for a file stream.

fpos_t
This is an object type suitable for storing any position in a file.

Library Macros
Following are the macros defined in the header stdio.h:
S.N.

Macro & Description

NULL
This macro is the value of a null pointer constant.

_IOFBF, _IOLBF and _IONBF


These are the macros which expand to integral constant expressions with distinct values
and suitable for the use as third argument to the setvbuf function.

Introduction to C Programming
3

BUFSIZ
This macro is an integer which represents the size of the buffer used by the setbuf function.

EOFM
This macro is a negative integer which indicates an end-of-file has been reached.

FOPEN_MAX
This macro is an integer which represents the maximum number of files that the system
can guarantee that can be opened simultaneously.

FILENAME_MAX
This macro is an integer which represents the longest length of a char array suitable for
holding the longest possible filename. If the implementation imposes no limit, then this
value should be the recommended maximum value.

L_tmpnam
This macro is an integer which represents the longest length of a char array suitable for
holding the longest possible temporary filename created by the tmpnam function.

SEEK_CUR, SEEK_END, and SEEK_SET


These macros are used in the fseek function to locate different positions in a file.

TMP_MAX
This macro is the maximum number of unique filenames that the function tmpnam can
generate.

10

stderr, stdin, and stdout


These macros are pointers to FILE types which correspond to the standard error, standard
input, and standard output streams.

Library Functions
Following are the functions defined in the header stdio.h:
Follow the same sequence of functions for better understanding and to make use of Try it option
because file created in the first function will be used in subsequent functions.
S.N.

Function & Description

int fclose(FILE *stream)


Closes the stream. All buffers are flushed.

void clearerr(FILE *stream)


Clears the end-of-file and error indicators for the given stream.

Introduction to C Programming
3

int feof(FILE *stream)


Tests the end-of-file indicator for the given stream.

int ferror(FILE *stream)


Tests the error indicator for the given stream.

int fflush(FILE *stream)


Flushes the output buffer of a stream.

int fgetpos(FILE *stream, fpos_t *pos)


Gets the current file position of the stream and writes it to pos.

FILE *fopen(const char *filename, const char *mode)


Opens the filename pointed to by filename using the given mode.

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)


Reads data from the given stream into the array pointed to by ptr.

FILE *freopen(const char *filename, const char *mode, FILE *stream)


Associates a new filename with the given open stream and same time closing the old file in
stream.

10

int fseek(FILE *stream, long int offset, int whence)


Sets the file position of the stream to the given offset. The argument offset signifies the
number of bytes to seek from the given whence position.

11

int fsetpos(FILE *stream, const fpos_t *pos)


Sets the file position of the given stream to the given position. The argument pos is a
position given by the function fgetpos.

12

long int ftell(FILE *stream)


Returns the current file position of the given stream.

13

size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
Writes data from the array pointed to by ptr to the given stream.

14

int remove(const char *filename)


Deletes the given filename so that it is no longer accessible.

15

int rename(const char *old_filename, const char *new_filename)


Causes the filename referred to by old_filename to be changed to new_filename.

16

void rewind(FILE *stream)


Sets the file position to the beginning of the file of the given stream.

Introduction to C Programming
17

void setbuf(FILE *stream, char *buffer)


Defines how a stream should be buffered.

18

int setvbuf(FILE *stream, char *buffer, int mode, size_t size)


Another function to define how a stream should be buffered.

19

FILE *tmpfile(void)
Creates a temporary file in binary update mode (wb+).

20

char *tmpnam(char *str)


Generates and returns a valid temporary filename which does not exist.

21

int fprintf(FILE *stream, const char *format, ...)


Sends formatted output to a stream.

22

int printf(const char *format, ...)


Sends formatted output to stdout.

23

int sprintf(char *str, const char *format, ...)


Sends formatted output to a string.

24

int vfprintf(FILE *stream, const char *format, va_list arg)


Sends formatted output to a stream using an argument list.

25

int vprintf(const char *format, va_list arg)


Sends formatted output to stdout using an argument list.

26

int vsprintf(char *str, const char *format, va_list arg)


Sends formatted output to a string using an argument list.

27

int fscanf(FILE *stream, const char *format, ...)


Reads formatted input from a stream.

28

int scanf(const char *format, ...)


Reads formatted input from stdin.

29

int sscanf(const char *str, const char *format, ...)


Reads formatted input from a string.

30

int fgetc(FILE *stream)


Gets the next character (an unsigned char) from the specified stream and advances the
position indicator for the stream.

31

char *fgets(char *str, int n, FILE *stream)


Reads a line from the specified stream and stores it into the string pointed to by str. It stops

Introduction to C Programming
when either (n-1) characters are read, the newline character is read, or the end-of-file is
reached, whichever comes first.
32

int fputc(int char, FILE *stream)


Writes a character (an unsigned char) specified by the argument char to the specified
stream and advances the position indicator for the stream.

33

int fputs(const char *str, FILE *stream)


Writes a string to the specified stream up to but not including the null character.

34

int getc(FILE *stream)


Gets the next character (an unsigned char) from the specified stream and advances the
position indicator for the stream.

35

int getchar(void)
Gets a character (an unsigned char) from stdin.

36

char *gets(char *str)


Reads a line from stdin and stores it into the string pointed to by str. It stops when either
the newline character is read or when the end-of-file is reached, whichever comes first.

37

int putc(int char, FILE *stream)


Writes a character (an unsigned char) specified by the argument char to the specified
stream and advances the position indicator for the stream.

38

int putchar(int char)


Writes a character (an unsigned char) specified by the argument char to stdout.

39

int puts(const char *str)


Writes a string to stdout up to but not including the null character. A newline character is
appended to the output.

40

int ungetc(int char, FILE *stream)


Pushes the character char (an unsigned char) onto the specified stream so that the this is
the next character read.

41

void perror(const char *str)


Prints a descriptive error message to stderr. First the string str is printed followed by a
colon then a space.

Introduction to C Programming

#include <stdlib.h>
The stdlib .h header defines four variable types, several macros and various functions for performing
general functions.
Library Variables
Following are the variable types defined in the header stdlib.h:
S.N.

Variable & Description

size_t
This is the unsigned integral type and is the result of the sizeof keyword.

wchar_t
This is an integer type of the size of a wide character constant.

div_t
This is the structure returned by the div function.

ldiv_t
This is the structure returned by the ldiv function.

Library Macros
Following are the macros defined in the header stdlib.h:
S.N.

Macro & Description

NULL
This macro is the value of a null pointer constant.

EXIT_FAILURE
This is the value for the exit function to return in case of failure.

EXIT_SUCCESS
This is the value for the exit function to return in case of success.

RAND_MAX
This macro is the maximum value returned by the rand function.

MB_CUR_MAX
This macro is the maximum number of bytes in a multibyte character set which cannot be
larger than MB_LEN_MAX.

Library Functions
Following are the functions defined in the header stdio.h:

Introduction to C Programming
S.N.

Function & Description

double atof(const char *str)


Converts the string pointed to by the argument str to a floating-point number (type
double).

int atoi(const char *str)


Converts the string pointed to by the argument str to an integer (type int).

long int atol(const char *str)


Converts the string pointed to by the argument str to a long integer (type long int)

double strtod(const char *str, char **endptr)


Converts the string pointed to by the argument str to a floating-point number (type
double).

long int strtol(const char *str, char **endptr, int base)


Converts the string pointed to by the argument str to a long integer (type long int).

unsigned long int strtoul(const char *str, char **endptr, int base)
Converts the string pointed to by the argument str to an unsigned long integer (type
unsigned long int).

void *calloc(size_t nitems, size_t size)


Allocates the requested memory and returns a pointer to it.

void free(void *ptr


Deallocates the memory previously allocated by a call to calloc, malloc, or realloc.

void *malloc(size_t size)


Allocates the requested memory and returns a pointer to it.

10

void *realloc(void *ptr, size_t size)


Attempts to resize the memory block pointed to by ptr that was previously allocated with a
call to malloc or calloc.

11

void abort(void)
Causes an abnormal program termination.

12

int atexit(void (*func)(void))


Causes the specified function func to be called when the program terminates normally.

13

void exit(int status)


Causes the program to terminate normally.

Introduction to C Programming
14

char *getenv(const char *name)


Searches for the environment string pointed to by name and returns the associated value
to the string.

15

int system(const char *string)


The command specified by string is passed to the host environment to be executed by the
command processor.

16

void *bsearch(const void *key, const void *base, size_t nitems, size_t size, int
(*compar)(const void *, const void *))
Performs a binary search.

17

void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))
Sorts an array

18

int abs(int x)
Returns the absolute value of x.

19

div_t div(int numer, int denom)


Divides numer (numerator) by denom (denominator).

20

long int labs(long int x)


Returns the absolute value of x.

21

ldiv_t ldiv(long int numer, long int denom)


Divides numer (numerator) by denom (denominator).

22

int rand(void)
Returns a pseudo-random number in the range of 0 to RAND_MAX.

23

void srand(unsigned int seed)


This function seeds the random number generator used by the function rand.

24

int mblen(const char *str, size_t n)


Returns the length of a multibyte character pointed to by the argument str.

25

size_t mbstowcs(schar_t *pwcs, const char *str, size_t n)


Converts the string of multibyte characters pointed to by the argument str to the array
pointed to by pwcs.

26

int mbtowc(whcar_t *pwc, const char *str, size_t n)


Examines the multibyte character pointed to by the argument str.

27

size_t wcstombs(char *str, const wchar_t *pwcs, size_t n)


Converts the codes stored in the array pwcs to multibyte characters and stores them in the
string str.

Introduction to C Programming
28

int wctomb(char *str, wchar_t wchar)


Examines the code which corresponds to a multibyte character given by the argument
wchar.

#include <string.h>
The string .h header defines one variable type, one macro and various functions for manipulating arrays
of characters.
to compare, copy, append, to find the length of string .. u have to use string functions from string.h
strcpy(one,two)-to copy two into one
strcmp(one,two) - compare one and two. returns 0 if both are same
strlen(one) - returns the length of one
strcat(one,two) - to append two wit one.
onetwo
Library Variables
Following is the variable type defined in the header string.h:
S.N.

Variable & Description

size_t
This is the unsigned integral type and is the result of the sizeof keyword.

Library Macros
Following is the macro defined in the header string.h:
S.N. Macro & Description
1

NULL
This macro is the value of a null pointer constant.

Library Functions
Following are the functions defined in the header string.h:
S.N.

Function & Description

Introduction to C Programming
1

void *memchr(const void *str, int c, size_t n)


Searches for the first occurrence of the character c (an unsigned char) in the first n bytes of
the string pointed to by the argument str.

int memcmp(const void *str1, const void *str2, size_t n)


Compares the first n bytes of str1 and str2.

void *memcpy(void *dest, const void *src, size_t n)


Copies n characters from src to dest.

void *memmove(void *dest, const void *src, size_t n)


Another function to copy n characters from str2 to str1.

void *memset(void *str, int c, size_t n)


Copies the character c (an unsigned char) to the first n characters of the string pointed to
by the argument str.

char *strcat(char *dest, const char *src)


Appends the string pointed to by src to the end of the string pointed to by dest.

char *strncat(char *dest, const char *src, size_t n)


Appends the string pointed to by src to the end of the string pointed to by dest up to n
characters long.

char *strchr(const char *str, int c)


Searches for the first occurrence of the character c (an unsigned char) in the string pointed
to by the argument str.

int strcmp(const char *str1, const char *str2)


Compares the string pointed to by str1 to the string pointed to by str2.

10

int strncmp(const char *str1, const char *str2, size_t n)


Compares at most the first n bytes of str1 and str2.

11

int strcoll(const char *str1, const char *str2)


Compares string str1 to str2. The result is dependent on the LC_COLLATE setting of the
location.

12

char *strcpy(char *dest, const char *src)


Copies the string pointed to by src to dest.

13

char *strncpy(char *dest, const char *src, size_t n)


Copies up to n characters from the string pointed to by src to dest.

Introduction to C Programming
14

size_t strcspn(const char *str1, const char *str2)


Calculates the length of the initial segment of str1 which consists entirely of characters not
in str2.

15

char *strerror(int errnum)


Searches an internal array for the error number errnum and returns a pointer to an error
message string.

16

size_t strlen(const char *str)


Computes the length of the string str up to but not including the terminating null character.

17

char *strpbrk(const char *str1, const char *str2)


Finds the first character in the string str1 that matches any character specified in str2.

18

char *strrchr(const char *str, int c)


Searches for the last occurrence of the character c (an unsigned char) in the string pointed
to by the argument str.

19

size_t strspn(const char *str1, const char *str2)


calculates the length of the initial segment of str1 which consists entirely of characters in
str2.

20

char *strstr(const char *haystack, const char *needle)


Finds the first occurrence of the entire string needle (not including the terminating null
character) which appears in the string haystack.

21

char *strtok(char *str, const char *delim)


Breaks string str into a series of tokens separated by delim.

22

size_t strxfrm(char *dest, const char *src, size_t n)


Transforms the first n characters of the string src into corrent locale and place them in the
string dest.

A function is a module or block of program code which deals with a particular task. Making functions is a
way of isolating one block of code from other independent blocks of code.
Functions serve two purposes.
They allow a programmer to say: `this piece of code does a specific job which stands by itself
and should not be mixed up with anyting else',
Second they make a block of code reusable since a function can be reused in many different
contexts without repeating parts of the program text.
A function can take a number of parameters, do required processing and then return a value. There may
be a function which does not return any value.
You already have seen couple of built-in functions like printf(); Similar way you can define your own
functions in C language.

Introduction to C Programming
Consider the following chunk of code
int total = 10;
printf("Hello World");
total = total + l;
To turn it into a function you simply wrap the code in a pair of curly brackets to convert it into a single
compound statement and write the name that you want to give it in front of the brackets:
Demo()
{
int total = 10;
printf("Hello World");
total = total + l;
}
curved brackets after the function's name are required. You can pass one or more paramenters to a
function as follows:
Demo( int par1, int par2)
{
int total = 10;
printf("Hello World");
total = total + l;
}
By default function does not return anything. But you can make a function to return any value as
follows:
int Demo( int par1, int par2)
{
int total = 10;
printf("Hello World");
total = total + l;
}

return total;

A return keyword is used to return a value and datatype of the returned value is specified before the
name of function. In this case function returns total which is int type. If a function does not return a
value then void keyword can be used as return value.
Once you have defined your function you can use it within a program:
main()
{
Demo();
}
Functions and Variables:
Each function behaves the same way as C language standard function main(). So a function will have its
own local variables defined. In the above example total variable is local to the function Demo.
A global variable can be accessed in any function in similar way it is accessed in main() function.
Declaration and Definition
When a function is defined at any place in the program then it is called function definition. At the time
of definition of a function actual logic is implemented with-in the function.
A function declaration does not have any body and they just have their interfaces.
A function declaration is usually declared at the top of a C source file, or in a separate header file.
A function declaration is sometime called function prototype or function signature. For the above
Demo() function which returns an integer, and takes two parameters a function declaration will be as
follows:
int Demo( int par1, int par2);

Introduction to C Programming

Passing Parameters to a Function


There are two ways to pass parameters to a function:
Pass by Value: mechanism is used when you don't want to change the value of passed
paramters. When parameters are passed by value then functions in C create copies of the
passed in variables and do required processing on these copied variables.
Pass by Reference mechanism is used when you want a function to do the changes in passed
parameters and reflect those changes back to the calling function. In this case only addresses of
the variables are passed to a function so that function can work directly over the addresses.
Here are two programs to understand the difference: First example is for Pass by value:
#include <stdio.h>
/* function declaration goes here.*/
void swap( int p1, int p2 );
int main()
{
int a = 10;
int b = 20;

printf("Before: Value of a = %d and value of b = %d\n", a, b );


swap( a, b );
printf("After: Value of a = %d and value of b = %d\n", a, b );

void swap( int p1, int p2 )


{
int t;

t = p2;
p2 = p1;
p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", p1, p2 );

Here is the result produced by the above example. Here the values of a and b remain unchanged before
calling swap function and after calling swap function.
Before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b(p2) = 10
After: Value of a = 10 and value of b = 20
Following is the example which demonstrate the concept of pass by reference
#include <stdio.h>
/* function declaration goes here.*/
void swap( int *p1, int *p2 );
int main()
{
int a = 10;
int b = 20;

printf("Before: Value of a = %d and value of b = %d\n", a, b );


swap( &a, &b );
printf("After: Value of a = %d and value of b = %d\n", a, b );

Introduction to C Programming
void swap( int *p1, int *p2 )
{
int t;

t = *p2;
*p2 = *p1;
*p1 = t;
printf("Value of a (p1) = %d and value of b(p2) = %d\n", *p1, *p2 );

Here is the result produced by the above example. Here the values of a and b are changes after calling
swap function.
Before: Value of a = 10 and value of b = 20
Value of a (p1) = 20 and value of b(p2) = 10
After: Value of a = 20 and value of b = 10

Return Statement
The return statement terminates the execution of a function and returns control to the calling function.
Execution resumes in the calling function at the point immediately following the call. A return statement
can also return a value to the calling function.
The value of expression, if present, is returned to the calling function. If expression is omitted, the
return value of the function is undefined. The expression, if present, is evaluated and then converted to
the type returned by the function. If the function was declared with return type void, a return statement
containing an expression generates a warning and the expression is not evaluated.
If no return statement appears in a function definition, control automatically returns to the calling
function after the last statement of the called function is executed. In this case, the return value of the
called function is undefined. If a return value is not required, declare the function to have void return
type; otherwise, the default return type is int.
Many programmers use parentheses to enclose the expression argument of the return statement.
However, C does not require the parentheses.

fflush() Function
The C library function int fflush(FILE *stream) flushes the output buffer of a stream.
Declaration
Following is the declaration for fflush() function.
int fflush(FILE *stream)
Parameters

stream -- This is the pointer to a FILE object that specifies a buffered stream.

Return Value

Introduction to C Programming
This function returns zero value on success. If an error occurs, EOF is returned and the error indicator is
set(i.e. feof).

if Statement
The if statement controls conditional branching. The body of an if statement is executed if the value of
the expression is nonzero. The syntax for the if statement has two forms.
selection-statement:
if ( expression ) statement
if ( expression ) statement else statement
In both forms of the if statement, the expressions, which can have any value except a structure, are
evaluated, including all side effects.
In the first form of the syntax, if expression is true (nonzero), statement is executed. If expression is
false, statement is ignored. In the second form of syntax, which uses else, the second statement is
executed if expression is false. With both forms, control then passes from the if statement to the next
statement in the program unless one of the statements contains a break, continue, or goto.
Example:
Line 26
if (strcmp(user, "user") == 0 && strcmp(pass, "pass") == 0)
menu();
else
{
printf_s("Username and/or password does not exist. Please enter the correct
information.\n\n\n");
login();
}

switch Statement
The switch and case statements help control complex conditional and branching operations. The switch
statement transfers control to a statement within its body.
selection-statement:
switch ( expression ) statement
labeled-statement:
case constant-expression : statement
default : statement
Control passes to the statement whose case constant-expression matches the value of switch
( expression ). The switch statement can include any number of case instances, but no two case

Introduction to C Programming
constants within the same switch statement can have the same value. Execution of the statement body
begins at the selected statement and proceeds until the end of the body or until a break statement
transfers control out of the body.
Use of the switch statement usually looks something like this:
switch ( expression )
{
declarations
.
.
.
case constant-expression :
statements executed if the expression equals the
value of this constant-expression
.
.
.
break;
default :
statements executed if expression does not equal
any case constant-expression
}
You can use the break statement to end processing of a particular case within the switch statement and
to branch to the end of the switch statement. Without break, the program continues to the next case,
executing the statements until a break or the end of the statement is reached. In some situations, this
continuation may be desirable.
The default statement is executed if no case constant-expression is equal to the value of switch
( expression ). If the default statement is omitted, and no case match is found, none of the statements in
the switch body are executed. There can be at most one default statement. The default statement need
not come at the end; it can appear anywhere in the body of the switch statement. A case or default label
can only appear inside a switch statement.
The type of switch expression and case constant-expression must be integral. The value of each case
constant-expression must be unique within the statement body.
The case and default labels of the switch statement body are significant only in the initial test that
determines where execution starts in the statement body. Switch statements can be nested. Any static
variables are initialized before executing into any switch statements.
Example:
Line 39
switch (choose)
{
case 1: reg(); menu();
break;
case 2:

Introduction to C Programming
printf_s("Edit an Existed Student Information(s):\n\n");
edit(); menu();
break;
case 3:
printf_s("Delete an Existed Student Information(s):\n\n");
delete();
break;
case 4:
search(); menu();
break;
case 5:
system("exit");
break;

default:
system("cls");
printf_s("Please choose an action from the menu.\n\n\n");
menu();
break;
}
}

File I/O operations in stdio.h


Character Based
int getc(FILE *f): returns the next character in the file stream f
as an integer or EOF
int fgetc(FILE *f): same as getc
int putc(int c, FILE *f): writes the character c to the file stream f and
returns the character written
int fputc(int c, FILE *f): same as putc
int ungetc(int c, FILE *f): pushes the character c back onto the file stream f
returns the chars pushed
you can only push back one character and EOF cannot be pushed back
used when you need to read in a char value and test it, and based on
test results need to put it back in the file.
int getchar(); read from stdin
putchar(int c); write to stdout (we usually use printf to do this instead)
Line Based: WARNING THESE CAN BE A BIT MORE TRICKY TO USE than getc & putc
char *fgets(char *s, int n, FILE *f);
reads at most n-1 characters into the array s stopping if a newline is
encountered, newline is included in the array which is '\0' terminated
int fputs(char *s, FILE *f);
writes the string s which need not contain a newline onto the file stream f
Formatted: WARNING THESE CAN BE REALLY TRICKY TO USE
(NEVER EVER USE scanf for reading in input from a user)
int fscanf(FILE *f, char *format, arg1, arg2, ...);
designed to be the counterpart to printf, uses a similar control string
returns EOF if end of file or an error occurs
otherwise returns the number of input items converted and assigned
int scanf(char *format, arg1, arg2, ...); for stdin

Introduction to C Programming
%d integer
%f float
%lf double
%c character
%s string, up to first white space
%[...] string, up to first character not in brackets
%[0123456789] would read in digits
%[^...] string, up to first character in brackets
%[^\n] would read everything up to a newline
int fprintf(FILE *f, char *format, addrofarg1, addrofarg2, ...);
just like standard printf, which assumes a file stream of stdout
allows you to specify other file streams

do-while Statement
The do-while statement lets you repeat a statement or compound statement until a specified expression
becomes false.
iteration-statement:
do statement while ( expression ) ;
The expression in a do-while statement is evaluated after the body of the loop is executed. Therefore,
the body of the loop is always executed at least once.
The expression must have arithmetic or pointer type. Execution proceeds as follows:
The statement body is executed.
Next, expression is evaluated. If expression is false, the do-while statement terminates and control
passes to the next statement in the program. If expression is true (nonzero), the process is repeated,
beginning with step 1.
The do-while statement can also terminate when a break, goto, or return statement is executed within
the statement body.
Example:
Line 101
do
{
printf_s("Please input your Date of birth\n");
scanf_s("%d", &date); fflush(stdin);
} while (date<0 || date >31);

Introduction to C Programming

References
C library function, 2014, strcpy(). [online] Available at:
<http://www.tutorialspoint.com/c_standard_library/c_function_strcpy.htm>[Accessed 4 June 2014].
Prototype int strcmp, 2014, strcmp(). [online] Available at:
<http://www.cprogramming.com/fod/strcmp.html>[Accessed 17 June 2014].
String length, 2014, find string length. [online] Available at:
<http://www.programmingsimplified.com/c-program-find-string-length>[Accessed 19 June 2014].
C Programming Expert, 2014, strcat(). [online] Available at:
<http://www.cprogrammingexpert.com/C/Tutorial/strings/strcat.aspx>[Accessed 29 June 2014].
Pointers in C++, 2011, Pointer Syntax. [online] Available at:
<http://www.cprogramming.com/tutorial/lesson6.html>[Accessed 01 July 2014].
Text Files in C, 2010, Using text files in C. [online] Available at:
<http://web.cs.swarthmore.edu/~newhall/unixhelp/C_files.html>[Accessed 10 July 2014].
Text Files in C, 2010, Using text files in C. [online] Available at:
<http://web.cs.swarthmore.edu/~newhall/unixhelp/C_files.html>[Accessed 10 July 2014].

C Language Reference, 2013, do-while Statement. [online] Available at:


<http://msdn.microsoft.com/en-us/library/8z1ch5dd.aspx> [Accessed 07 July 2014]

C Language Reference, 2013, IF Statement. [online] Available at:


< http://msdn.microsoft.com/en-us/library/fh88ctk1.aspx > [Accessed 07 July 2014]

C Language Reference, 2013, Switch Statement. [online] Available at:


<http://msdn.microsoft.com/en-us/library/66k51h7a.aspx> [Accessed 07 July 2014]

S-ar putea să vă placă și