C – Unit I

UNIT 1:  FUNDAMENTALS CONCEPTS IN C PROGRAMMING

 

1.1 C FUNDAMENTALS CHARACTER SET

As every language contains a set of characters used to construct words, statements etc., C language also has a set of characters which include alphabets, digits and special symbols.

Every C program contains statements. These statements are constructed using words and these words are constructed using characters from C character set. C language character set contains the following set of characters…

  1. Alphabets
  2. Digits
  3. Special Symbols

 

Alphabets

C language supports all the alphabets from english language. Lower and upper case letters together supports 52 alphabets.

lower case letters – a to z

UPPER CASE LETTERS – A to Z

 

Digits

C language supports 10 digits which are used to construct numerical values in C language.

Digits – 0, 1, 2, 3, 4, 5, 6, 7, 8, 9

 

Special Symbols

C language supports rich set of special symbols that include symbols to perform mathematical operations, to check conditions, white spaces, back spaces and other special symbols.

Special Symbols – ~ @ # $ % ^ & * ( ) _ – + = { } [ ] ; : ‘ ” / ? . > , < \ | tab newline space NULL bell backspace verticaltab etc.,

Every character in C language has its equivalent ASCII (American Standard Code for Information Interchange) value.

 

 

Commonly used characters in C with thier ASCII values

C program to print all the characters of C character Set

 

#include<stdio.h>

#include<conio.h>

int main() {

int i;

clrscr();

printf(“ASCII  ==>  Character\n”);

for(i = -128; i <= 127; i++)

printf(“%d    ==>     %c\n”, i, i);

getch();

return 0;

}

 

1.2 IDENTIFIERS AND KEYWORDS

 

Keywords are predefined, reserved words used in programming that have special meanings to the compiler. Keywords are part of the syntax and they cannot be used as an identifier. For example:

int money;

Here, int is a keyword that indicates ‘money’ is a variable of type integer.

As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all keywords allowed in ANSI C.

 

Keywords in C Language
auto double int struct
break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static while
default goto sizeof volatile
const float short unsigned

 

Along with these keywords, C supports other numerous keywords depending upon the compiler.

All these keywords, their syntax and application will be discussed in their respective topics. However, if you want a brief overview on these keywords without going further, visit list of all keywords in C programming.

 

Identifier refers to name given to entities such as variables, functions, structures etc.

Identifier must be unique. They are created to give unique name to a entity to identify it during the execution of the program. For example:

int money;

double accountBalance;

Here, money and accountBalance are identifiers.

Also remember, identifier names must be different from keywords. You cannot use int as an identifier because int is a keyword.

 

Rules for writing an identifier

  1. A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.
  2. The first letter of an identifier should be either a letter or an underscore. However, it is discouraged to start an identifier name with an underscore.
  3. There is no rule on length of an identifier. However, the first 31 characters of identifiers are discriminated by the compiler.

 

1.3 DATATYPES

 

Data types in c refer to an extensive system used for declaring variables or functions of different types. The type of a variable determines how much space it occupies in storage and how the bit pattern stored is interpreted.

The types in C can be classified as follows −

Sr.No. Types & Description
1 Basic Types

They are arithmetic types and are further classified into: (a) integer types and (b) floating-point types.

2 Enumerated types

They are again arithmetic types and they are used to define variables that can only assign certain discrete integer values throughout the program.

3 The type void

The type specifier void indicates that no value is available.

4 Derived types

They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union types and (e) Function types.

 

 

 

Integer Types

 

The following table provides the details of standard integer types with their storage sizes and value ranges −

Type Storage size Value range
char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 4 bytes -2,147,483,648 to 2,147,483,647
unsigned long 4 bytes 0 to 4,294,967,295

 

To get the exact size of a type or a variable on a particular platform, you can use the sizeof operator. The expressions sizeof(type) yields the storage size of the object or type in bytes. Given below is an example to get the size of int type on any machine −

#include <stdio.h>

#include <limits.h>

 

