Balanace sheets

C – Language History
  • The C programming language is a structure oriented programming language, developed at Bell Laboratories in 1972 by Dennis Ritchie
  • C programming language features were derived from an earlier language called “B” (Basic Combined Programming Language – BCPL)
  • C language was invented for implementing UNIX operating system
  • In 1978, Dennis Ritchie and Brian Kernighan published the first edition  “The C Programming Language” and commonly known as K&R C
  • In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern, comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI C”, was completed late 1988.
  • C programming language standards:
  • C89/C90 standard – First standardized specification for C language was developed by the American National Standards Institute in 1989. C89 and C90 standards refer to the same programming language.
  • C99 standard – Next revision was published in 1999 that introduced new features like advanced data types and other changes.
  • C11 and Embedded C language:
  • C11 standard adds new features to C programming language and library like type generic macros, anonymous structures, improved Unicode support, atomic operations, multi-threading and bounds-checked functions. It also makes some portions of the existing C99 library optional and improves compatibility with C++.
  • Embedded C includes features not available in C like fixed-point arithmetic, named address spaces, and basic I/O hardware addressing.
  • Operating systems, C compiler and all UNIX application programs are written in C language
  • It is also called as procedure oriented programming language. The C language is reliable, simple and easy to use. C has been coded in assembly language.
  • Features of C programming language:
  • Reliability
  • Portability
  • Flexibility
  • Interactivity
  • Modularity
  • Efficiency and Effectiveness
  • Uses of C programming language:The C programming language is used for developing system applications that forms a major portion of operating systems such as Windows, UNIX and Linux. Below are some examples of C being used.
  • Database systems
  • Graphics packages
  • Word processors
  • Spreadsheets
  • Operating system development
  • Compilers and Assemblers
  • Network drivers
  • Interpreters
  • Which level is C language belonging to?The C language is a structured languageC – Basic Program     We are going to learn a simple “Hello World” C program in this section. Also, all the below topics are explained in this section which are the basics of a C program.
  • C basic program with output and explanation
  • Steps to write C programs and get the output
  • Creation, Compilation and Execution of a C program
  • How to install C compiler and IDE
  • Basic structure of a C program
  • Basic commands in C programming to write basic C Program:Below are few commands and syntax used in C programming to write a simple C program. Let’s see all the sections of a simple C program line by line.1. C Basic Program:Output:2. Steps to write C programs and get the output:      Below are the steps to be followed for any C program to create and get the output. This is common to all C program and there is no exception whether its a very small C program or very large C program.3. Creation, Compilation and Execution of a C program:Prerequisite:
  • If  you want to create, compile and execute C programs by your own, you have to install C compiler in your machine. Then, you can start to execute your own C programs in your machine.
  • You can refer below link for how to install C compiler and compile and execute C programs in your machine.
  • Once C compiler is installed in your machine, you can create, compile and execute C programs as shown in below link.
  • 4. Basic structure of C program:Structure of C program is defined by set of rules called protocol, to be followed by programmer while writing C program. All C programs are having sections/parts which are mentioned below.
  • Documentation section
  • Link Section
  • Definition Section
  • Global declaration section
  • Function prototype declaration section
  • Main function
  • User defined function definition section
  • Example C program to compare all the sections:You can compare all the sections of a C program with the below C program.Output:: Description for each  Section of a C program
  • Let us see about each section of a C basic program in detail below.
  • Please note that a C program mayn’t have all below mentioned sections except main function and link sections.
  • Also, a C program structure mayn’t be in below mentioned order.
  • C – printf and scanf
  • printf() and scanf() functions are inbuilt library functions in C which are available in C library by default. These functions are declared and related macros are defined in “stdio.h” which is a header file.
  • We have to include “stdio.h” file as shown in below C program to make use of these printf() and scanf() library functions.
  • 1. C printf() function:
  • printf() function is used to print the “character, string, float, integer, octal and hexadecimal values” onto the output screen.
  • We use printf() function with %d format specifier to display the value of an integer variable.
  • Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for double and %x for hexadecimal variable.
  • To generate a newline,we use “\n” in C printf() statement.
  • Note:
  • C language is case sensitive. For example, printf() and scanf() are different from Printf() and Scanf(). All characters in printf() and scanf() functions must be in lower case.
  • Example program for C printf() function:Output:You can see the output with the same data which are placed within the double quotes of printf statement in the program except
  • %d got replaced by value of an integer variable  (no),
  • %c got replaced by value of a character variable  (ch),
  • %f got replaced by value of a float variable  (flt),
  • %lf got replaced by value of a double variable  (dbl),
  • %s got replaced by value of a string variable  (str),
  • %o got replaced by a octal value corresponding to integer variable  (no),
  • %x got replaced by a hexadecimal value corresponding to integer variable
  • \n got replaced by a newline.
  • 2. C scanf() function:
  • scanf() function is used to read character, string, numeric data from keyboard
  • Consider below example program where user enters a character. This value is assigned to the variable “ch” and then displayed.
  • Then, user enters a string and this value is assigned to the variable “str” and then displayed.
  • Example program for printf() and scanf() functions in C:
  • Output : 
  • C – Data Types
  • C data types are defined as the data storage format that a variable can store a data to perform a specific operation.
  • Data types are used to define a variable before to use in a program.
  • Size of variable, constant and array are determined by data types.
  • C – data types:There are four data types in C language. They are,1. Basic data types in C:1.1. Integer data type:
  • Integer data type allows a variable to store numeric values.
  • int” keyword is used to refer integer data type.
  • The storage size of int data type is 2 or 4 or 8 byte.
  • It varies depend upon the processor in the CPU that we use.  If we are using 16 bit processor, 2 byte  (16 bit) of memory will be allocated for int data type.
  • Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory for 64 bit processor is allocated for int datatype.
  • int (2 byte) can store values from -32,768 to +32,767
  • int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
  • If you want to use the integer value that crosses the above limit, you can go for “long int” and “long long int” for which the limits are very high.
  • Note:
  • We can’t store decimal values using int data type.
  • If we use int data type to store decimal values, decimal values will be truncated and we will get only whole number.
  • In this case, float data type can be used to store decimal values in a variable.
  • 1.2. Character data type:
  • Character data type allows a variable to store only one character.
  • Storage size of character data type is 1. We can store only one character using character data type.
  • char” keyword is used to refer character data type.
  • For example, ‘A’ can be stored using char datatype. You can’t store more than one character using char data type.
  • Please refer  topic to know how to store more than one characters in a variable.
  • 1.3. Floating point data type:Floating point data type consists of 2 types. They are,
  • float
  • double
  • 1. float:
  • Float data type allows a variable to store decimal values.
  • Storage size of float data type is 4. This also varies depend upon the processor in the CPU as “int” data type.
  • We can use up-to 6 digits after decimal using float data type.
  • For example, 10.456789 can be stored in a variable using float data type.
  • 2. double:
  • Double data type is also same as float data type which allows up-to 10 digits after decimal.
  • The range for double datatype is from 1E–37 to 1E+37.
  • 1.3.1. sizeof() function in C:sizeof() function is used to find the memory space allocated for each C data types.Output  :1.3.2. Modifiers in C:
  • The amount of memory space to be allocated for a variable is derived by modifiers.
  • Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount of storage space allocated to a variable.
  • For example, storage space for int data type is 4 byte for 32 bit processor. We can increase the range by using long int which is 8 byte. We can decrease the range by using short int which is 2 byte.
  • There are 5 modifiers available in C language. They are,
  • short
  • long
  • signed
  • unsigned
  • long long
  • Below table gives the detail about the storage size of each C basic data type in 16 bit processor.Please keep in mind that storage size and range for int and float datatype will vary depend on the CPU processor (8,16, 32 and 64 bit)
  • Enumeration data type in C:
  • Enumeration data type consists of named integer constants as a list.
  • It start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the list.
  • Enum syntax in C:
  • enum identifier [optional{ enumerator-list }];
  • Enum example in C: 
  • enum month { Jan, Feb, Mar }; or/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */enum month { Jan = 1, Feb, Mar };/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */enum month { Jan = 20, Feb, Mar };/* Jan is assigned to 20. Feb and Mar variables will be assigned to 21 and 22 respectively by default */
  • The above enum functionality can also be implemented by “#define” preprocessor directive as given below. Above enum example is same as given below.
  • #define Jan 20;#define Feb 21;#define Mar 22;C – enum example program:Output :  
  • Derived data type in C:
  • Array, pointer, structure and union are called derived data type in C language.
  • To know more about derived data types, please visit “” ,” , “” and “” topics in this tutorial.
  • 4. Void data type in C:
  • Void is an empty data type that has no value.
  • This can be used in functions and pointers.
  • Please visit “” topic to know how to use void data type in function with simple call by value and call by reference example programs.
  • C – Tokens and keywords      C tokens, Identifiers and Keywords are the basics in a C program. All are explained in this page with definition and simple example programs.
  • C tokens:
  • C tokens are the basic buildings blocks in C language which are constructed together to write a C program.
  • Each and every smallest individual units in a C program are known as C tokens.
  • C tokens are of six types. They are,
  • Keywords               (eg: int, while),
  • Identifiers               (eg: main, total),
  • Constants              (eg: 10, 20),
  • Strings                    (eg: “total”, “hello”),
  • Special symbols  (eg: (), {}),
  • Operators              (eg: +, /,-,*)
  • C tokens example program:where,
  • main – identifier
  • {,}, (,) – delimiter
  • int – keyword
  • x, y, total – identifier
  • main, {, }, (, ), int, x, y, total – tokens
  •     Do you know how to use C token in real time application programs? We have given simple real time application programs where C token is used. You can refer the below C programs to know how to use C token in real time program.
  • Identifiers in C language:
  • Each program elements in a C program are given a name called identifiers.
  • Names given to identify Variables, functions and arrays are examples for identifiers. eg. x is a name given to integer variable in above program.
  • Rules for constructing identifier name in C:
  • First character should be an alphabet or underscore.
  • Succeeding characters might be digits or letter.
  • Punctuation and special characters aren’t allowed except underscore.
  • Identifiers should not be keywords.
  • Keywords in C language:
  • Keywords are pre-defined words in a C compiler.
  • Each keyword is meant to perform a specific function in a C program.
  • Since keywords are referred names for compiler, they can’t be used as variable name.
  • C language supports 32 keywords which are given below. Click on each keywords below for detail description and example programs.C – Constant
  • C Constants are also like normal variables. But, only difference is, their values can not be modified by the program once they are defined.
  • Constants refer to fixed values. They are also called as literals
  • Constants may be belonging to any of the data type.
  • Syntax:
  • const data_type variable_name; (or) const data_type *variable_name;Types of C constant:
  • Integer constants
  • Real or Floating point constants
  • Octal & Hexadecimal constants
  • Character constants
  • String constants
  • Backslash character constants
  • Rules for constructing C constant:1. Integer Constants in C:
  • An integer constant must have at least one digit.
  • It must not have a decimal point.
  • It can either be positive or negative.
  • No commas or blanks are allowed within an integer constant.
  • If no sign precedes an integer constant, it is assumed to be positive.
  • The allowable range for integer constants is -32768 to 32767.
  • 2. Real constants in C:
  • A real constant must have at least one digit
  • It must have a decimal point
  • It could be either positive or negative
  • If no sign precedes an integer constant, it is assumed to be positive.
  • No commas or blanks are allowed within a real constant.
  • Character and string constants in C:
  • A character constant is a single alphabet, a single digit or a single special symbol enclosed within single quotes.
  • The maximum length of a character constant is 1 character.
  • String constants are  enclosed within double quotes.
  • Backslash Character Constants in C:
  • There are some characters which have special meaning in C language.
  • They should be preceded by backslash symbol to make use of special function of them.
  • Given below is the list of special characters and their purpose.
  • How to use constants in a C program?
  • We can define constants in a C program in the following ways.
  • By “const” keyword
  • By “#define” preprocessor directive
  • Please note that when you try to change constant values after defining in C program, it will through error.
  • 1. Example program using const keyword in C:   Output:2. Example program using #define preprocessor directive in C:Output:C – VariableC variable is a named location in a memory where a program can manipulate the data. This location is used to hold the value of the variable.
  • The value of the C variable may get change in the program.
  • C variable might be belonging to any of the data type like int, float, char etc.
  • Rules for naming C variable:
  • Variable name must begin with letter or underscore.
  • Variables are case sensitive
  • They can be constructed with digits, letters.
  • No special symbols are allowed other than underscore.
  • sum, height, _value are some examples for variable name
  • Declaring & initializing C variable:
  • Variables should be declared in the C program before to use.
  • Memory space is not allocated for a variable while declaration. It happens only on variable definition.
  • Variable initialization means assigning a value to the variable.
  • There are three types of variables in C program They are,
  • Local variable
  • Global variable
  • Environment variable
  • Example program for local variable in C:
  • The scope of local variables will be within the function only.
  • These variables are declared within the function and can’t be accessed outside the function.
  • In the below example, m and n variables are having scope within the main function only. These are not visible to test function.
  • Like wise, a and b variables are having scope within the test function only. These are not visible to main function.
  • Output:
  • Example program for global variable in C:
  • The scope of global variables will be throughout the program. These variables can be accessed from anywhere in the program.
  • This variable is defined outside the main function. So that, this variable is visible to main function and all other sub functions.
  • Output:
  • Environment variables in C:
  • Environment variable is a variable that will be available for all C  applications and C programs.
  • We can access these variables from anywhere in a C program without declaring and initializing in an application or C program.
  • The inbuilt functions which are used to access, modify and set these environment variables are called environment functions.
  • There are 3 functions which are used to access, modify and assign an environment variable in C. They are,
  • 1. setenv()2. getenv()3. putenv()Example program for getenv() function in C:      This function gets the current value of the environment variable. Let us assume that environment variable DIR is assigned to “/usr/bin/test/”.Output: Example program for setenv() function in C:      This function sets the value for environment variable. Let us assume that environment variable “FILE” is to be assigned “/usr/bin/example.cOutput:Example program for putenv() function in C:      This function modifies the value for environment variable. Below example program shows that how to modify an existing environment variable value.Output:Difference between variable declaration & definition in C:C – Operators and Expressions
  • The symbols which are used to perform logical and mathematical operations in a C program are called C operators.
  • These C operators join individual constants and variables to form expressions.
  • Operators, functions, constants and variables are combined together to form expressions.
  • Consider the expression A + B * 5. where, +, * are operators, A, B  are variables, 5 is constant and A + B * 5 is an expression.
  • Types of C operators:C language offers many types of operators. They are,
  • Arithmetic operators
  • Assignment operators
  • Relational operators
  • Logical operators
  • Bit wise operators
  • Conditional operators (ternary operators)
  • Increment/decrement operators
  • Special operators
  • Continue on types of C operators:
  • Click on each operators name below for detail description and example programs.
  • C – Decision Control statement
  • In decision control statements (C if else and nested if), group of statements are executed when condition is true.  If condition is false, then else part statements are executed.
  • There are 3 types of decision making control statements in C language. They are,
  •   if statements
  •   if else statements
  •   nested if statements
  • “If”, “else” and “nested if” decision control statements in C:
  • Syntax for each C decision control statements are given in below table with description.
  • Example program for if statement in C:      In “if” control statement, respective block of code is executed when condition is true.Output:Example program for if else statement in C:      In C if else control statement, group of statements are executed when condition is true.  If condition is false, then else part statements are executed.Output:Example program for nested if statement in C: 
  • In “nested if” control statement, if condition 1 is false, then condition 2 is checked and statements are executed if it is true. 
  • If condition 2 also gets failure, then else part is executed.
  •  Output:C – Loop control statements      Loop control statements in C are used to perform looping operations until the given condition is true. Control comes out of the loop statements once condition becomes false.Types of loop control statements in C:There are 3 types of loop control statements in C language. They are,
  • for
  • while
  • do-while
  • Syntax for each C loop control statements are given in below table with description.
  • Example program (for loop) in C:      In for loop control statement, loop is executed until condition becomes false.Output:Example program (while loop) in C:      In while loop control statement, loop is executed until condition becomes false.Output:Example program (do while loop) in C:      In do..while loop control statement, while loop is executed irrespective of the condition for first time. Then 2nd time onwards, loop is executed until condition becomes false.Output:Difference between while & do while loops in C:C – Case control statements     The statements which are used to execute only specific block of statements in a series of blocks are called case control statements.There are 4 types of case control statements in C language. They are,
  • switch
  • break
  • continue
  • goto
  • 1. switch case statement in C:
  • Switch case statements are used to execute only specific case statements based on the switch expression.
  • Below is the syntax for switch case statement.
  • switch (expression){case label1:   statements;break;case label2:   statements;break;default:    statements;break;}Example program for switch..case statement in C:Output:2. break statement in C:
  • Break statement is used to terminate the while loops, switch case loops and for loops from the subsequent execution.
  • Syntax: break;
  • Example program for break statement in C: Output:3. Continue statement in C:
  • Continue statement is used to continue the next iteration of for loop, while loop and do-while loops.  So, the remaining statements are skipped within the loop for that particular iteration.
  • Syntax : continue;
  • Example program for continue statement in C:Output:
  • goto statement in C:
  • goto statements is used to transfer the normal flow of a program to the specified label in the program.
  • Below is the syntax for goto statement in C.
  • {         …….         go to label;         …….         …….         LABEL:         statements;}Example program for goto statement in C: Output:C – Type Qualifiers
  • C – type qualifiers : The keywords which are used to modify the properties of a variable are called type qualifiers.
  • Types of C type qualifiers:There are two types of qualifiers available in C language. They are,
  • const
  • volatile
  • 1. const keyword:
  • Constants are also like normal variables. But, only difference is, their values can’t be modified by the program once they are defined.
  • They refer to fixed values. They are also called as literals.
  • They may be belonging to any of the data type.
  • Syntax: 
  • const data_type variable_name; (or) const data_type *variable_name;
  • Please refer  topic in this tutorial for more details on const keyword.
  • 2. volatile keyword:
  • When a variable is defined as volatile, the program may not change the value of the variable explicitly.
  • But, these variable values might keep on changing without any explicit assignment by the program. These types of qualifiers are called volatile.
  • For example, if global variable’s address is passed to clock routine of the operating system to store the system time, the value in this address keep on changing without any assignment by the program. These variables are named as volatile variable.
  • Syntax:       
  • volatile data_type variable_name; (or) volatile data_type *variable_name;C – Storage Class Specifiers      Storage class specifiers in C language tells the compiler where to store a variable, how to store the variable, what is the initial value of the variable and life time of the variable.Syntax:storage_specifier data_type variable _nameTypes of Storage Class Specifiers in C:     There are 4 storage class specifiers available in C language. They are,
  • auto
  • extern
  • static
  • register
  • Note:
  • For faster access of a variable, it is better to go for register specifiers rather than auto specifiers.
  • Because, register variables are stored in register memory whereas auto variables are stored in main CPU memory.
  • Only few variables can be stored in register memory. So, we can use variables as register that are used very often in a C program.
  • Example program for auto variable in C:The scope of this auto variable is within the function only. It is equivalent to local variable. All local variables are auto variables by default.COutput:Example program for static variable in C:      Static variables retain the value of the variable between different function calls.COutput:Example program for extern variable in C:     The scope of this extern variable is throughout the main program. It is equivalent to global variable. Definition for extern variable might be anywhere in the C program.COutput:Example program for register variable in C:
  • Register variables are also local variables, but stored in register memory. Whereas, auto variables are stored in main CPU memory.
  • Register variables will be accessed very faster than the normal variables since they are stored in register memory rather than main memory.
  • But, only limited variables can be used as register since register size is very low. (16 bits, 32 bits or 64 bits)
  • C Output:C – Array     C Array is a collection of variables belongings to the same data type. You can store group of data of same data type in an array.
  • Array might be belonging to any of the data types
  • Array size must be a constant value.
  • Always, Contiguous (adjacent) memory locations are used to store array elements in memory.
  • It is a best practice to initialize an array to zero or null while declaring, if we don’t assign any values to array.
  • Example for C Arrays:
  • int a[10];       // integer array
  • char b[10];   // character array   i.e. string
  • Types of C arrays:There are 2 types of C arrays. They are,
  • One dimensional array
  • Multi dimensional array
  • Two dimensional array
  • Three dimensional array, four dimensional array etc…
  • 1. One dimensional array in C:
  • Syntax : data-type arr_name[array_size];
  • Example program for one dimensional array in C:C Output:2. Two dimensional array in C:
  • Two dimensional array is nothing but array of array.
  • syntax : data_type array_name[num_of_rows][num_of_column]
  • Example program for two dimensional array in C:COutput:C – String     Prev                                                                                              
  • 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:COutput: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.
  • C – Pointer     Prev                                                                                              
  • C Pointer is a variable that stores/points the address of another variable. C Pointer is used to allocate memory dynamically i.e. at run time. The pointer variable might be belonging to any of the data type such as int, float, char, double, short etc.
  •    Syntax : data_type *var_name; Example : int *p;  char *p;
  • Where, * is used to denote that “p” is pointer variable and not a normal variable.
  • Key points to remember about pointers in C:
  • Normal variable stores the value whereas pointer variable stores the address of the variable.
  • The content of the C pointer always be a whole number i.e. address.
  • Always C pointer is initialized to null, i.e. int *p = null.
  • The value of null pointer is 0.
  • & symbol is used to get the address of the variable.
  • * symbol is used to get the value of the variable that the pointer is pointing to.
  • If pointer is assigned to NULL, it means it is pointing to nothing.
  • Two pointers can be subtracted to know how many elements are available between these two pointers.
  • But, Pointer addition, multiplication, division are not allowed.
  • The size of any pointer is 2 byte (for 16 bit compiler).
  • Example program for pointer in C:output :C – Function     Prev                                                                                                   C functions are basic building blocks in a program. All C programs are written using functions to improve re-usability, understandability and to keep track on them. You can learn below concepts of C functions in this section in detail.
  • What is C function?
  • Uses of C functions
  • C function declaration, function call and definition with example program
  • How to call C functions in a program?
  • Call by value
  • Call by reference
  • C function arguments and return values
  • C function with arguments and with return value
  • C function with arguments and without return value
  • C function without arguments and without return value
  • C function without arguments and with return value
  • Types of C functions
  • Library functions in C
  • User defined functions in C
  • Creating/Adding user defined function in C library
  • Command line arguments in C
  • Variable length arguments in C
  • 1. What is C function?     A large C program is divided into basic building blocks called C function. C function contains set of instructions enclosed by “{  }” which performs specific operation in a C program. Actually, Collection of these functions creates a C program.2. Uses of C functions:
  • C functions are used to avoid rewriting same logic/code again and again in a program.
  • There is no limit in calling C functions to make use of same functionality wherever required.
  • We can call functions any number of times in a program and from any place in a program.
  • A large C program can easily be tracked when it is divided into functions.
  • The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve the functionality and to improve understandability of very large C programs.
  • 3. C function declaration, function call and function definition:There are 3 aspects in each C function. They are,
  • Function declaration or prototype  – This informs compiler about the function name, function parameters and  return value’s data type.
  • Function call – This calls the actual function
  • Function definition – This contains all the statements to be executed.
  • Simple example program for C function:
  • As you know, functions should be declared and defined before calling in a C program.
  • In the below program, function “square” is called from main function.
  • The value of “m” is passed as argument to the function “square”. This value is multiplied by itself in this function and multiplied value “p” is returned to main function from function “square”.
  • COutput:4. How to call C functions in a program?There are two ways that a C function can be called from a program. They are,
  • Call by value
  • Call by reference
  • 1. Call by value:
  • In call by value method, the value of the variable is passed to the function as parameter.
  • The value of the actual parameter can not be modified by formal parameter.
  • Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is copied to formal parameter.
  • Note:
  • Actual parameter – This is the argument which is used in function call.
  • Formal parameter – This is the argument which is used in function definition
  • Example program for C function (using call by value):
  • In this program, the values of the variables “m” and “n” are passed to the function “swap”.
  • These values are copied to formal parameters “a” and “b” in swap function and used.
  • COutput:2. Call by reference:
  • In call by reference method, the address of the variable is passed to the function as parameter.
  • The value of the actual parameter can be modified by formal parameter.
  • Same memory is used for both actual and formal parameters since only address is used by both parameters.
  • Example program for C function (using call by reference):
  • In this program, the address of the variables “m” and “n” are passed to the function “swap”.
  • These values are not copied to formal parameters “a” and “b” in swap function.
  • Because, they are just holding the address of those variables.
  • This address is used to access and change the values of the variables.
  • COutput:C – Library functions     Prev                                                                                              
  • 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.
  • Please check the below links for actual C source code for the respective C header files.
  • If you want to check source code for all header files, you can check inside “include” directory after C compiler is installed in your machine.
  • For example, if you install DevC++ compiler in C directory in your machine, “C:\Dev-Cpp\include” is the path where all header files will be available.
  • List of most used header files in C:
  • Check the below table to know all the C library functions and header files in which they are declared.
  • Click on the each header file name below to know the list of inbuilt functions declared inside them.
  • C – Argument, return value     Prev                                                                                                  All C functions can be called either with arguments or without arguments in a C program. These functions may or may not return values to the calling function. Now, we will see simple example C programs for each one of the below.
  • C function with arguments (parameters) and with return value
  • C function with arguments (parameters) and without return value
  • C function without arguments (parameters) and without return value
  • C function without arguments (parameters) and with return value
  • Note:
  • If the return data type of a function is “void”, then, it can’t return any values to the calling function.
  • If the return data type of the function is other than void such as “int, float, double etc”, then, it can return values to the calling function.
  • 1. Example program for with arguments & with return value:      In this program, integer, array and string are passed as arguments to the function. The return type of this function is “int” and value of the variable “a” is returned from the function. The values for array and string are modified inside the function itself.COutput:2. Example program for with arguments & without return value:      In this program, integer, array and string are passed as arguments to the function. The return type of this function is “void” and no values can be returned from the function. All the values of integer, array and string are manipulated and displayed inside the function itself.COutput:3. Example program for without arguments & without return value:      In this program, no values are passed to the function “test” and no values are returned from this function to main function.COutput:4. Example program for without arguments & with return value:      In this program, no arguments are passed to the function “sum”. But, values are returned from this function to main function. Values of the variable a and b are summed up in the function “sum” and the sum of these value is returned to the main function.COutput:Do you know how many values can be return from C functions?
  • Always, Only one value can be returned from a function.
  • If you try to return more than one values from a function, only one value will be returned that appears at the right most place of the return statement.
  • For example, if you use “return a,b,c” in your function, value for c only will be returned and values a, b won’t be returned to the program.
  • In case, if you want to return more than one values, pointers can be used to directly change the values in address instead of returning those values to the function.
  • C – Creating library functions     Prev                                                                                              User defined functions in C:
  • As you know, there are 2 types of functions in C. They are, library functions and user defined functions.
  • Library functions are inbuilt functions which are available in common place called C library. Where as, User defined functions are the functions which are written by us for our own requirement.
  • Adding user defined functions in C library:
  • Do you know that we can add our own user defined functions in C library?
  • Yes. It is possible to add, delete, modify and access our own user defined function to or from C library.
  • The advantage of adding user defined function in C library is, this function will be available for all C programs once added to the C library.
  • We can use this function in any C program as we use other C library functions.
  • In latest version of GCC compilers, compilation time can be saved since these functions are available in library in the compiled form.
  • Normal header files are saved as “file_name.h” in which all library functions are available. These header files contain source code and this source code is added in main C program file where we add this header file using “#include <file_name.h>” command.
  • Where as, precompiled version of header files are saved as “file_name.gch”.
  • Steps for adding our own functions in C library:Step 1:For example, below is a sample function that is going to be added in the C library. Write the below function in a file and save it as “addition.caddition(int i, int j){int total;total = i + j;return total;}Step 2:Compile “addition.c” file by using Alt + F9 keys (in turbo C).step 3:“addition.obj” file would be created which is the compiled form of “addition.c” file.Step 4:Use the below command to add this function to library (in turbo C).c:\> tlib math.lib + c:\ addition.obj+ means adding c:\addition.obj file in the math library.We can delete this file using – (minus).Step 5:        Create a file “addition.h” & declare prototype of addition() function like below.int addition (int i, int j);Now addition.h file containing prototype of function “addition”.Note : Please create, compile and add files in the respective directory as directory name may change for each IDE.Step 6:Let us see how to use our newly added library function in a C program.C Output:C – Command line arguments     Prev                                                                                              Command line arguments in C:      main() function of a C program accepts arguments from command line or from other shell scripts by following commands. They are,
  • argc
  • argv[]
  • where,argc      – Number of arguments in the command line including program nameargv[]   – This is carrying all the arguments
  • In real time application, it will happen to pass arguments to the main program itself.  These arguments are passed to the main () function while executing binary file from command line.
  • For example, when we compile a program (test.c), we get executable file in the name “test”.
  • Now, we run the executable “test” along with 4 arguments in command line like below.
  • ./test this is a programWhere,argc             =       5argv[0]         =       “test”argv[1]         =       “this”argv[2]         =       “is”argv[3]         =       “a”argv[4]         =       “program”argv[5]         =       NULLExample program for argc() and argv() functions in C:C Output:C – Variable length argument     Prev                                                                                              
  • Variable length arguments is an advanced concept in C language offered by c99 standard. In c89 standard, fixed arguments only can be passed to the functions.
  • When a function gets number of arguments that changes at run time, we can go for variable length arguments.
  • It is denoted as … (3 dots)
  • stdarg.h header file should be included to make use of variable length argument functions.
  • Example program for variable length arguments in C:COutput:       In the above program, function “add” is called twice. But, number of arguments passed to the function gets varies for each. So, 3 dots (…) are mentioned for function ‘add” that indicates that this function will get any number of arguments at run time.C – Summary of C functions     Prev                                                                                                    As you know, C functions are basic building blocks in every C program. We have given key points those to be kept in mind for using existing C library functions and writing our own functions in a C program efficiently.Key points to remember while writing functions in C:
  • All C programs contain main() function which is mandatory.
  • main() function is the function from where every C program is started to execute.
  • Name of the function is unique in a C program.
  • C Functions can be invoked from anywhere within a C program.
  • There can any number of functions be created in a program. There is no limit on this.
  • There is no limit in calling C functions in a program.
  • All functions are called in sequence manner specified in main() function.
  • One function can be called within another function.
  • C functions can be called with or without arguments/parameters. These arguments are nothing but inputs to the functions.
  • C functions may or may not return values to calling functions. These values are nothing but output of the functions.
  • When a function completes its task, program control is returned to the function from where it is called.
  • There can be functions within functions.
  • Before calling and defining a function, we have to declare function prototype in order to inform the compiler about the function name, function parameters and return value type.
  • C function can return only one value to the calling function.
  • When return data type of a function is “void”, then, it won’t return any values
  • When return data type of a function is other than void such as “int, float, double”, it returns value to the calling function.
  • main() program comes to an end when there is no functions or commands to execute.
  • There are 2 types of functions in C. They are, 1. Library functions 2. User defined functions
  •       There are many inbuilt C functions which are offered by C compiler. You can check list of all C functions and simple example programs with outputs below.C – Type Casting functions      Prev                                                                                              
  • Typecasting concept in C language is used to modify a variable from one date type to another data type. New data type should be mentioned before the variable name or value in brackets which to be typecast.
  • C type casting example program:
  • In the below C program, 7/5 alone will produce integer value as 1.
  • So, type cast is done before division to retain float value (1.4).
  • COutput:Note:
  • It is best practice to convert lower data type to higher data type to avoid data loss.
  • Data will be truncated when higher data type is converted to lower. For example, if float is converted to int, data which is present after decimal point will be lost.
  • Inbuilt typecast functions in C:
  • There are many inbuilt typecasting functions available in C language which performs data type conversion from one type to another.
  • Click on each function name below for description and example programs.
  • C – Union     Prev                                                                                                    C Union is also like structure, i.e. collection of different data types which are grouped together. Each element in a union is called member.
  • Union and structure in C  are same in concepts, except allocating memory for their members.
  • Structure allocates storage space for all its members separately.
  • Whereas, Union allocates one common storage space for all its members
  • We can access only one member of union at a time. We can’t access all member values at the same time in union. But, structure can access all member values at the same time. This is because, Union allocates one common storage space for all its members. Wheras Structure allocates storage space for all its members separately.
  • Many union variables can be created in a program and memory will be allocated for each union variable separately.
  • Below table will help you how to form a C union, declare a union, initializing and accessing the members of the union.
  • Example program for C union:COutput:Explanation for above C union program:      There are 2 union variables declared in this program to understand the difference in accessing values of union members.Record1 union variable:
  • Raju” is assigned to union member “record1.name” . The memory location name is “record1.name” and the value stored in this location is “Raju”.
  • Then, “Maths” is assigned to union member “record1.subject”. Now, memory location name is changed to “record1.subject” with the value “Maths” (Union can hold only one member at a time).
  • Then, “86.50” is assigned to union member “record1.percentage”. Now, memory location name is changed to “record1.percentage” with value “86.50”.
  • Like this, name and value of union member is replaced every time on the common storage space.
  • So, we can always access only one union member for which value is assigned at last. We can’t access other member values.
  • So, only “record1.percentage” value is displayed in output. “record1.name” and “record1.percentage” are empty.
  • Record2 union variable:
  • If we want to access all member values using union, we have to access the member before assigning values to other members as shown in record2 union variable in this program.
  • Each union members are accessed in record2 example immediately after assigning values to them.
  • If we don’t access them before assigning values to other member, member name and value will be over written by other member as all members are using same memory.
  • We can’t access all members in union at same time but structure can do that.
  • Example program – Another way of declaring C union:    In this program, union variable “record” is declared while declaring union itself as shown in the below program.COutput:Note:      We can access only one member of union at a time. We can’t access all member values at the same time in union. But, structure can access all member values at the same time. This is because, Union allocates one common storage space for all its members. Wheras Structure allocates storage space for all its members separately.Difference between structure and union in C: