Programming in C Unit 5 : String, Math and Date Time Functions Shalu J. Rajawat
Strings 2
Strings A special kind of array is an array of characters ending in the null character \0 called string arrays A string is declared as an array of characters char s[10] char p[30] When declaring a string don’t forget to leave a space for the null character which is also known as the string terminator character 3
Strings 4 String Literals String literal values are represented by sequences of characters between double quotes (“) Examples “” - empty string “hello” “a” versus ‘a’ ‘a’ is a single character value (stored in 1 byte) as the ASCII value for a “a” is an array with two characters, the first is a, the second is the character value \0
Strings 5 Duplicate String Literals Each string literal in a C program is stored at a different location So even if the string literals contain the same string, they are not equal (in the == sense) Example: char string1[6] = “hello”; char string2[6] = “hello”; but string1 does not equal string2 (they are stored at different locations)
String Variables 6 Allocate an array of a size large enough to hold the string (plus 1 extra value for the delimiter) Examples (with initialization): char str1[6] = “Hello”; char str2[] = “Hello”; char *str3 = “Hello”; char str4[6] = {‘ H’,’e’,’l’,’l’,’o ’,’\0’}; Note, each variable is considered a constant in that the space it is connected to cannot be changed str1 = str2; /* not allowable, but we can copy the contents of str2 to str1 (more later) */
String Input Use %s field specification in scanf to read string ignores leading white space reads characters until next white space encountered C stores null (\0) char after last non-white space char Reads into array (no & before name, array is a pointer) Example: char Name[11]; scanf (“% s”,Name ); Problem: no limit on number of characters read (need one for delimiter), if too many characters for array, problems may occur . 7
Operations on strings 8 strcpy - copy one string into another strcat - append one string onto the right side of the other strcmp – compare alphabetic order of two strings strlen – return the length of a string Strrev -reverse the string Strupr - convert string to uppercase Strlwr - convert string to lowercase
Strcpy 9 strcpy ( destinationstring , sourcestring ) Copies sourcestring into destinationstring For example strcpy ( str , “hello world”); assigns “hello world” to the string str Code: #include < stdio.h > #include < string.h > main() { char x[] = “Example with strcpy ”; char y[25]; printf (“The string in array x is %s \n “, x); strcpy ( y,x ); printf (“The string in array y is %s \n “, y); }
Strcat 10 strcat ( destinationstring , sourcestring ) appends sourcestring to right hand side of destinationstring For example if str had value “a big ” strcat ( str , “hello world ”); Appends “hello world” to the string “a big ” to get “ a big hello world ” Code: # include < stdio.h > #include < string.h > main() { char x[] = “Example with strcat ”; char y[]= “which stands for string concatenation”; printf (“The string in array x is %s \n “, x); strcat ( x,y ); printf (“The string in array x is %s \n “, x); }
Mathematics Functions 11
Mathematics Functions All C inbuilt functions which are declared in “ math.h ” header file supports all the mathematical related functions in C language. All the arithmetic functions used in C language are given below. 12 Function Description floor ( ) This function returns the nearest integer which is less than or equal to the argument passed to this function. round ( ) This function returns the nearest integer value of the float/double/long double argument passed to this function. If decimal value is from “.1 to .5”, it returns integer value less than the argument. If decimal value is from “.6 to .9”, it returns the integer value greater than the argument. ceil ( ) This function returns nearest integer value which is greater than or equal to the argument passed to this function. sin ( ) This function is used to calculate sine value.
Mathematics Functions Function Description cos ( ) This function is used to calculate cosine. cosh ( ) This function is used to calculate hyperbolic cosine. exp ( ) This function is used to calculate the exponential “e” to the x th power. tan ( ) This function is used to calculate tangent. tanh ( ) This function is used to calculate hyperbolic tangent. sinh ( ) This function is used to calculate hyperbolic sine. log ( ) This function is used to calculates natural logarithm. log10 ( ) This function is used to calculates base 10 logarithm. sqrt ( ) This function is used to find square root of the argument passed to this function. pow ( ) This is used to find the power of the given number. trunc . ( . ) This function truncates the decimal value from floating point value and returns integer value. 13
Program for Mathematics Function // C code to illustrate // the use of math function #include < stdio.h > #include < math.h > int main () { double x = 0, val4 = -2.3, x=2.7, ret; int b = -344, c =3; printf ("The exponential value of %lf is %lf\n", x, exp(x)); printf ("The exponential value of %lf is %lf\n", x+1, exp(x+1)); printf ("The exponential value of %lf is %lf\n", x+2, exp(x+2)); printf ("value4 = %.1lf\n", ceil(val4)); printf ("Value4 = %.1lf\n", floor(val4)); printf ("The absolute value of %d is %lf\n", b, fabs (b)); ret = log(x); printf("log(%lf) = %lf", x, ret); x = 10000; /* finding value of log1010000 */ ret = log10(x); printf("log10(%lf) = %lf\n", x, ret); printf ("Remainder of %f / %d is %lf\n", x, c, fmod (x, c)); return(0); } 14
Date & Time Function 15
Date & Time Function Date &Time functions in C are used to interact with system date & time routine and formatted time outputs are displayed. Example programs for the date & time functions are given below . 16
Date and Time Functions Function Description setdate () This function used to modify the system date getdate() This function is used to get the CPU time clock() This function is used to get current system time time() This function is used to get current system time as structure difftime() This function is used to get the difference between two given times strftime() This function is used to modify the actual time format mktime() This function interprets tm structure as calendar time localtime () This function shares the tm structure that contains date and time informations gmtime() This function shares the tm structure that contains date and time informations ctime () This function is used to return string that contains date and time informations asctime () Tm structure contents are interpreted by this function as calendar time. This time is converted into string. 17
setDate #include< stdio.h > #include< dos.h > #include< conio.h > int main() { struct date dt ; printf ("Enter new date in the format(day month year)"); scanf ("% d%d%d",&dt.da_day,&dt.da_mon,&dt.da_year ); setdate (& dt ); printf ("Now, current system date is %d-%d-% d\n” , dt.da_day,dt.da_mon,dt.da_year ); return 0; } 18
getDate () #include< stdio.h > #include< dos.h > int main() { struct date dt ; getdate (& dt ); printf ("Operating system's current date is %d-%d-%d\n" , dt.da_day,dt.da_mon,dt.da_year ); return 0; } 19
Clock() #include < stdio.h > #include < time.h > #include < math.h > int main() { int i ; clock_t CPU_time_1 = clock(); printf ("CPU start time is : %d \n", CPU_time_1); for ( i = 0; i < 150000000; i ++); clock_t CPU_time_2 = clock(); printf ("CPU end time is : %d", CPU_time_2); } 20
Time() & Difftime () #include < stdio.h > #include < time.h > int main () { time_t seconds; seconds = time ( NULL ); printf ("Number of hours since 1970 Jan 1st " \ "is %ld \n", seconds/3600); return 0; } #include < stdio.h > #include < time.h > int main() { time_t begin, end ; long i ; begin= time( NULL ); for ( i = 0; i < 150000000; i ++); end = time( NULL ); printf ("for loop used %f seconds to complete the " \ "execution\n", difftime ( end , begin)); return 0; } 21
Remaining Functions #include < stdio.h > #include < time.h > #define LEN 150 int main () { char buf [LEN]; time_t curtime ; struct tm * loc_time ; //Getting current time of system curtime = time ( NULL ); // Converting current time to local time loc_time = localtime (& curtime ); // Displaying date and time in standard format printf ("%s", asctime ( loc_time )); strftime ( buf , LEN, "Today is %A, %b %d.\n", loc_time ); fputs ( buf , stdout ); strftime ( buf , LEN, "Time is %I:%M %p.\n", loc_time ); fputs ( buf , stdout ); return 0; } 22
Summary C is a general-purpose programming language. C is a high-level language that is easy to read, understand and maintain C programs can be reused. C needs a compiler to convert its programs into machine readable form 23