int main() {

printf(“Storage size for int : %d \n”, sizeof(int));

 

return 0;

}

When you compile and execute the above program, it produces the following result on Linux −

Storage size for int : 4

 

 

 

Floating-Point Types

The following table provide the details of standard floating-point types with storage sizes and value ranges and their precision −

Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

 

The header file float.h defines macros that allow you to use these values and other details about the binary representation of real numbers in your programs. The following example prints the storage space taken by a float type and its range values −

 

#include <stdio.h>

#include <float.h>

 

int main() {

printf(“Storage size for float : %d \n”, sizeof(float));

printf(“Minimum float positive value: %E\n”, FLT_MIN );

printf(“Maximum float positive value: %E\n”, FLT_MAX );

printf(“Precision value: %d\n”, FLT_DIG );

 

return 0;

}

 

When you compile and execute the above program, it produces the following result on Linux −

Storage size for float : 4

Minimum float positive value: 1.175494E-38

Maximum float positive value: 3.402823E+38

Precision value: 6

 

 

 

The void Type

The void type specifies that no value is available. It is used in three kinds of situations −

Sr.No. Types & Description
1 Function returns as void

There are various functions in C which do not return any value or you can say they return void. A function with no return value has the return type as void. For example, void exit (int status);

2 Function arguments as void

There are various functions in C which do not accept any parameter. A function with no parameter can accept a void. For example, int rand(void);

3 Pointers to void

A pointer of type void * represents the address of an object, but not its type. For example, a memory allocation function void *malloc( size_t size ); returns a pointer to void which can be casted to any data type.

 

1.4 CONSTANTS

 

As the name suggests the name constants is given to such variables or values in C programming language which cannot be modified once they are defined. They are fixed values in a program. There can be any types of constants like integer, float, octal, hexadecimal, character constants etc. Every constant has some range. The integers that is too big to fit into an int will be taken as a long. Now there are various ranges that differ from unsigned to signed bits. Under signed bit the range of an int, varies from -128 to +127 and under unsigned bit int varies from 0 to 255.

In C program we can define constants in two ways as shown below:

  1. using #define preprocessor directive
  2. using a const keyword.

 

Let us now learn about above two ways in details:

  • using #define preprocessor directive : This directive used to declare an alias name for existing variable or any value. We can use this to declare a constant as shown below:
  • #define identifierName value

where identifierName is the name given to constant and value is any value assigned to it.

 

Below is the C program to explain how to use #define to declare constants:

#include<stdio.h>

#define val  10

#define floatVal  4.5

#define charVal ‘G’

 

int main()

{

printf(“Integer Constant: %d\n”,val);

printf(“Floating point Constant: %f\n”,floatVal);

printf(“Character Constant: %c\n”,charVal);

 

return 0;

}

 

Output:

Integer Constant: 10

Floating point Constant: 4.500000

Character Constant: G

 

using a const keyword: Using const keyword to define constants is as simple as defining variables, the difference is you will have to precede the definition with a const keyword. Below program shows how to use const to declare costants of different data types:

 

#include <stdio.h>

 

int main()

{

const int intVal = 10; // int constant

const float floatVal = 4.14; // Real constant

const char charVal = ‘A’; // char constant

const char stringVal[10] = “ABC”; // string constant

 

printf(“Integer constant :%d \n”, intVal );

printf(“Floating point constant : %f \n”, floatVal );

printf(“Character constant : %c \n”, charVal );

printf(“String constant : %s \n”, stringVal);

 

return 0;

}

 

Output:

Integer constant :10

Floating point constant : 4.140000

Character constant : A

String constant : ABC

 

String Literals : When string value is directly assigned to a pointer, in most of the compilers, it’s stored in a read only block (generally in data segment) that is shared among functions.

char *str  =  “GfG”;

 

In the above line “GfG” is stored in a read only location, but pointer str is stored in a read-write memory. You can change str to point something else but cannot change value at present str. So this kind of string should only be used when we don’t want to modify string at a later stage in program.

 

