19.1 Learn the rules for Mixed Arithmetic Expressions
19.2 Learn the C String functions
19.3 Learn the C vector functions
| c_value * i_value | int |
| f_value - 7.3 | double |
| d_value + c_value | double |
| c_value - s_value | int |
| s_value - l_value | long int |
| s_value + 7 | int |
| s_value - 7.0 | double |
| 7 + 7.0 | double |
EXAMPLE USE OF CASTS
double ratio, q, r ; q = 7.0 ; r = 2.0 ; ratio = (int) q / (int) r ;
STRING FUNCTIONS
| strcpy( ) | char *s1, char *s2 | copies s2 to s1 ; returns s1 |
| strncpy( ) | char *s1, char *s2, int n | copies at most n characters of s2 to s1 ; returns s1 |
| strcat( ) | char *s1, char *s2 | concatenates s2 to end of s1 ; returns s1 |
| strncat( ) | char *s1, char *s2, int n | concatenates first n characters of s2 to end of s1 ; returns s1 |
| strcmp( ) | char *s1, char *s2 | compares s1 to s2 ; returns < 0 if s1 < s2, 0 if s1 == s2 or > 0 if s1 > s2 |
| strlen( ) | char *s1 | returns length of s1 ( not including `\0` ) |
PROGRAM USING STRING FUNCTIONS
/* test various functions in string library */
#include <stdio.h>
#include <string.h>
main ( )
{
char string1[ ] = "document" ;
/* first test string */
char string2[ ] = "disk" ;
/* second test string */
char s3[20], s4 [20], s5[20] ;
/* test string length */
printf("Length of string 1 is %d\n",
strlen(string1)) ;
/* test string copy functions */
strcpy(s3, string2) ;
strncpy(s4, string2, 3) ;
printf("Two copied strings are %s and %s \n",
s3, s4) ;
/* test string concatenation functions */
strcat(s3, string1) ;
strncat(s4, string1, 3) ;
printf("Two concatenated strings are %s and %s \n",
s3, s4) ;
/* test string comparison */
if(strcmp(s3, s4)) printf("Strings are different \n") ;
else
printf("Strings are identical \n") ;
}
OUTPUT :
Length of string1 is 8 Two copied strings are disk and dis Two concatenated strings are disk document and disdoc Strings are different
FUNCTION TO COMPUTE LENGTH OF A VECTOR
/* function to compute the length of a vector */
#include <math.h>
double length( double v[ ], int n)
{
double total = 0.0 ;
int i ;
for( i=0 ; i<n ; i++ ) total += v[i] * v[i] ;
return(sqrt(total)) ;
}
FUNCTION TO COMPUTE INNER PRODUCT OF TWO VECTORS
/* function to compute an inner product */
double inner_product( double v[ ], double w[ ], int n )
{
double total = 0.0 ;
int i ;
for ( i=0 ; i<n ; i++ ) total += v[i] * w[i] ;
return(total) ;
}
On to the next lecture
Go back to lecture menu