C Tutorial Examples




C library function wcstombs() example

#include <stdio.h>
#include <stdlib.h>

#define BUFFER_SIZE 50

int main () {
   size_t ret;
   char *MB = (char *)malloc( BUFFER_SIZE );
   wchar_t *WC = L"Welcome To Tutorialsroot.com";

   /* converting wide-character string */
   ret = wcstombs(MB, WC, BUFFER_SIZE);
   
   printf("Characters converted = %u\n", ret);
   printf("Multibyte character = %s\n\n", MB);
   
   return(0);
}

Output

Characters converted = 28
Multibyte character = Welcome To Tutorialsroot.com

C library function malloc() example

#include <stdio.h>
#include <stdlib.h>

int main () {
   char *str;

   /* Initial memory allocation */
   str = (char *) malloc(15);
   strcpy(str, "tutorialsroot");
   printf("String = %s,  Address = %u\n", str, str);

   /* Reallocating memory */
   str = (char *) realloc(str, 25);
   strcat(str, ".com");
   printf("String = %s,  Address = %u\n", str, str);

   free(str);
   
   return(0);
}

Output

String = tutorialsroot,  Address = 35287056
String = tutorialsroot.com, Address = 35291200

C library function atan() example

#include <stdio.h>
#include <math.h>
#define PI 3.141592654

int main()
{
    double num = 1.0;
    double result;

    result = atan(num);

    printf("Inverse of tan(%.2f) = %.2f in radians", num, result);

    // Converting radians to degrees
    result = (result * 180) / PI;
    printf("\nInverse of tan(%.2f) = %.2f in degrees", num, result);

    return 0;
}

Output

Inverse of cos(1.00) = 0.79 in radians
Inverse of cos(1.00) = 45 in degrees

C library function time() example

#include <stdio.h>
#include <time.h>

int main () {
   time_t seconds;

   seconds = time(NULL);
   printf("Hours since January 1, 1980 = %ld\n", seconds/3600);
  
   return(0);
}

Output

Hours since January 1, 1980 = 425190

C library function strftime() example

#include <stdio.h>
#include <time.h>

int main () {
   time_t rawtime;
   struct tm *info;
   char buffer[80];

   time( &rawtime );

   info = localtime( &rawtime );

   strftime(buffer,80,"%x - %I:%M%p", info);
   printf("Formatted date & time : |%s|\n", buffer );
  
   return(0);
}

Output

Formatted date & time : |07/04/18 - 06:46AM|

C library function localtime() example

#include <stdio.h>
#include <time.h>

int main () {
   time_t rawtime;
   struct tm *info;
   char buffer[80];

   time( &rawtime );

   info = localtime( &rawtime );
   printf("Current local time and date: %s", asctime(info));

   return(0);
}

Output

Current local time and date: Wed Jul  4 06:51:23 2018

C library function gmtime() example

#include <stdio.h>
#include <time.h>

#define PDT (-7)

int main(int argc, const char * argv[])
{
    /* Define temporary variables */
    struct tm *gtime;
    time_t now;

    /* Read the current system time */
    time(&now);

    /* Convert the system time to GMT (now UTC) */
    gtime = gmtime(&now);

    /* Display the time in PDT and UTC */
    printf ("Pacific Daylight Time: %2d:%02d\n", (gtime->tm_hour + PDT) % 24,
    gtime->tm_min);
    printf ("Universal Time: %2d:%02d\n", gtime->tm_hour % 24, gtime->tm_min);

    return 0;
}


Output

Pacific Daylight Time: 14:14
Universal Time: 21:14

C library function difftime() example

#include <iostream>
#include <ctime>

using namespace std;

int main()
{
   time_t start, finish;
   long product;

   time(&start);
   for(int i=0; i<10000; i++)
   {
      for(int j=0; j<100000; j++)
      {
         product = i*j;
      }
   }
   time(&finish);
   cout << "Time required = " << difftime(finish, start) << " seconds";
   return 0;
}

Output

Time required = 3 seconds

C library function ctime() example

#include <iostream>
#include <ctime>
using namespace std;

int main()
{
   time_t curr_time;
   curr_time = time(NULL);

   char *tm = ctime(&curr_time);
   cout << "Today is : " << tm;

   return 0;
}

Output

Today is : Fri Mar 24 18:48:04 2017

C library function clock() example

#include <time.h>
#include <stdio.h>

int main () {
   clock_t start_t, end_t, total_t;
   int i;

   start_t = clock();
   printf("Starting of the program, start_t = %ld\n", start_t);
    
   printf("Going to scan a big loop, start_t = %ld\n", start_t);
   for(i=0; i< 10000000; i++) {
   }
   end_t = clock();
   printf("End of the big loop, end_t = %ld\n", end_t);
   
   total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
   printf("Total time taken by CPU: %f\n", total_t  );
   printf("Exiting of the program...\n");

   return(0);
}

Output

Starting of the program, start_t = 660
Going to scan a big loop, start_t = 660
End of the big loop, end_t = 28739
Total time taken by CPU: 0.000000
Exiting of the program...

C library function asctime() example

#include <stdio.h>
#include <string.h>
#include <time.h>

int main () {
   struct tm t;

   t.tm_sec    = 20;
   t.tm_min    = 20;
   t.tm_hour   = 6;
   t.tm_mday   = 25;
   t.tm_mon    = 2;
   t.tm_year   = 89;
   t.tm_wday   = 6;

   puts(asctime(&t));
   
   return(0);
}

Output

Sat Mar 25 06:20:20 1989

C library function strxfrm() example

#include <iostream>
#include <cstring>
#include <clocale>
using namespace std;
int main()
{
   setlocale(LC_COLLATE, "cs_CZ.UTF-8");
   const char* s1 = "hrnec";
   const char* s2 = "chrt";
   char t1[20], t2[20];

   cout << "strcoll returned " << strcoll(s1,s2) << endl;
   cout << "Before transformation, " << "strcmp returned " << strcmp(s1,s2) << endl;

   strxfrm(t1,s1,10);
   strxfrm(t2,s2,10);
   cout << "After transformation, " << "strcmp returned " << strcmp(t1,t2) << endl;

   return 0;
}

Output

strcoll returned -1
Before transformation, strcmp returned 1
After transformation, strcmp returned -1

C library function strtok() example

#include <cstring>
#include <iostream>

using namespace std;

int main()
{
   char str[] = "Crimson Chat,Tropical Parula,sparrow,pigeon,crow";
   char delim[] = ",";
   cout << "The tokens are:" << endl;
   char *token = strtok(str,delim);
   while (token)
   {
      cout << token << endl;
      token = strtok(NULL,delim);
   }
   return 0;
}

Output

The tokens are:
Crimson Chat
Tropical Parula
sparrow
pigeon
crow

C library function strstr() example

#include <stdio.h>
#include <string.h>

int main () {
   const char haystack[20] = "TutorialsRoot";
   const char needle[10] = "Root";
   char *ret;

   ret = strstr(haystack, needle);

   printf("The substring is: %s\n", ret);

   return(0);
}

Output

The substring is: Root

C library function strspn() example

#include <cstring>
#include <iostream>

using namespace std;

int main()
{
   char src[] = "0123456789";
   char dest[] = "190126abqs121kfew";

   size_t length = strspn(dest, src);

   cout << dest << " contains " << length << " initial numbers";
   return 0;
}

Output

190126abqs121kfew contains 6 initial numbers

C library function strrchr() example

#include <stdio.h>
#include <string.h>

int main () {
   int len;
   const char str[] = "http://www.tutorialsroot.com";
   const char ch = '.';
   char *ret;

   ret = strrchr(str, ch);

   printf("String after |%c| is - |%s|\n", ch, ret);
   
   return(0);
}

Output

String after |.| is - |.com|

C library function strpbrk() example

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
   char digits[] = "0123456789";
   char code[] = "ceQasieoLPqa4xz10Iyq";
   char *pos;
   int count = 0;

   pos = strpbrk (code, digits);
   while (pos != NULL)
   {
      pos = strpbrk (pos+1,digits);
      count ++;
   }

   cout << "There are " << count << " numbers in " << code;

   return 0;
}

Output

There are 3 numbers in ceQasieoLPqa4xz10Iyq

C library function strlen() example

#include <stdio.h>
#include <string.h>
int main()
{
   char a[20]="Program";
   char b[20]={'P','r','o','g','r','a','m','\0'};
   char c[20];

   printf("Enter string: ");
   gets(c);

   printf("Length of string a = %d \n",strlen(a));

   //calculates the length of string before null charcter.
   printf("Length of string b = %d \n",strlen(b));
   printf("Length of string c = %d \n",strlen(c));

   return 0;
}

Output

Enter string: String
Length of string a = 7
Length of string b = 7
Length of string c = 6

C library function strerror() example

#include <stdio.h>
#include <string.h>
#include <errno.h>

int main () {
   FILE *fp;

   fp = fopen("file.txt","r");
   if( fp == NULL ) {
      printf("Error: %s\n", strerror(errno));
   }
   
   return(0);
}

Output

Error: No such file or directory

C library function strcspn() example