The below program may crash (gives segmentation fault error) because the line *(str+1) = ‘n’ tries to write a read only memory.

int main()

{

char *str;

 

/* Stored in read only part of data segment */

str = “GfG”;

 

/* Problem:  trying to modify read only memory */

*(str+1) = ‘n’;

return 0;

}

 

1.5 VARIABLES

 

A variable is nothing but a name given to a storage area that our programs can manipulate. Each variable in C has a specific type, which determines the size and layout of the variable’s memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.

 

S.No. Type & Description
1 char

Typically a single octet(one byte). This is an integer type.

2 int

The most natural size of integer for the machine.

3 float

A single-precision floating point value.

4 double

A double-precision floating point value.

5 void

Represents the absence of type.

 

C programming language also allows to define various other types of variables, which we will cover in subsequent chapters like Enumeration, Pointer, Array, Structure, Union, etc. For this chapter, let us study only basic variable types.

 

Variable Definition in C

A variable definition tells the compiler where and how much storage to create for the variable. A variable definition specifies a data type and contains a list of one or more variables of that type as follows −

type variable_list;

 

Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any user-defined object; and variable_list may consist of one or more identifier names separated by commas. Some valid declarations are shown here −

int    i, j, k;

char   c, ch;

float  f, salary;

double d;

 

The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to create variables named i, j and k of type int.

 

Variables can be initialized (assigned an initial value) in their declaration. The initializer consists of an equal sign followed by a constant expression as follows −

type variable_name = value;

 

Some examples are −

extern int d = 3, f = 5;    // declaration of d and f.

int d = 3, f = 5;           // definition and initializing d and f.

byte z = 22;                // definition and initializes z.

char x = ‘x’;               // the variable x has the value ‘x’.

For definition without an initializer: variables with static storage duration are implicitly initialized with NULL (all bytes have the value 0); the initial value of all other variables are undefined.

 

Variable Declaration in C

A variable declaration provides assurance to the compiler that there exists a variable with the given type and name so that the compiler can proceed for further compilation without requiring the complete detail about the variable. A variable definition has its meaning at the time of compilation only, the compiler needs actual variable definition at the time of linking the program.

A variable declaration is useful when you are using multiple files and you define your variable in one of the files which will be available at the time of linking of the program. You will use the keyword extern to declare a variable at any place. Though you can declare a variable multiple times in your C program, it can be defined only once in a file, a function, or a block of code.

 

Example

Try the following example, where variables have been declared at the top, but they have been defined and initialized inside the main function −

 

#include <stdio.h>

 

// Variable declaration:

extern int a, b;

extern int c;

extern float f;

 

int main () {

 

/* variable definition: */

int a, b;

int c;

float f;

 

/* actual initialization */

a = 10;

b = 20;

 

c = a + b;

printf(“value of c : %d \n”, c);

 

f = 70.0/3.0;

printf(“value of f : %f \n”, f);

 

return 0;

}

 

When the above code is compiled and executed, it produces the following result −

value of c : 30

value of f : 23.333334

 

The same concept applies on function declaration where you provide a function name at the time of its declaration and its actual definition can be given anywhere else. For example −

// function declaration

int func();

 

int main() {

 

// function call

int i = func();

}

 

// function definition

int func() {

return 0;

}

 

Lvalues and Rvalues in C

There are two kinds of expressions in C −

  • lvalue − Expressions that refer to a memory location are called “lvalue” expressions. An lvalue may appear as either the left-hand or right-hand side of an assignment.
  • rvalue − The term rvalue refers to a data value that is stored at some address in memory. An rvalue is an expression that cannot have a value assigned to it which means an rvalue may appear on the right-hand side but not on the left-hand side of an assignment.

Variables are lvalues and so they may appear on the left-hand side of an assignment. Numeric literals are rvalues and so they may not be assigned and cannot appear on the left-hand side. Take a look at the following valid and invalid statements −

int g = 20; // valid statement

 

