Happy Codings - Programming Code Examples
Html Css Web Design Sample Codes CPlusPlus Programming Sample Codes JavaScript Programming Sample Codes C Programming Sample Codes CSharp Programming Sample Codes Java Programming Sample Codes Php Programming Sample Codes Visual Basic Programming Sample Codes

C Programming Code Examples

C > Beginners Lab Assignments Code Examples

setlocale: set local information

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/* setlocale: set local information */ //Declaration: char *setlocale(int type, const char *locale); //type must be one of the following macros (defined in <locale.h>): //LC_ALL: refers to all localization categories. //LC_COLLATE: affects the operation of the strcoll() function. //LC_CTYPE: alters the way the character functions work. //LC_MONETARY: determines the monetary format. //LC_NUMERIC: changes the decimal-point character for formatted input/output functions. //LC_TIME: determines the behavior of the strftime() function. #include <locale.h> #include <stdio.h> int main(void) { printf(setlocale(LC_ALL, "")); printf("Happy Codings - C Programming Language Code Examples"); return 0; }
strftime() Function in C
Format time as string. Copies into ptr the content of format, expanding its format specifiers into the corresponding values that represent the time described in timeptr, with a limit of maxsize characters. strftime() is a function in C which is used to format date and time. It comes under the header file time.h, which also contains a structure named struct tm which is used to hold the time and date.
Syntax for strftime() Function in C
#include <time.h> size_t strftime (char* ptr, size_t maxsize, const char* format, const struct tm* timeptr );
Pointer to the destination array where the resulting C string is copied.
Maximum number of characters to be copied to ptr, including the terminating null-character.
C string containing any combination of regular characters and special format specifiers. These format specifiers are replaced by the function to the corresponding values to represent the time specified in timeptr.
Abbreviated weekday name (Example: Sun)
Full weekday name (Example: Sunday)
Abbreviated month name (Example: Mar)
Full month name (Example: March)
Date and time representation (Example: Sun Aug 19 02:56:02 2012)
Day of the month (01-31) (Example: 19)
Hour in 24h format (00-23) (Example: 14)
Hour in 12h format (01-12) (Example: 05)
Day of the year (001-366) (Example: 231)
Month as a decimal number (01-12) (Example: 08)
Minute (00-59) (Example: 55)
AM or PM designation (Example: PM)
Second (00-61) (Example: 02)
Week number with the first Sunday as the first day of week one (00-53) (Example: 33)
Weekday as a decimal number with Sunday as 0 (0-6) (Example: 4)
Week number with the first Monday as the first day of week one (00-53) (Example: 34)
Date representation (Example: 08/19/12)
Time representation (Example: 02:50:06)
Year, last two digits (00-99) (Example: 01)
Year (Example: 2012)
Timezone name or abbreviation (Example: CDT)
A % sign (Example: %)
Pointer to a tm structure that contains a calendar time broken down into its components (see struct tm).
struct tm { int tm_sec; /* seconds, range 0 to 59 */ int tm_min; /* minutes, range 0 to 59 */ int tm_hour; /* hours, range 0 to 23 */ int tm_mday; /* day of the month, range 1 to 31 */ int tm_mon; /* month, range 0 to 11 */ int tm_year; /* The number of years since 1900 */ int tm_wday; /* day of the week, range 0 to 6 */ int tm_yday; /* day in the year, range 0 to 365 */ int tm_isdst; /* daylight saving time */ };
If the length of the resulting C string, including the terminating null-character, doesn't exceed maxsize, the function returns the total number of characters copied to ptr (not including the terminating null-character). Otherwise, it returns zero, and the contents of the array pointed by ptr are indeterminate.
Particular library implementations may support additional specifiers or combinations. Those listed here are supported by the latest C and C++ standards (both published in 2011), but those in yellow were introduced in C99 (only required for C++ implementations since C++11), and may not be supported by libraries that comply with older standards.
Data races
The function accesses the array pointed by format and the object pointed by timeptr. On success, it also modifies the elements in the array pointed by ptr. Concurrently changing locale settings may also introduce data races.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/* convert date and time to a string by strftime() function example */ // C program to demonstrate the working of strftime() #include <stdlib.h> #include <stdio.h> #include <time.h> #define Size 50 int main () { time_t t ; struct tm *tmp ; char MY_TIME[Size]; time( &t ); //localtime() uses the time pointed by t , // to fill a tm structure with the // values that represent the // corresponding local time. tmp = localtime( &t ); // using strftime to display time strftime(MY_TIME, sizeof(MY_TIME), "%x - %I:%M%p", tmp); printf("Formatted date & time : %s\n", MY_TIME ); return(0); }
main() Function in C
In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined. main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed. Its first function or entry point of the program from where program start executed, program's execution starts from the main. So main is an important function in c , c++ programming language.
Syntax for main() Function in C
void main() { ......... // codes start from here ......... }
is a keyword in C language, void means nothing, whenever we use void as a function return type then that function nothing return. here main() function no return any value. In place of void we can also use int return type of main() function, at that time main() return integer type value.
is a name of function which is predefined function in C library. • An operating system always calls the main() function when a programmers or users execute their programming code. • It is responsible for starting and ends of the program. • It is a universally accepted keyword in programming language and cannot change its meaning and name. • A main() function is a user-defined function in C that means we can pass parameters to the main() function according to the requirement of a program. • A main() function is used to invoke the programming code at the run time, not at the compile time of a program. • A main() function is followed by opening and closing parenthesis brackets.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/* basic c program by main() function example */ #include <stdio.h> #include <conio.h> main() { printf (" It is a main() function "); int fun2(); // jump to void fun1() function printf ("\n Finally exit from the main() function. "); } void fun1() { printf (" It is a second function. "); printf (" Exit from the void fun1() function. "); } int fun2() { void fun1(); // jump to the int fun1() function printf (" It is a third function. "); printf (" Exit from the int fun2() function. "); return 0; }
time() Function in C
The time() function is defined in time.h header file. This function returns the time since 00:00:00 UTC, January 1, 1970 (Unix timestamp) in seconds. If second is not a null pointer, the returned value is also stored in the object pointed to by second.
Syntax for time() Function in C
#include <time.h> time_t time( time_t *second )
This function accepts single parameter second. This parameter is used to set the time_t object which store the time. This function returns current calender time as a object of type time_t. It is used to get current system time as structure. time() function is a useful utility function that we can use to measure the elapsed time of our program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
/* return the time since 00:00:00 UTC, January 1, 1970 by time() function example */ #include <time.h> #include <stdlib.h> #include <stdio.h> int main(void) { time_t current_time; char* c_time_string; /* Obtain current time. */ current_time = time(NULL); if (current_time == ((time_t)-1)) { (void) fprintf(stderr, "Failure to obtain the current time.\n"); exit(EXIT_FAILURE); } /* Convert to local time format. */ c_time_string = ctime(¤t_time); if (c_time_string == NULL) { (void) fprintf(stderr, "Failure to convert the current time.\n"); exit(EXIT_FAILURE); } /* Print to stdout. ctime() has already added a terminating newline character. */ (void) printf("Current time is %s", c_time_string); exit(EXIT_SUCCESS); }
printf() Function in C
Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. printf format string refers to a control parameter used by a class of functions in the input/output libraries of C programming language. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such as a number) to characters. "printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers, but are sufficient for many purposes.
Syntax for printf() function in C
#include <stdio.h> int printf ( const char * format, ... );
C string that contains the text to be written to stdout. It can optionally contain embedded format specifiers that are replaced by the values specified in subsequent additional arguments and formatted as requested. A format specifier follows this prototype: [see compatibility note below] %[flags][width][.precision][length]specifier Where the specifier character at the end is the most significant component, since it defines the type and the interpretation of its corresponding argument:
a conversion format specifier.
d or i
Signed decimal integer
Unsigned decimal integer
Unsigned octal
Unsigned hexadecimal integer
Unsigned hexadecimal integer (uppercase)
Decimal floating point, lowercase
Decimal floating point, uppercase
Scientific notation (mantissa/exponent), lowercase
Scientific notation (mantissa/exponent), uppercase
Use the shortest representation: %e or %f
Use the shortest representation: %E or %F
Hexadecimal floating point, lowercase
Hexadecimal floating point, uppercase
String of characters
Pointer address
Nothing printed. The corresponding argument must be a pointer to a signed int. The number of characters written so far is stored in the pointed location.
A % followed by another % character will write a single % to the stream. The format specifier can also contain sub-specifiers: flags, width, .precision and modifiers (in that order), which are optional and follow these specifications:
one or more flags that modifies the conversion behavior (optional)
Left-justify within the given field width; Right justification is the default (see width sub-specifier).
Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.
If no sign is going to be written, a blank space is inserted before the value.
Used with o, x or X specifiers the value is preceeded with 0, 0x or 0X respectively for values different than zero. Used with a, A, e, E, f, F, g or G it forces the written output to contain a decimal point even if no more digits follow. By default, if no digits follow, no decimal point is written.
Left-pads the number with zeroes (0) instead of spaces when padding is specified (see width sub-specifier).
an optional * or integer value used to specify minimum width field.
Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.
The width is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
an optional field consisting of a . followed by * or integer or nothing to specify the precision.
For integer specifiers (d, i, o, u, x, X): precision specifies the minimum number of digits to be written. If the value to be written is shorter than this number, the result is padded with leading zeros. The value is not truncated even if the result is longer. A precision of 0 means that no character is written for the value 0. For a, A, e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). For g and G specifiers: This is the maximum number of significant digits to be printed. For s: this is the maximum number of characters to be printed. By default all characters are printed until the ending null character is encountered. If the period is specified without an explicit value for precision, 0 is assumed.
The precision is not specified in the format string, but as an additional integer value argument preceding the argument that has to be formatted.
an optional length modifier that specifies the size of the argument.
... (additional arguments)
Depending on the format string, the function may expect a sequence of additional arguments, each containing a value to be used to replace a format specifier in the format string (or a pointer to a storage location, for n). There should be at least as many of these arguments as the number of values specified in the format specifiers. Additional arguments are ignored by the function. If a writing error occurs, the error indicator (ferror) is set and a negative number is returned. If a multibyte character encoding error occurs while writing wide characters, errno is set to EILSEQ and a negative number is returned.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
/* print formatted data to stdout by printf() function example */ #include <stdio.h> int main() { char ch; char str[100]; int a; float b; printf("Enter any character \n"); scanf("%c", &ch); printf("Entered character is %c \n", ch); printf("Enter any string ( upto 100 character ) \n"); scanf("%s", &str); printf("Entered string is %s \n", str); printf("Enter integer and then a float: "); // Taking multiple inputs scanf("%d%f", &a, &b); printf("You entered %d and %f", a, b); return 0; }
strcoll() Function in C
Compare two strings using locale. Compares the C string str1 to the C string str2, both interpreted appropriately according to the LC_COLLATE category of the C locale currently selected. This function starts comparing the first character of each string. If they are equal to each other continues with the following pair until the characters differ or until a null-character signaling the end of a string is reached. The behavior of this function depends on the LC_COLLATE category of the selected C locale.
Syntax for strcoll() Function in C
#include <string.h> int strcoll ( const char * str1, const char * str2 );
C string to be compared.
C string to be compared. Function strcoll() takes two strings as parameters and returns an integer value. Returns an integral value indicating the relationship between the strings: A zero value indicates that both strings are equal. A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite. The strcoll() function may fail if: [EINVAL] The str1 or str2 arguments contain characters outside the domain of the collating sequence.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/* compare two strings using locale by strcoll() string function code example */ // C program to illustrate strcoll() #include <stdio.h> #include <string.h> int main() { char str1[13]; char str2[13]; int ret; strcpy(str1, "HappyCodings"); strcpy(str2, "HappyCodings"); ret = strcoll(str1, str2); if (ret > 0) { printf("str1 is greater than str2"); } else if (ret < 0) { printf("str1 is lesser than str2"); } else { printf("str1 is equal to str2"); } return (0); }
#include Directive in C
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program. Here are the two types of file that can be included using #include: • Header File or Standard files: This is a file which contains C/C++ function declarations and macro definitions to be shared between several source files. Functions like the printf(), scanf(), cout, cin and various other input-output or other standard functions are contained within different header files. So to utilise those functions, the users need to import a few header files which define the required functions. • User-defined files: These files resembles the header files, except for the fact that they are written and defined by the user itself. This saves the user from writing a particular function multiple times. Once a user-defined file is written, it can be imported anywhere in the program using the #include preprocessor.
Syntax for #include Directive in C
#include "user-defined_file"
Including using " ": When using the double quotes(" "), the preprocessor access the current directory in which the source "header_file" is located. This type is mainly used to access any header files of the user's program or user-defined files.
#include <header_file>
Including using <>: While importing file using angular brackets(<>), the the preprocessor uses a predetermined directory path to access the file. It is mainly used to access system header files located in the standard system directories.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
/* #include directive tells the preprocessor to insert the contents of another file into the source code at the point where the #include directive is found. */ // C program to illustrate file inclusion // <> used to import system header file #include <stdio.h> // " " used to import user-defined file #include "process.h" // main function int main() { // add function defined in process.h add(10, 20); // mult function defined in process.h multiply(10, 20); // printf defined in stdio.h printf("Process completed"); return 0; }
setlocale() Function in C
Set or retrieve locale. Sets locale information to be used by the current program, either changing the entire locale or portions of it. The function can also be used to retrieve the current locale's name by passing NULL as the value for argument locale. Locales contain information on how to interpret and perform certain input/output and transformation operations taking into consideration location and language specific settings. Most running environments have certain locale information set according to the user preferences or localization. But, independently of this system locale, on start, all C programs have the "C" locale set, which is a rather neutral locale with minimal locale information that allows the result of programs to be predictable. In order to use the default locale set in the environment, this function can be called with "" as argument locale. On program startup, the locale selected is the "C" locale, which is the same as would be set by calling setlocale(LC_ALL,"C"). The locale settings selected in the environment can be selected by calling setlocale(LC_ALL,""). The portions of the current locale affected by a call to this function are specified by argument category.
Syntax for setlocale() Function in C
#include <locale.h> char* setlocale (int category, const char* locale);
Portion of the locale affected. It is one of the following constant values defined as macros in :
Selects all the C locale
Selection the collation category
Selects the character classification category
Selects the monetary formatting category
Selects the numeric formatting category
Selects the time formatting category
specify the language to be used for messages.
C string containing the name of a C locale. These are system specific, but at least the two following locales must exist:
Minimal "C" locale
Environment's default locale If the value of this parameter is NULL, the function does not make any changes to the current locale, but the name of the current locale is still returned by the function. On success, function returns a pointer to a C string identifying the locale currently set for the category. If category is LC_ALL and different portions of the locale are set to different values, the string returned gives this information in a format which may vary between library implementations. If the function failed to set a new locale, this is not modified and a null pointer is returned.
Data races
Changing locale settings may introduce data races with concurrent calls to the same function or to any C-library function affected by the locale.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
/* set or retrieve locale by setlocale() function code example */ #include <stdio.h> #include <locale.h> int main(int argc, const char * argv[]) { /* Define a temporary variable */ struct lconv *loc; /* Set the locale to the POSIX C environment */ setlocale (LC_ALL, "C"); /* Retrieve a pointer to the current locale */ loc = localeconv(); /* Display some of the locale settings */ printf("Thousands Separator: %s\n", loc->thousands_sep); printf("Currency Symbol: %s\n", loc->currency_symbol); /* Set the locale to the environment default */ setlocale (LC_ALL, ""); /* Retrieve a pointer to the current locale */ loc = localeconv(); /* Display some of the locale settings */ printf("Thousands Separator: %s\n", loc->thousands_sep); printf("Currency Symbol: %s\n", loc->currency_symbol); return 0; }

Find number of Days in a Month using switch case - best approach. Lets Observe the above program carefully for a moment. In the above program we are performing same action on...
Check whether a number is divisible by 5 and 13 or not using if else. A number is divisible by some other number if it gives 0 as remainder. To check if a number is exactly divisible by a...
C program input two numbers and perform all arithmetic operations. How to perform all arithmetic operation between two numbers in C programming. C program to find sum,...
This C Program implements a Selection Sort. 'Selection Sort' works by finding the smallest unsorted item in the list and swapping it with the item in the current position. It is used for
C Program implements selection sort method using functions. 'Selection' Sort is among the simplest of Sorting Techniques. Lets first find the smallest in the array and exchange it with
This program takes string and its substring as input, removes the Substring from the string. Take a string, its substring as input and Store it in the array str[] & key[] respectively. Store
Program input a number and check whether the number is Perfect number or not. Perfect number is a positive integer which is equal to the sum of its proper positive divisors. So 6 is
Read elements in a matrix and find the sum of main diagonal (major diagonal) elements of matrix. Find sum of all elements of main diagonal of a matrix. Input elements in the