#include <stdio.h>
#include <stdlib.h>
int main() {
   int size;
   // initializing strings
   char str1[] = "tutorialsroot";
   char str2[] = "kfc";
   // using strcspn() to calculate initial chars
   // before 1st matching chars.
   // returns 3
   size = strcspn(str1, str2);
   printf("The unmatched characters before first matched character : %d\n", size);
}

Output

The unmatched characters before first matched character : 3

C library function strncpy() example

#include <stdio.h>
#include <stdlib.h>

int main () {
   char src[40];
   char dest[12];
  
   memset(dest, '\0', sizeof(dest));
   strcpy(src, "This is tutorialsroot.com");
   strncpy(dest, src, 10);

   printf("Final copied string : %s\n", dest);
   
   return(0);
}

Output

Final copied string : This is tu

C library function strcpy() example

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char str1[10]= "awesome";
    char str2[10];
    char str3[10];

    strcpy(str2, str1);
    strcpy(str3, "well");
    puts(str2);
    puts(str3);

    return 0;
}

Output

awesome
well

C library function strcpy() example

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char str1[10]= "awesome";
    char str2[10];
    char str3[10];

    strcpy(str2, str1);
    strcpy(str3, "well");
    puts(str2);
    puts(str3);

    return 0;
}

Output

awesome
well

C library function strcoll() example

#include <stdio.h>
#include <string.h>

int main () {
   char str1[15];
   char str2[15];
   int ret;

   strcpy(str1, "abc");
   strcpy(str2, "ABC");

   ret = strcoll(str1, str2);

   if(ret > 0) {
      printf("str1 is less than str2");
   } else if(ret < 0) {
      printf("str2 is less than str1");
   } else {
      printf("str1 is equal to str2");
   }
   
   return(0);
}

Output

str1 is less than str2

C library function strncmp() example

#include <stdio.h>
#include <string.h>

int main () {
   char str1[15];
   char str2[15];
   int ret;

   strcpy(str1, "abcdefg");
   strcpy(str2, "ABCDEFG");

   ret = strncmp(str1, str2, 4);

   if(ret < 0) {
      printf("str1 is less than str2");
   } else if(ret > 0) {
      printf("str2 is less than str1");
   } else {
      printf("str1 is equal to str2");
   }
   
   return(0);
}

Output

str2 is less than str1

C library function strcmp() example

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
    int result;

    // comparing strings str1 and str2
    result = strcmp(str1, str2);
    printf("strcmp(str1, str2) = %d\n", result);

    // comparing strings str1 and str3
    result = strcmp(str1, str3);
    printf("strcmp(str1, str3) = %d\n", result);

    return 0;
}

Output

strcmp(str1, str2) = 32
strcmp(str1, str3) = 0

C library function strchr() example

#include <stdio.h>
#include <stdlib.h>

int main () {
   const char str[] = "http://www.tutorialsroot.com";
   const char ch = '.';
   char *ret;

   ret = strchr(str, ch);

   printf("String after |%c| is - |%s|\n", ch, ret);
   
   return(0);
}

Output

String after |.| is - |.tutorialsroot.com|

C library function strncat() example

#include <stdio.h>
#include <stdlib.h>
int main () {
   char src[50], dest[50];

   strcpy(src,  "It is source");
   strcpy(dest, "IT is destination");

   strncat(dest, src, 15);

   printf("Final destination string : |%s|", dest);
   
   return(0);
}

Output

Final destination string : |IT is destinationThis is source|

C library function strcat() example

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char str1[] = "This is ", str2[] = "tutorialsroot.com";

    //concatenates str1 and str2 and resultant string is stored in str1.
    strcat(str1,str2);

    puts(str1);    
    puts(str2); 

    return 0;
}

Output

This is tutorialsroot.com
tutorialsroot.com

C library function memset() example

#include <stdio.h>
#include <stdlib.h>

int main () {
   char str[50];

   strcpy(str,"It is string.h library function");
   puts(str);

   memset(str,'$',7);
   puts(str);
   
   return(0);
}

Output

This is string.h library function
$$$$$$$ string.h library function

C library function memmove() example

#include <stdio.h>
#include <stdlib.h>

int main () {
   char dest[] = "oldstring";
   const char src[]  = "newstring";

   printf("Before memmove dest = %s, src = %s\n", dest, src);
   memmove(dest, src, 9);
   printf("After memmove dest = %s, src = %s\n", dest, src);

   return(0);
}

Output

Before memmove dest = oldstring, src = newstring
After memmove dest = newstring, src = newstring

C library function memcpy() example

#include <stdio.h>
#include <stdlib.h>

int main () {
   const char src[50] = "http://www.tutorialsroot.com";
   char dest[50];
   strcpy(dest,"Hiiii!!");
   printf("Before memcpy dest = %s\n", dest);
   memcpy(dest, src, strlen(src)+1);
   printf("After memcpy dest = %s\n", dest);
   
   return(0);
}

Output

Before memcpy dest =
After memcpy dest = http://www.tutorialsroot.com

C library function memcmp() example

#include <stdio.h>
#include <stdlib.h>

int main () {
   char str1[15];
   char str2[15];
   int ret;

   memcpy(str1, "abcdef", 6);
   memcpy(str2, "ABCDEF", 6);

   ret = memcmp(str1, str2, 5);

   if(ret > 0) {
      printf("str2 is less than str1");
   } else if(ret < 0) {
      printf("str1 is less than str2");
   } else {
      printf("str1 is equal to str2");
   }
   
   return(0);
}

Output

str2 is less than str1

C library function memchr() example

#include <stdio.h>
#include <stdlib.h>

int main () {
   const char str[] = "http://www.tutorialsroot.com";
   const char ch = '.';
   char *ret;

   ret = memchr(str, ch, strlen(str));

   printf("String after |%c| is - |%s|\n", ch, ret);

   return(0);
}

Output

String after |.| is - |.tutorialsroot.com|

C library function wctomb() example

#include <stdio.h>
#include <stdlib.h>

int main () {
   int i;
   wchar_t wc = L'a';
   char *pmbnull = NULL;
   char *pmb = (char *)malloc(sizeof( char ));

   printf("Converting wide character:\n");
   i = wctomb( pmb, wc );
   printf("Characters converted: %u\n", i);
   printf("Multibyte character: %.1s\n", pmb);

   printf("Trying to convert when target is NULL:\n");
   i = wctomb( pmbnull, wc );
   printf("Characters converted: %u\n", i);
   /* this will not print any value */
   printf("Multibyte character: %.1s\n", pmbnull);
   
   return(0);
}

Output

Converting wide character:
Characters converted: 1
Multibyte character: a
Trying to convert when target is NULL:
Characters converted: 0
Multibyte character:

C library function mbtowc() example

#include <stdio.h>
#include <stdlib.h>
int main() 
  {
      char pmb[] = "Welcome to Tutorialaaroot.com";
      wchar_t pwc[100];
      int len, ret_val;
      /* resets internal conversion state */
      mbtowc (NULL, NULL, 0);
      len = strlen(pmb);
      ret_val = mbtowc(pwc, pmb, strlen(pmb));

      cout << "Return Value = " << ret_val << endl;
      wcout << "Wide character string: " << pwc;

      return(0);
   }

Output

Return Value = 1
Wide character string: W@

C library function mbstowcs() example

#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
   {
      char src[] = "\xc4\xe3\xba\xc3";
      wchar_t dest[10];
      int num;
      num = mbstowcs(dest, src, MB_CUR_MAX);
      cout << "Number of wide character converted = " << num << endl;
      wcout << "Wide Character String = " << dest << endl;
      return 0;
   }

Output

Number of wide character converted = 1
Wide Character String = ─

C library function mblen() example

#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
   {
      int len;
      char *s = (char *)malloc(20);
      strcpy(s,"\xe4\xbd\xa0\xe5\xa5\xbd");

      /* resets the conversion state */
      mblen(NULL, 0);
      len = mblen(s,strlen(s));

      cout << "Length of multibyte character: " << len << endl;
      return 0;
   }

Output

Length of multibyte character: 1

C library function srand() example

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main () {
   int i, n;
   time_t t;
   
   n = 5;
   
   srand((unsigned) time(&t));

   for( i = 0 ; i < n ; i++ ) {
      printf("%d\n", rand() % 50);
   }
   
   return(0);
}

Output

38
45
29
29
47

C library function rand() example

#include <stdio.h>
#include <stdlib.h>

int main () {
   int i, n;
   time_t t;
   
   n = 5;
   
   srand((unsigned) time(&t));


   for( i = 0 ; i < n ; i++ ) {
      printf("%d\n", rand() % 50);
   }
   
   return(0);
}

Output

38
45
29
29
47

C library function ldiv() example

#include <stdio.h>
#include <stdlib.h>

int main () {
   ldiv_t output;

   output = ldiv(100000L, 30000L);

   printf("Quotient = %ld\n", output.quot);

   printf("Remainder = %ld\n", output.rem);
   
   return(0);
}

Output

Quotient = 3
Remainder = 10000

C library function labs() example

#include <stdio.h>
#include <stdlib.h>
int main()
{
   float num, root;
   printf("Enter a number: ");
   scanf("%f", &num);
   // Computes the square root of num and stores in root.
   root = sqrt(num);
   printf("Square root of %.2f = %.2f", num, root);
   return 0;
}

Output

Enter a number: 12
Square root of 12.00 = 3.46