10 = 20; // invalid statement; would generate compile-time error

 

1.6 DECLARATIONS

 

In computer programming, a declaration is a language construct that specifies properties of an identifier: it declares what a word (identifier) “means”. Declarations are most commonly used for functions, variables, constants, and classes, but can also be used for other entities such as enumerations and type definitions. Beyond the name (the identifier itself) and the kind of entity (function, variable, etc.), declarations typically specify the data type (for variables and constants), or the type signature (for functions); types may also include dimensions, such as for arrays. A declaration is used to announce the existence of the entity to the compiler; this is important in those strongly typed languages that require functions, variables, and constants, and their types to be specified with a declaration before use and is used in forward declaration. The term “declaration” is frequently contrasted with the term “definition” but meaning and usage varies significantly between languages; see below.

 

Declarations are particularly prominent in languages in the ALGOL tradition, including the BCPL family, most prominently C and C++, and also Pascal. Java uses the term “declaration”, though Java does not have separate declarations and definitions.

 

In the C-family of programming languages, declarations are often collected into header files, which are included in other source files that reference and use these declarations, but don’t have access to the definition. The information in the header file provides the interface between code that uses the declaration and that which defines it, a form of information hiding. A declaration is often used in order to access functions or variables defined in different source files, or in a library. A mismatch between the definition type and the declaration type generates a compiler error.

 

For variables, definitions assign values to an area of memory that was reserved during the declaration phase. For functions, definitions supply the function body. While a variable or function may be declared many times, it is typically defined once (in C++, this is known as the One Definition Rule or ODR).

 

Dynamic languages such as JavaScript or Python generally allow functions to be redefined, that is, re-bound; a function is a variable much like any other, with a name and a value (the definition).

 

Here are some examples of declarations that are not definitions, in C:

 

extern char example1;

extern int example2;

void example3(void);

Here are some examples of declarations that are definitions, again in C:

char example1; /* Outside of a function definition it will be initialized to zero.  */

int example2 = 5;

void example3(void) { /* definition between braces */ }

 

1.7 EXPRESSIONS

 

  1. In programming, an expression is any legal combination of symbols that represents a value.
  2. C Programming Provides its own rules of Expression, whether it is legal expression or illegal expression. For example, in the C language x+5 is a legal expression.
  3. Every expression consists of at least one operand and can have one or more operators.
  4. Operands are values and Operators are symbols that represent particular actions.

 

Valid C Programming Expression :

 

C Programming code gets compiled firstly before execution. In the different phases of compiler, c programming expression is checked for its validity.

 

Expressions Validity
a + b Expression is valid since it contain + operator which is binary operator
+ + a + b Invalid Expression

 

Priority and Expression :

In order to solve any expression we should have knowledge of C Programming Operators and their priorities.

 

Types of Expression :

In Programming, different verities of expressions are given to the compiler. Expressions can be classified on the basis of Position of Operators in an expression –

Type Explanation Example
Infix Expression in which Operator is in between Operands a + b
Prefix Expression in which Operator is written before Operands + a b
Postfix Expression in which Operator is written after Operands a b +

These expressions are solved using the stack.

 

1.8 STATEMENTS

 

The statements of a C program, control the flow of program execution. In C language several kinds of statements are available. They are

 

1.9 ARITHMETIC OPERATOR

 

The following table shows all the arithmetic operators supported by the C language. Assume variable A holds 10 and variable B holds 20, then –

 

Operator Description Example
+ Adds two operands. A + B = 30
Subtracts second operand from the first. A − B = -10
* Multiplies both operands. A * B = 200
/ Divides numerator by de-numerator. B / A = 2
% Modulus Operator and remainder of after an integer division. B % A = 0
++ Increment operator increases the integer value by one. A++ = 11
Decrement operator decreases the integer value by one. A– = 9

 

Example

Try the following example to understand all the arithmetic operators available in C −

#include <stdio.h>

 

main() {

 

int a = 21;

int b = 10;

int c ;

 

c = a + b;

printf(“Line 1 – Value of c is %d\n”, c );

 

c = a – b;

printf(“Line 2 – Value of c is %d\n”, c );

 

c = a * b;

printf(“Line 3 – Value of c is %d\n”, c );

 

c = a / b;

printf(“Line 4 – Value of c is %d\n”, c );

 

c = a % b;

printf(“Line 5 – Value of c is %d\n”, c );

 

c = a++;

printf(“Line 6 – Value of c is %d\n”, c );

 

c = a–;

printf(“Line 7 – Value of c is %d\n”, c );

}

 

When you compile and execute the above program, it produces the following result −

Line 1 – Value of c is 31

Line 2 – Value of c is 11

Line 3 – Value of c is 210

Line 4 – Value of c is 2

Line 5 – Value of c is 1

Line 6 – Value of c is 21

Line 7 – Value of c is 22

 

1.10 UNARY OPERATOR

 

A unary operator, in C#, is an operator that takes a single operand in an expression or a statement. The unary operators in C# are +, -,!, ~, ++, — and the cast operator.

The signature of the declaration of a unary operator includes the operator token and the type of parameter; it does not require the return type and the name of the parameter.

 

All the C# unary operators have predefined implementation that will be used by default in an expression. These unary operators can be overloaded in user-defined types with custom implementation by defining static member functions using the “operator” keyword.

 

The list of unary operators with their details includes:

 

  • Unary Plus Operator (+): The result of an operation on a numeric type is the value of the operand itself. This operator has been predefined for all numeric types.
  • Unary Minus Operator (-): This operator can be used to negate numbers of the integer, floating-point and decimal type.
  • Logical Complement (negation) Operator (!): This operator can be used only with operands of Boole type.
  • Bitwise Complement (negation) Operator (~): This operator can be used with integer, unit, long and ulong operand types. The result of the operation is a bitwise complement (inverse of the binary representation) of the operand.
  • Prefix Increment (++) and Decrement (–) Operator: The operand can be a variable, property access, or an indexer access. With an increment operator, the result of the operation for operands of integer type would be the value incremented by 1. With a decrement operator, the result would be the value decremented by 1 from the operand. The increment/decrement operator can also be used with postfix notation
  • Cast Operator: Used to build cast expressions for conversion to a given type. This operator is represented by the symbol, “T,” where T is the type to which the operand or the result of the expression must be converted

 

1.11 RELATIONS AND LOGICAL OPERATOR

 

  • The relational operators are binary operators — they work between two values
  • The relational operators and their meanings:

 

== equal to

>  greater than

>= greater than or equal

<  less than

<= less than or equal

!= not equal to

 

Use of the Relational Operators

  • A relational operator tests data values against one another
  • You can only compare similar data types. (It makes no sense to compare a char to a float.)
  • All relational operators return either a 1 (meaning true) or a 0 (false.)
  • You will use the relational operators to test whether a condition is true or false and act accordingly.

 

Some Examples

  • Given the following C declarations:

int a =1, b = 2, c = 3, d = 1;

  • a == d is true
  • c > b is true
  • c >= b is true
  • a >= c is false
  • a != d is false
  • a <= d is true
  • Be sure to use the double equal sign (= =) when testing for equality.
  • If you use the assignment operator (=) by mistake, C will accept that assignment as valid and test the result as false (zero) or true (non-zero).

 

One use of relational operators

commission = 0.10*sales + (sales > 1000.00) * 0.05 * (sales – 1000.00);

 

In this example, a sales person is paid a commission of 10% on the first $1000 of sales and an extra 5% on sales above $1000

This code uses a “trick” to code what would normally be a few lines with one line

Strive to maintain readability instead of getting the shortest code possible

Example:  Printing the results of relational operators.

Logical Operators

 

  • You can combine relational operators using logical operators
  • C’s logical operators are:
  • && (AND) returns true if and only if both operands are true
  • || (OR) returns true if one or both operands are true
  • ! (NOT) returns true if operand is false and false if operand is true

 

Precedence of operators

 

  • (dept < 1 || dept > 5) is interpreted as ((dept < 1)||(dept > 5))
  • The relational operators have higher precedence that the logical operators
  • It is usually best to include the extra parentheses

 

Using logical operators

 

if ( x == 0 || x == 1)
{

do one thing

}
else
{

do another thing

}

 

  • Important: don’t say

if (x == 0 || 1) // why not???

  • Don’t overuse the ! operator
  • Better to say (x >= y) than !(x < y)
  • Use if for a simple decision, if-else if you need to determine one of two course of action, and logical operators if you need to combine two or more relational operators

 

1.12 ASSIGNMENT OPERATOR

 

The following table lists the assignment operators supported by the C language –

 

Operator Description Example
= Simple assignment operator. Assigns values from right side operands to left side operand C = A + B will assign the value of A + B to C
+= Add AND assignment operator. It adds the right operand to the left operand and assign the result to the left operand. C += A is equivalent to C = C + A
-= Subtract AND assignment operator. It subtracts the right operand from the left operand and assigns the result to the left operand. C -= A is equivalent to C = C – A
*= Multiply AND assignment operator. It multiplies the right operand with the left operand and assigns the result to the left operand. C *= A is equivalent to C = C * A
/= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A
%= Modulus AND assignment operator. It takes modulus using two operands and assigns the result to the left operand. C %= A is equivalent to C = C % A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

 

 

 

Example

Try the following example to understand all the assignment operators available in C −

 

#include <stdio.h>

 

main() {

 

int a = 21;

int c ;

 

c =  a;

printf(“Line 1 – =  Operator Example, Value of c = %d\n”, c );

 

c +=  a;

printf(“Line 2 – += Operator Example, Value of c = %d\n”, c );

 

c -=  a;

printf(“Line 3 – -= Operator Example, Value of c = %d\n”, c );

 

c *=  a;

printf(“Line 4 – *= Operator Example, Value of c = %d\n”, c );

 

c /=  a;

printf(“Line 5 – /= Operator Example, Value of c = %d\n”, c );

 

c  = 200;

c %=  a;

printf(“Line 6 – %= Operator Example, Value of c = %d\n”, c );

 

c <<=  2;

printf(“Line 7 – <<= Operator Example, Value of c = %d\n”, c );

 

c >>=  2;

printf(“Line 8 – >>= Operator Example, Value of c = %d\n”, c );

 

c &=  2;

printf(“Line 9 – &= Operator Example, Value of c = %d\n”, c );

 

c ^=  2;

printf(“Line 10 – ^= Operator Example, Value of c = %d\n”, c );

 

c |=  2;

printf(“Line 11 – |= Operator Example, Value of c = %d\n”, c );

}

 

When you compile and execute the above program, it produces the following result –

 

Line 1 – =  Operator Example, Value of c = 21

Line 2 – += Operator Example, Value of c = 42

Line 3 – -= Operator Example, Value of c = 21

Line 4 – *= Operator Example, Value of c = 441

Line 5 – /= Operator Example, Value of c = 21

Line 6 – %= Operator Example, Value of c = 11

Line 7 – <<= Operator Example, Value of c = 44

Line 8 – >>= Operator Example, Value of c = 11

Line 9 – &= Operator Example, Value of c = 2

Line 10 – ^= Operator Example, Value of c = 0

Line 11 – |= Operator Example, Value of c = 2

 

1.13 CONDITIONAL OPERATORS

 

A conditional operator is a ternary operator, that is, it works on 3 operands.

 

Conditional Operator Syntax

conditionalExpression ? expression1 : expression2

 

The conditional operator works as follows:

 

  • The first expression conditionalExpression is evaluated first. This expression evaluates to 1 if it’s true and evaluates to 0 if it’s false.
  • If conditionalExpression is true, expression1 is evaluated.
  • If conditionalExpression is false, expression2 is evaluated.

 

#include <stdio.h>

int main(){

char February;

int days;

printf(“If this year is leap year, enter 1. If not enter any integer: “);

scanf(“%c”,&February);

 

// If test condition (February == ‘l’) is true, days equal to 29.

// If test condition (February ==’l’) is false, days equal to 28.

days = (February == ‘1’) ? 29 : 28;

 

printf(“Number of days in February = %d”,days);

return 0;

}

 

Output

If this year is leap year, enter 1. If not enter any integer: 1

Number of days in February = 29

 

1.14 LIBRARY FUNCTIONS

 

  • Library functions in C language are inbuilt functions which are grouped together and placed in a common place called library.
  • Each library function in C performs specific operation.
  • We can make use of these library functions to get the pre-defined output instead of writing our own code to get those outputs.
  • These library functions are created by the persons who designed and created C compilers.
  • All C standard library functions are declared in many header files which are saved as file_name.h.
  • Actually, function declaration, definition for macros are given in all header files.
  • We are including these header files in our C program using “#include<file_name.h>” command to make use of the functions those are declared in the header files.
  • When we include header files in our C program using “#include<filename.h>” command, all C code of the header files are included in C program. Then, this C program is compiled by compiler and executed.

 

Header file Description
stdio.h This is standard input/output header file in which Input/Output
functions are declared
conio.h This is console input/output header file
string.h All string related functions are defined in this header file
stdlib.h This header file contains general functions used in C programs
math.h All maths related functions are defined in this header file
time.h This header file contains time and clock related functions
ctype.h All character handling functions are defined in this header file
stdarg.h Variable argument functions are declared in this header file
signal.h Signal handling functions are declared in this file
setjmp.h This file contains all jump functions
locale.h This file contains locale functions
errno.h Error handling functions are given in this file
assert.h This contains diagnostics functions

 

1.15 STRING FUNCTIONS

 

  • C Strings are nothing but array of characters ended with null character (‘\0’).
  • This null character indicates the end of the string.
  • Strings are always enclosed by double quotes. Whereas, character is enclosed by single quotes in C.

Example for C string:

  • char string[20] = {‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘2’, ‘r’, ‘e’, ‘f’, ’r’, ‘e’, ‘s’, ‘h’, ‘\0’};
    (or)
  • char string[20] = “fresh2refresh”;
    (or)
  • char string []    = “fresh2refresh”;
  • Difference between above declarations are, when we declare char as “string[20]”, 20 bytes of memory space is allocated for holding the string value.
  • When we declare char as “string[]”, memory space will be allocated as per the requirement during execution of the program.

 

Example program for C string:

 

#include <stdio.h>

 

int main ()

{

char string[20] = “fresh2refresh.com”;

 

printf(“The string is : %s \n”, string );

return 0;

}

 

The string is : fresh2refresh.com

 

C String functions:

 

  • String.h header file supports all the string functions in C language. All the string functions are given below.
  • Click on each string function name below for detail description and example programs.

 

String functions Description
strcat ( ) Concatenates str2 at the end of str1
strncat ( ) Appends a portion of string to another
strcpy ( ) Copies str2 into str1
strncpy ( ) Copies given number of characters of one string to another
strlen ( ) Gives the length of str1
strcmp ( ) Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if str1 > str2
strcmpi ( ) Same as strcmp() function. But, this function negotiates case.  “A” and “a” are treated as same.
strchr ( ) Returns pointer to first occurrence of char in str1
strrchr ( ) last occurrence of given character in a string is found
strstr ( ) Returns pointer to first occurrence of str2 in str1
strrstr ( ) Returns pointer to last occurrence of str2 in str1
strdup ( ) Duplicates the string
strlwr ( ) Converts string to lowercase
strupr ( ) Converts string to uppercase
strrev ( ) Reverses the given string
strset ( ) Sets all character in a string to given character
strnset ( ) It sets the portion of characters in a string to given character
strtok ( ) Tokenizing given string using delimiter