The byte (/bat/) is a unit of digital information that most commonly consists of eight bits.
Historically, the bytewas the number of bits used to encode a single character of text in a
computer and for this reason it is the smallest addressable unit of memory in many computer
architectures.
1 bit = a 1 or 0 (b)
4 bits = 1 nybble (?)
8 bits = 1 byte (B)
1024 bytes = 1 Kilobyte (KB)
1024 Kilobytes = 1 Megabyte (MB)
1024 Megabytes = 1 Gigabyte (GB)
1024 Gigabytes = 1 Terabyte (TB)
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)
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
Database systems
Graphics packages
Word processors
Spreadsheets
Network drivers
Interpreters
WHICH LEVEL IS C LANGUAGE BELONGING TO?
1.
Middle Level:
Middle level languages dont provide all the built-in functions found in high level languages, but provides all
building blocks that we need to produce the result we want. Examples: C, C++
2.
High Level:
High level languages provide almost everything that the programmer might need to do as already built into the
language. Example: Java, Python
3.
Low Level:
Low level languages provides nothing other than access to the machines basic instruction
set. Example: Assembler
C LANGUAGE IS A STRUCTURED LANGUAGE:
Structure oriented language:
In this type of language, large programs are divided into small programs called functions
Data moves freely around the systems from one function to another
Prime focus is in the data that is being operated and not on the functions or procedures
Examples: C++, JAVA and C# (C sharp)
Non structure oriented language:
There is no specific structure for programming this language. Examples: BASIC, COBOL, FORTRAN
KEY POINTS TO REMEMBER IN C LANGUAGE:
1.
The C language is structured, middle level programming language developed by Dennis Ritchie
2.
Operating system programs such as Windows, Unix, Linux are written in C language
3.
C89/C90 and C99 are two standardized editions of C language
4.
C has been written in assembly language
C LANGUAGE TUTORIAL REFERENCE E-BOOKS & RESEARCH PAPERS:
[ANSI 89] American National Standards Institute., American National Standard for Information Programming
Language C, X3 159-1989
[Kernighan 78] B. W. Kernighan and D. M. Ritchie, The C Programming Language, Prentice-Hall: Englewood
Cliffs, NJ, 1978. Second edition, 1988.
[Thinking 90] C* Programming Guide, Thinking Machines Corp.: Cambridge Mass., 1990.
C 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.
1.
C basic program with output and explanation
2.
Steps to write C programs and get the output
3.
Creation, Compilation and Execution of a C program
* How to install C compiler and IDE
4.
Basic structure of a C program
C PROGRAMMING BASICS TO WRITE A C PROGRAM:
Below are few commands and syntax used in C programming to write a simple C program. Lets see all the sections of a
simple C program line by line.
Command
Explanation
#include <stdio.h>
int main()
/*_some_comments_*/
printf(Hello_World!
);
getch();
return 0;
1. C BASIC PROGRAM:
#include <stdio.h>
int main()
{
/* Our first simple C basic program */
printf(Hello World! );
getch();
return 0;
}
.
OUTPUT:
Hello World!
.
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.
1.
Create
2.
Compile
3.
Execute or Run
4.
Get the Output
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.
C ENVIRONMENT SETUP USING IDE TOOL
C ENVIRONMENT SETUP USING GCC COMPILER
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.
1.
Documentation section
2.
Link Section
3.
Definition Section
4.
Global declaration section
5.
Function prototype declaration section
6.
Main function
7.
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.
/* C basic structure program Documentation section
Author: fresh2refresh.com
Date : 01/01/2012
*/#include <stdio.h> /* Link section */
int total = 0; /* Global declaration and definition section */
int sum (int, int); /* Function declaration section */
int main () /* Main function */
{
printf (This is a C basic program \n);
total = sum (1, 1);
printf (Sum of two numbers : %d \n, total);
return 0;
}
int sum (int a, int b) /* User defined function */
{ /* definition section */
return a + b;
}
.
OUTPUT:
Please note that a C program maynt have all below mentioned sections except main function and link sections.
Description
Documentation
section
Link Section
Definition Section
Global declaration
section
Function prototype
declaration section
Main function
User defined
function section
[ANSI 89] American National Standards Institute., American National Standard for Information Programming
Language C, X3 159-1989
[Kernighan 78] B. W. Kernighan and D. M. Ritchie, The C Programming Language, Prentice-Hall: Englewood
Cliffs, NJ, 1978. Second edition, 1988.
[Thinking 90] C* Programming Guide, Thinking Machines Corp.: Cambridge Mass., 1990.
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.
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:
#include <stdio.h>
int main()
{
char ch = A;
char str[20] = fresh2refresh.com;
float flt = 10.234;
int no = 150;
double dbl = 20.123456;
printf(Character is %c \n, ch);
printf(String is %s \n , str);
printf(Float value is %f \n, flt);
printf(Integer value is %d\n , no);
printf(Double value is %lf \n, dbl);
printf(Octal value is %o \n, no);
printf(Hexadecimal value is %x \n, no);
return 0;
}
.
Output:
Character is A
String is fresh2refresh.com
Float value is 10.234000
Integer value is 150
Double value is 20.123456
Octal value is 226
Hexadecimal value is 96
.
You can see the output with the same data which are placed within the double quotes of printf statement in the program
except
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:
#include <stdio.h>
int main()
{
char ch;
char str[100];
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);
}
.
Output :
The format specifier %d is used in scanf() statement. So that, the value entered is received as an integer and %s
for string.
Ampersand is used before variable name ch in scanf() statement as &ch.
It is just like in a pointer which is used to point to the variable. For more information about how pointer works,
please click here.
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.
Types
Data Types
enum
void
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.
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:
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:
Storage size of character data type is 1. We can store only one character using character data type.
For example, A can be stored using char datatype. You cant store more than one character using char data
type.
Please refer C Strings 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,
1.
float
2.
double
1. FLOAT:
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.
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.
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)
S.N
o
C Data types
storage
Size
Range
char
127 to 127
int
32,767 to 32,767
float
double
long double
10
long int
2,147,483,647 to 2,147,483,647
short int
32,767 to 32,767
0 to 65,535
32,767 to 32,767
10
(2power(63) 1) to 2(power)63 1
11
2,147,483,647 to 2,147,483,647
12
0 to 4,294,967,295
13
unsigned long
long int
2(power)64 1
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:
#include <stdio.h>
int main()
{
enum MONTH { Jan = 0, Feb, Mar };
enum MONTH month = Mar;
if(month == 0)
printf(Value of Jan);
else if(month == 1)
printf(Month is Feb);
if(month == 2)
printf(Month is Mar);
}
.
Output :
Month is March
.
3. 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 C Array , C Pointer , C Structure and C
Union topics in this tutorial.
4. VOID DATA TYPE IN C:
Please visit C Function topic to know how to use void data type in function with simple call by value and
call by reference example programs.
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,
1.
Keywords
(eg: int, while),
2.
Identifiers
(eg: main, total),
3.
Constants
(eg: 10, 20),
4.
Strings
(eg: total, hello),
5.
Special symbols (eg: (), {}),
6.
Operators
(eg: +, /,-,*)
C TOKENS EXAMPLE PROGRAM:
int main()
{
int x, y, total;
x = 10, y = 20;
total = x + y;
Printf (Total = %d \n, total);
}
.
where,
main identifier
int keyword
x, y, total identifier
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:
1.
First character should be an alphabet or underscore.
2.
Succeeding characters might be digits or letter.
3.
Punctuation and special characters arent allowed except underscore.
4.
Identifiers should not be keywords.
3. KEYWORDS IN C LANGUAGE:
Since keywords are referred names for compiler, they cant 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.
1.
auto
2.
double
3.
int
4.
struct
5.
const
6.
float
7.
short
8.
unsigned
9.
break
10.
else
11.
long
12.
switch
13.
continue
14.
for
15.
signed
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
void
case
enum
register
typedef
default
goto
sizeof
volatile
char
extern
return
union
do
if
static
while
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.
Syntax:
const data_type variable_name; (or) const data_type *variable_name;
TYPES OF C CONSTANT:
1.
Integer constants
2.
Real or Floating point constants
3.
Octal & Hexadecimal constants
4.
Character constants
5.
String constants
6.
Backslash character constants
S.n
o
Constant type
data type
Example
Integer
constants
int unsigned
int long intlong
long int
Real or Floating
point constants
float doule
10.456789600.123456789
Octal constant
int
013
/* starts with 0 */
Hexadecimal
constant
int
0x90
/* starts with 0x */
character
constants
char
A , B,
string constants
char
ABCD , Hai
A real constant must have at least one digit
A character constant is a single alphabet, a single digit or a single special symbol enclosed within single
quotes.
They should be preceded by backslash symbol to make use of special function of them.
Meaning
\b
Backspace
\f
Form feed
\n
New line
\r
Carriage return
\t
Horizontal tab
Double quote
Single quote
\\
Backslash
\v
Vertical tab
\a
Alert or bell
\?
Question mark
\N
\XN
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:
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
void main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
const char backslash_char = '\?'; /*special char cnst*/
printf("value of height :%d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
C 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.
C variable might be belonging to any of the data type like int, float, char etc.
RULES FOR NAMING C VARIABLE:
1.
Variable name must begin with letter or underscore.
2.
Variables are case sensitive
3.
They can be constructed with digits, letters.
4.
No special symbols are allowed other than underscore.
5.
sum, height, _value are some examples for variable name
DECLARING & INITIALIZING C VARIABLE:
Memory space is not allocated for a variable while declaration. It happens only on variable definition.
Type
Syntax
Example
Variable
declaration
data_type
variable_name;
Variable
initialization
data_type
variable_name = value;
3.
Environment variable
1. EXAMPLE PROGRAM FOR LOCAL VARIABLE IN C:
These variables are declared within the function and cant 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.
1 #include<stdio.h>
2 void test();
3 int main()
4 {
5 int m = 22, n = 44;
6 // m, n are local variables of main function
7 /*m and n variables are having scope
8 within this main function only.
9 These are not visible to test funtion.*/
10 /* If you try to access a and b in this function,
11 you will get 'a' undeclared and 'b' undeclared error */
12 printf("\nvalues : m = %d and n = %d", m, n);
13 test();
14 }
15 void test()
16 {
17 int a = 50, b = 80;
18 // a, b are local variables of test function
19 /*a and b variables are having scope
20 within this test function only.
21 These are not visible to main function.*/
22 /* If you try to access m and n in this function,
23 you will get 'm' undeclared and 'n' undeclared
24 error */printf("\nvalues : a = %d and b = %d", a, b);
25 }
Output:
values : m = 22 and n = 44
values : a = 50 and b = 80
2. 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.
1
#include<stdio.h>
2
void test();int m = 22, n = 44;
3
int a = 50, b = 80;
4
int main()
5
{
6
printf("All variables are accessed from main function");
7
printf("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
8
test();
9
}
10 void test()
11 {
12 printf("\n\nAll variables are accessed from" \
13 " test function");
14 printf("\nvalues: m=%d:n=%d:a=%d:b=%d", m,n,a,b);
15 }
Output:
All variables are accessed from main function
values : m = 22 : n = 44 : a = 50 : b = 80
All variables are accessed from test function
values : m = 22 : n = 44 : a = 50 : b = 80
3. 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/.
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main()
5 {
6 printf("Directory = %s\n",getenv("DIR"));
7 return 0;
8 }
OUTPUT:
/usr/bin/test/
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.c
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main()
5 {
6 setenv("FILE", "/usr/bin/example.c",50);
7 printf("File = %s\n", getenv("FILE"));
8 return 0;
9 }
OUTPUT:
File = /usr/bin/example.c
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.
1 #include <stdio.h>
2 #include <stdlib.h>
3
4 int main()
5 {
6 setenv("DIR", "/usr/bin/example/",50);
7 printf("Directory name before modifying = " \
8 "%s\n", getenv("DIR"));
9 putenv("DIR=/usr/home/");
10 printf("Directory name after modifying = " \
11 "%s\n", getenv("DIR"));
12 return 0;
13 }
OUTPUT:
Directory name before modifying = /usr/bin/example/
Variable declaration
Variable definition
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,
1.
Arithmetic operators
2.
Assignment operators
3.
Relational operators
4.
Logical operators
5.
Bit wise operators
6.
Conditional operators (ternary operators)
7.
Increment/decrement operators
8.
Special operators
CONTINUE ON TYPES OF C OPERATORS:
Click on each operators name below for detail description and example programs.
S.n
o
Types of Operators
Arithmetic_operators
Assignment_operators
Relational operators
Logical operators
Conditional (ternary)
operators
Increment/decrement
operators
Special operators
Description
C Arithmetic Operators
ARITHMETIC OPERATORS IN C:
C Arithmetic operators are used to perform mathematical calculations like addition, subtraction, multiplication,
division and modulus in C programs.
S.no
Arithmetic
Operators
Operation
Example
Addition
A+B
Subtraction
A-B
multiplication
A*B
Division
A/B
Modulus
A%B
In this example program, two values 40 and 20 are used to perform arithmetic operations such as addition,
subtraction, multiplication, division, modulus and output is displayed for each operation.
1 #include <stdio.h>
2
3 int main()
4 {
5 int a=40,b=20, add,sub,mul,div,mod;
6 add = a+b;
7 sub = a-b;
8 mul = a*b;
9 div = a/b;
10 mod = a%b;
11 printf("Addition of a, b is : %d\n", add);
12 printf("Subtraction of a, b is : %d\n", sub);
13 printf("Multiplication of a, b is : %d\n", mul);
14 printf("Division of a, b is : %d\n", div);
15 printf("Modulus of a, b is : %d\n", mod);
16 }
OUTPUT:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
C Assignment Operators
ASSIGNMENT OPERATORS IN C:
In C programs, values for the variables are assigned using assignment operators.
For example, if the value 10 is to be assigned for the variable sum, it can be assigned as sum = 10;
Example
Explanation
sum = 10
+=
sum += 10
-=
sum -= 10
*=
sum *= 10
/+
sum /= 10
%=
sum %= 10
&=
sum&=10
^=
sum ^= 10
In this program, values from 0 9 are summed up and total 45 is displayed as output.
Assignment operators such as = and += are used in this program to assign the values and to sum up the
values.
1 # include <stdio.h>
2
3 int main()
4 {
5 int Total=0,i;
6 for(i=0;i<10;i++)
7 {
8 Total+=i; // This is same as Total = Toatal+i
9 }
10 printf("Total = %d", Total);
11 }
OUTPUT:
Total = 45
C Relational Operators
RELATIONAL OPERATORS IN C:
Relational operators are used to find the relation between two variables. i.e. to compare the values of two
variables in a C program.
S.no
Operators
Example
Description
>
x>y
x is greater than y
<
x<y
x is less than y
>=
x >= y
<=
x <= y
==
x == y
x is equal to y
!=
x != y
x is not equal to y
In this program, relational operator (==) is used to compare 2 values whether they are equal are not.
If both values are equal, output is displayed as values are equal. Else, output is displayed as values are not
equal.
Note : double equal sign (==) should be used to compare 2 values. We should not single equal sign (=).
1 #include <stdio.h>
2
3 int main()
4 {
5 int m=40,n=20;
6 if (m == n)
7 {
8 printf("m and n are equal");
9 }
10 else
11 {
12 printf("m and n are not equal");
13 }
14 }
OUTPUT:
m and n are not equal
C Logical Operators
LOGICAL OPERATORS IN C:
These operators are used to perform logical operations on the given expressions.
There are 3 logical operators in C language. They are, logical AND (&&), logical OR (||) and logical NOT (!).
S.no
Operators
Name
Example
Description
&&
logical AND
(x>5)&&(y<5)
||
logical OR
(x>=10)||(y>=10)
!((x>5)&&(y<5))
logical NOT
In this program, operators (&&, || and !) are used to perform logical operations on the given expressions.
&& operator if clause becomes true only when both conditions (m>n and m! =0) is true. Else, it becomes
false.
|| Operator if clause becomes true when any one of the condition (o>p || p!=20) is true. It becomes false
when none of the condition is true.
! Operator It is used to reverses the state of the operand.
If the conditions (m>n && m!=0) is true, true (1) is returned. This value is inverted by ! operator.
So, ! (m>n and m! =0) returns false (0).
These operators are used to perform bit operations. Decimal values are converted into binary values which are
the sequence of bits and bit wise operators work on these bits.
Bit wise operators in C language are & (bitwise AND), | (bitwise OR), ~ (bitwise OR), ^ (XOR), << (left shift)
and >> (right shift).
TRUTH TABLE FOR BIT WISE OPERATION BIT WISE OPERATORS
x
x|y
x&y
x^y
Operator_symbol
Operator_name
&
Bitwise_AND
Bitwise OR
Bitwise_NOT
XOR
<<
Left Shift
>>
Right Shift
Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y= 01010000
Bit wise left shift and right shift : In left shift operation x << 1 , 1 means that the bits will be left shifted by
one place. If we use it as x << 2 , then, it means that the bits will be left shifted by 2 places.
EXAMPLE PROGRAM FOR BIT WISE OPERATORS IN C:
In this example program, bit wise operations are performed as shown above and output is displayed in decimal
format.
1 #include <stdio.h>
2
3 int main()
4 {
5 int m = 40,n = 80,AND_opr,OR_opr,XOR_opr,NOT_opr ;
6 AND_opr = (m&n);
7 OR_opr = (m|n);
8 NOT_opr = (~m);
9 XOR_opr = (m^n);
10 printf("AND_opr value = %d\n",AND_opr );
11 printf("OR_opr value = %d\n",OR_opr );
12 printf("NOT_opr value = %d\n",NOT_opr );
13 printf("XOR_opr value = %d\n",XOR_opr );
14 printf("left_shift value = %d\n", m << 1);
15 printf("right_shift value = %d\n", m >> 1);
16 }
OUTPUT:
AND_opr value = 0
OR_opr value = 120
Conditional operators return one value if condition is true and returns another value is condition is false.
In above example, if A is greater than 100, 0 is returned else 1 is returned. This is equal to if else conditional
statements.
EXAMPLE PROGRAM FOR CONDITIONAL/TERNARY OPERATORS IN C:
1 #include <stdio.h>
2
3 int main()
4 {
5 int x=1, y ;
6 y = ( x ==1 ? 2 : 0 ) ;
7 printf("x value is %d\n", x);
8 printf("y value is %d", y);
9 }
OUTPUT:
x value is 1
y value is 2
C Increment/decrement Operators
Increment operators are used to increase the value of the variable by one and decrement operators are used to
decrease the value of the variable by one in C programs.
Syntax:
Increment operator: ++var_name; (or) var_name++;
Decrement operator: -var_name; (or) var_name -;
Example:
Increment operator : ++ i ; i ++ ;
Decrement operator : i ; i ;
In this program, value of i is incremented one by one from 1 up to 9 using i++ operator and output is
displayed as 1 2 3 4 5 6 7 8 9.
1 //Example for increment operators
2
3 #include <stdio.h>
4 int main()
5 {
6
int i=1;
7
while(i<10)
8
{
9
printf("%d ",i);
10
i++;
11
}
12 }
OUTPUT:
123456789
EXAMPLE PROGRAM FOR DECREMENT OPERATORS IN C:
In this program, value of I is decremented one by one from 20 up to 11 using i operator and output is
displayed as 20 19 18 17 16 15 14 13 12 11.
//Example for decrement operators
1
2
3 #include <stdio.h>
4 int main()
5 {
6
int i=20;
7
while(i>10)
8
{
9
printf("%d ",i);
10
i--;
11
}
12 }
OUTPUT:
20 19 18 17 16 15 14 13 12 11
DIFFERENCE BETWEEN PRE/POST INCREMENT & DECREMENT OPERATORS IN C:
Below table will explain the difference between pre/post increment and decrement operators in C.
S.n
o
Operator type
Pre increment
Postincrement
Pre decrement
Post_decrement
Operator
Description
++i
i++
Above 3 steps are continued until while expression becomes false and output is displayed as 1 2 3 4.
EXAMPLE PROGRAM FOR POST INCREMENT OPERATORS IN C:
1 #include <stdio.h>
2 int main()
3 {
4
int i=0;
5
while(i++ < 5 )
6
{
7
printf("%d ",i);
8
}
9
return 0;
10 }
OUTPUT:
12345
Above 3 steps are continued until while expression becomes false and output is displayed as 1 2 3 4 5.
EXAMPLE PROGRAM FOR PRE DECREMENT OPERATORS IN C:
1 #include <stdio.h>
2 int main()
3 {
4
int i=10;
5
while(--i > 5 )
6
{
7
printf("%d ",i);
8
}
9
return 0;
10 }
OUTPUT:
9876
Above 3 steps are continued until while expression becomes false and output is displayed as 9 8 7 6.
EXAMPLE PROGRAM FOR POST DECREMENT OPERATORS IN C:
1 #include <stdio.h>
2 int main()
3 {
4
int i=10;
5
while(i-- > 5 )
6
{
7
printf("%d ",i);
8
}
9
return 0;
10 }
OUTPUT:
98765
Above 3 steps are continued until while expression becomes false and output is displayed as 9 8 7 6 5.
>
C Special Operators
SPECIAL OPERATORS IN C:
Operator
s
Description
&
Sizeof ()
In this program, & symbol is used to get the address of the variable and * symbol is used to get the value
of the variable that the pointer is pointing to. Please refer C pointer topic to know more about pointers.
1 #include <stdio.h>
2 int main()
3 {
4 int *ptr, q;
5 q = 50;
6 /* address of q is assigned to ptr */
7 ptr = &q;
8 /* display q's value using ptr variable */
9 printf("%d", *ptr);
10 return 0;
11 }
OUTPUT:
50
EXAMPLE PROGRAM FOR SIZEOF() OPERATOR IN C:
sizeof() operator is used to find the memory space allocated for each C data types.
1 #include <stdio.h>
2 #include <limits.h>
3
4 int main()
5 {
6 int a;
7 char b;
8 float c;
9 double d;
10 printf("Storage size for int data type:%d \n",sizeof(a));
11 printf("Storage size for char data type:%d \n",sizeof(b));
12 printf("Storage size for float data type:%d \n",sizeof(c));
13 printf("Storage size for double data type:%d\n",sizeof(d));
14 return 0;
15 }
OUTPUT:
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8
1.
2.
3.
In decision control statements (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
Decision control
statements
Syntax/Description
Syntax:
if (condition)
{ Statements; }
Description:
In these type of statements, if condition is true, then respective block of code is
executed.
if
Syntax:
if (condition)
{ Statement1; Statement2; }
else
{ Statement3; Statement4; }
Description:
In these type of statements, group of statements are executed when condition is true.
If condition is false, then else part statements are executed.
ifelse
Syntax:
if (condition1){ Statement1; }
else_if(condition2)
{ Statement2; }
else Statement 3;
Description:
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.
nested if
EXAMPLE PROGRAM FOR IF STATEMENT IN C:
In if control statement, respective block of code is executed when condition is true.
1 int main()
2 {
3 int m=40,n=40;
4 if (m == n)
5 {
6 printf("m and n are equal");
7 }
8 }
OUTPUT:
m and n are equal
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m == n)
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
}
OUTPUT:
m and n are not equal
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.
#include <stdio.h>
int main()
{
int m=40,n=20;
if (m>n) {
printf("m is greater than n");
}
else if(m<n) {
printf("m is less than n");
}
else {
printf("m is equal to n");
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
OUTPUT:
m is greater than n
for
while
do-while
Syntax for each C loop control statements are given in below table with description.
S.n
o
Loop
Name
Syntax
Description
Where,
exp1 variable initialization
( Example: i=0, j=2, k=3 )
exp2 condition checking
( Example: i>5, j<3, k=3 )
exp3 increment/decrement
( Example: ++i, j, ++k )
while
while (condition)
{ statements; }
where,
condition might be a>5, i<10
do while
do { statements; }
while (condition);
where,
condition might be a>5, i<10
for
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d ",i);
}
}
OUTPUT:
0123456789
EXAMPLE PROGRAM (WHILE LOOP) IN C:
In while loop control statement, loop is executed until condition becomes false.
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
int main()
{
int i=3;
while(i<10)
{
printf("%d\n",i);
i++;
}
13 }
OUTPUT:
3456789
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
int main()
{
int i=1;
do
{
printf("Value of i is %d\n",i);
i++;
}while(i<=4 && i>=2);
}
OUTPUT:
Value of i is 1
Value of i is 2
Value of i is 3
Value of i is 4
DIFFERENCE BETWEEN WHILE & DO WHILE LOOPS IN C:
S.n
o
while
do while
Loop is
executed only
when
condition is
true.
switch
break
continue
goto
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
int main ()
{
int value = 3;
switch(value)
{
case 1:
printf(Value is 1 \n );
break;
case 2:
printf(Value is 2 \n );
break;
case 3:
printf(Value is 3 \n );
break;
case 4:
printf(Value is 4 \n );
break;
default :
printf(Value is other than 1,2,3,4 \n );
}
return 0;
}
Output:
Value is 3
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;
#include <stdio.h>
int main()
{
4
5
6
7
8
9
10
11
12
13
14
15
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("\nComing out of for loop when i = 5");
break;
}
printf("%d ",i);
}
}
OUTPUT:
01234
Coming out of for loop when i = 5
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;
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5 || i==6)
{
printf("\nSkipping %d from display using " \
"continue statement \n",i);
continue;
}
printf("%d ",i);
}
}
OUTPUT:
01234
Skipping 5 from display using continue statement
Skipping 6 from display using continue statement
789
4. 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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("\nWe are using goto statement when i = 5");
goto HAI;
}
printf("%d ",i);
}
HAI : printf("\nNow, we are inside label name \"hai\" \n");
}
OUTPUT:
01234
We are using goto statement when i = 5
Now, we are inside label name hai
C Type Qualifiers
C type qualifiers : The keywords which are used to modify the properties of a variable are called type
qualifiers.
const
volatile
1. CONST KEYWORD:
Constants are also like normal variables. But, only difference is, their values cant 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:
Please refer C Constants 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 variables 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 _name
TYPES OF STORAGE CLASS SPECIFIERS IN C:
There are 4 storage class specifiers available in C language. They are,
1.
2.
3.
4.
auto
extern
static
register
S.
No.
Storage
Specifier
Storage
place
Initial /
default
value
Scope
Life
auto
CPU
Memory
Garbage
value
local
Global
extern
CPU
memory
Zero
static
CPU
memory
Zero
local
register
Register
memory
Garbage
value
local
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.
#include<stdio.h>
void increment(void);
int main()
{
increment();
increment();
increment();
increment();
return 0;
}
void increment(void)
{
auto int i = 0 ;
printf ( "%d ", i ) ;
i++;
}
OUTPUT:
0000
EXAMPLE PROGRAM FOR STATIC VARIABLE IN C:
Static variables retain the value of the variable between different function calls.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
OUTPUT:
0123
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.
1
2
3
4
5
6
7
8
9
10
11
#include<stdio.h>
int x = 10 ;
int main( )
{
extern int y;
printf("The value of x is %d \n",x);
printf("The value of y is %d",y);
return 0;
}
int y=50;
OUTPUT:
The value of x is 10
The value of y is 50
EXAMPLE PROGRAM FOR REGISTER VARIABLE IN C:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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)
#include <stdio.h>
int main()
{
register int i;
int arr[5];// declaring array
arr[0] = 10;// Initializing array
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d \n", i, arr[i]);
}
return 0;
}
OUTPUT:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
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.
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,
1.
2.
Array initialization
Accessing array
Syntax: data_type
arr_name
[arr_size];
data_type arr_name
[arr_size]=(value1, value2,
value3,.);
arr_name[index];
age[0];_/*0_is_accessed*/age[1];_/*1_is_accessed*/age[2];
_/*2_is_accessed*/
#include<stdio.h>
int main()
{
int i;
int arr[5] = {10,20,30,40,50};
// declaring and Initializing array in C
//To initialize all array elements to 0, use int arr[5]={0};
/* Above array can be initialized as below also
arr[0] = 10;
arr[1] = 20;
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
arr[2] = 30;
arr[3] = 40;
arr[4] = 50; */
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d \n", i, arr[i]);
}
}
OUTPUT:
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
2. TWO DIMENSIONAL ARRAY IN C:
Array declaration
Array initialization
Accessing
array
data_type arr_name[2][2]
= {{0,0},{0,1},{1,0},
{1,1}};
arr_name[index
];
arr [0] [0] =
1; arr [0] ]1] =
2;arr [1][0] =
3;
Example:int arr[2][2];
#include<stdio.h>int main(){
int i,j;
// declaring and Initializing array
int arr[2][2] = {10,20,30,40};
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
34
35
Output:
value of arr[0] [0] is 10
value of arr[0] [1] is 20
value of arr[1] [0] is 30
value of arr[1] [1] is 40
C String
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.
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.
S.n
o
String
functions
Description
strcat ( )
strncat ( )
strcpy ( )
strncpy ( )
strlen ( )
strcmp ( )
strcmpi_(.)
strchr ( )
strrchr ( )
10
strstr ( )
11
strrstr ( )
12
strdup ( )
13
strlwr ( )
14
strupr ( )
15
strrev ( )
16
strset ( )
17
strnset ( )
18
strtok ( )
C strcat() function
strcat( ) function in C language concatenates two given strings. It concatenates source string at the end of
destination string. Syntax for strcat( ) function is given below.
Example :
In this program, two strings fresh2refresh and C tutorial are concatenated using strcat( ) function
and result is displayed as C tutorial fresh2refresh.
#include <stdio.h>
#include <string.h>
1
2
3
4 int main( )
5 {
6
char source[ ] = " fresh2refresh" ;
7
char target[ ]= " C tutorial" ;
8
9
printf ( "\nSource string = %s", source ) ;
10 printf ( "\nTarget string = %s", target ) ;
11
12 strcat ( target, source ) ;
13
14 printf ( "\nTarget string after strcat( ) = %s", target ) ;
15 }
OUTPUT:
Source string
= fresh2refresh
Target string
= C tutorial
Target string after strcat( ) = C tutorial fresh2refresh
C strncat() function
strncat( ) function in C language concatenates ( appends ) portion of one string at the end of another
string. Syntax for strncat( ) function is given below.
Example :
strncat ( str2, str1, 3 ); First 3 characters of str1 is concatenated at the end of str2.
strncat ( str1, str2, 3 ); First 3 characters of str2 is concatenated at the end of str1.
In strncat( ) operation, null character of destination string is overwritten by source strings first character and
null character is added at the end of new destination string which is created after strncat( ) operation.
In this program, first 5 characters of the string fresh2refresh is concatenated at the end of the
string C tutorial using strncat( ) function and result is displayed as C tutorial fres.
#include <stdio.h>
#include <string.h>
1
2
3
4 int main( )
5 {
6
char source[ ] = " fresh2refresh" ;
7
char target[ ]= "C tutorial" ;
8
9
printf ( "\nSource string = %s", source ) ;
10 printf ( "\nTarget string = %s", target ) ;
11
12 strncat ( target, source, 5 ) ;
13
14 printf ( "\nTarget string after strncat( ) = %s", target ) ;
15 }
OUTPUT:
Source string
= fresh2refresh
Target string
= C tutorial
Target string after strcat( ) = C tutorial fres
C strcpy() function
strcpy( ) function copies contents of one string into another string. Syntax for strcpy function is given below.
Example:
If destination string length is less than source string, entire source string value wont be copied into destination
string.
For example, consider destination string length is 20 and source string length is 30. Then, only 20 characters
from source string will be copied into destination string and remaining 10 characters wont be copied and will be
truncated.
1
2
3
4
5
6
7
8
In this program, source string fresh2refresh is copied into target string using strcpy( ) function.
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
printf ( "\nsource string = %s", source ) ;
9
printf ( "\ntarget string = %s", target ) ;
10 strcpy ( target, source ) ;
11 printf ( "\ntarget string after strcpy( ) = %s", target ) ;
12 return 0;
13 }
OUTPUT:
source string = fresh2refresh
target string =
target string after strcpy( ) = fresh2refresh
C strncpy() function
strncpy( ) function copies portion of contents of one string into another string. Syntax for strncpy( ) function is
given below.
Example:
If destination string length is less than source string, entire source string value wont be copied into destination
string.
For example, consider destination string length is 20 and source string length is 30.
If you want to copy 25 characters from source string using strncpy( ) function, only 20 characters from source
string will be copied into destination string and remaining 5 characters wont be copied and will be truncated.
1
2
3
4
5
6
7
8
9
10
11
12
13
In this program, only 5 characters from source string fresh2refresh is copied into target string using
strncpy( ) function.
#include <stdio.h>
#include <string.h>
int main( )
{
char source[ ] = "fresh2refresh" ;
char target[20]= "" ;
printf ( "\nsource string = %s", source ) ;
printf ( "\ntarget string = %s", target ) ;
strncpy ( target, source, 5 ) ;
printf ( "\ntarget string after strcpy( ) = %s", target ) ;
return 0;
}
OUTPUT:
source string = fresh2refresh
target string =
target string after strncpy( ) = fresh
C strlen() function
strlen( ) function in C gives the length of the given string. Syntax for strlen( ) function is given below.
strlen( ) function counts the number of characters in a given string and returns the integer value.
It stops counting the character when null character is found. Because, null character indicates the end of the
string in C.
In below example program, length of the string fresh2refres.com is determined by strlen( ) function as
below. Length of this string 17 is displayed as output.
#include <stdio.h>
#include <string.h>
1
2
3
4 int main( )
5 {
6
int len;
7
char array[20]="fresh2refresh.com" ;
8
9
len = strlen(array) ;
10
11
printf ( "\string length = %d \n" , len ) ;
12
return 0;
13 }
OUTPUT:
string length = 17
C strcmp() function
strcmp( ) function in C compares two given strings and returns zero if they are same.
If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0 value. Syntax for
strcmp( ) function is given below.
strcmp( ) function is case sensitive. i.e, A and a are treated as different characters.
In this program, strings fresh and refresh are compared. 0 is returned when strings are equal.
Negative value is returned when str1 < str2 and positive value is returned when str1 > str2.
1 #include <stdio.h>
2 #include <string.h>
3 int main( )
4 {
5
char str1[ ] = "fresh" ;
6
char str2[ ] = "refresh" ;
7
int i, j, k ;
8
i = strcmp ( str1, "fresh" ) ;
9
j = strcmp ( str1, str2 ) ;
10 k = strcmp ( str1, "f" ) ;
strcmpi( ) function in C is same as strcmp() function. But, strcmpi( ) function is not case sensitive. i.e, A and
a are treated as same characters. Where as, strcmp() function treats A and a as different characters.
strcmpi() function is non standard function which may not available in standard library in C.
Both functions compare two given strings and returns zero if they are same.
If length of string1 < string2, it returns < 0 value. If length of string1 > string2, it returns > 0 value. Syntax for
strcmp( ) function is given below.
1
2
3
4
5
6
7
8
9
10
11
12
13
In this program, strings fresh and refresh are compared. 0 is returned when strings are equal.
Negative value is returned when str1 < str2 and positive value is returned when str1 > str2.
#include <stdio.h>
#include <string.h>
int main( )
{
char str1[ ] = "fresh" ;
char str2[ ] = "refresh" ;
int i, j, k ;
i = strcmpi ( str1, "FRESH" ) ;
j = strcmpi ( str1, str2 ) ;
k = strcmpi ( str1, "f" ) ;
printf ( "\n%d %d %d", i, j, k ) ;
return 0;
}
OUTPUT:
0 -1 1
C strchr() function
strchr( ) function returns pointer to the first occurrence of the character in a given string. Syntax for strchr( )
function is given below.
1
2
In this program, strchr( ) function is used to locate first occurrence of the character i in the
string This is a string for testing. Character i is located at position 3 and pointer is returned at
first occurrence of the character i.
#include <stdio.h>
#include <string.h>
3 int main ()
4 {
5
char string[55] ="This is a string for testing";
6
char *p;
7
p = strchr (string,'i');
8
9
printf ("Character i is found at position %d\n",p-string+1);
10 printf ("First occurrence of character \"i\" in \"%s\" is" \
11
" \"%s\"",string, p);
12
13 return 0;
14 }
OUTPUT:
Character i is found at position 3
First occurrence of character i in This is a string for testing is is is a string for testing
Character i is found at position 6
Occurrence of character i : 2
Occurrence of character i in This is a string for testing is is a string for testing
Character i is found at position 14
Occurrence of character i : 3
Occurrence of character i in This is a string for testing is ing for testing
Character i is found at position 26
Occurrence of character i : 4
Occurrence of character i in This is a string for testing is ing
C strrchr() function
strrchr( ) function in C returns pointer to the last occurrence of the character in a given string. Syntax for strrchr( )
function is given below.
char *strrchr(const char *str, int character);
EXAMPLE PROGRAM FOR STRRCHR() FUNCTION IN C:
In this program, strrchr( ) function is used to locate last occurrence of the character i in the string This is a string for
testing. Last occurrence of character i is located at position 26 and pointer is returned at last occurrence of
the character i.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>
#include <string.h>
int main ()
{
char string[55] ="This is a string for testing";
char *p;
p = strrchr (string,'i');
printf ("Character i is found at position %d\n",p-string+1);
printf ("Last occurrence of character \"i\" in \"%s\" is" \
" \"%s\"",string, p);
return 0;
}
OUTPUT:
#include <stdio.h>
#include <string.h>
int main ()
{
char string[55] ="This is a test string for testing";
char *p;
p = strstr (string,"test");
if(p)
{
printf("string found\n" );
printf ("First occurrence of string \"test\" in \"%s\" is"\
" \"%s\"",string, p);
}
else printf("string not found\n" );
return 0;
}
OUTPUT:
string found
First occurrence of string test in This is a test string for testing is test string for testing
C strrstr() function
strrstr( ) function returns pointer to the last occurrence of the string in a given string. Syntax for strrstr( )
function is given below.
char *strrstr(const char *str1, const char *str2);
strrstr( ) function is non standard function which may not available in standard library in C.
#include <stdio.h>
#include <string.h>
int main ()
{
char string[55] ="This is a test string for testing";
6
char *p;
7
p = strrstr (string,"test");
8
if(p)
9
{
10
printf("string found\n" );
11
printf ("Last occurrence of string \"test\" in \"%s\" is"\
12
" \"%s\"",string, p);
13 }
14 else printf("string not found\n" );
15 return 0;
16 }
OUTPUT:
string found
Last occurrence of string test in This is a test string for testing is testing
C strdup() function
strdup( ) function in C duplicates the given string. Syntax for strdup( ) function is given below.
char *strdup(const char *string);
strdup( ) function is non standard function which may not available in standard library in C.
#include <stdio.h>
#include <string.h>
int main()
{
char *p1 = "Raja";
char *p2;
p2 = strdup(p1);
printf("Duplicated string is : %s", p2);
return 0;
}
OUTPUT:
Duplicated string is : Raja
C strlwr() function
strlwr( ) function converts a given string into lowercase. Syntax for strlwr( ) function is given below.
char *strlwr(char *string);
strlwr( ) function is non standard function which may not available in standard library in C.
In this program, string MODIFY This String To LOwer is converted into lower case using strlwr( ) function and result
is displayed as modify this string to lower.
1
2
3
4
5
6
7
8
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "MODIFY This String To LOwer";
printf("%s\n",strlwr (str));
return 0;
}
OUTPUT:
modify this string to lower
C strupr() function
strupr( ) function converts a given string into uppercase. Syntax for strupr( ) function is given below.
char *strupr(char *string);
strupr( ) function is non standard function which may not available in standard library in C.
#include<stdio.h>
#include<string.h>
int main()
{
char str[ ] = "Modify This String To Upper";
printf("%s\n",strupr(str));
return 0;
}
OUTPUT:
MODIFY THIS STRING TO UPPER
C strrev() function
strrev( ) function reverses a given string in C language. Syntax for strrev( ) function is given below.
char *strrev(char *string);
strrev( ) function is non standard function which may not available in standard library in C.
#include<stdio.h>
2
3
4
5
6
7
8
9
10
11
12
13
#include<string.h>
int main()
{
char name[30] = "Hello";
printf("String before strrev( ) : %s\n",name);
printf("String after strrev( ) : %s",strrev(name));
return 0;
}
OUTPUT:
String before strrev( ) : Hello
String after strrev( ) : olleH
C strset() function
strset( ) function sets all the characters in a string to given character. Syntax for strset( ) function is given
below.
char *strset(char *string, int c);
strset( ) function is non standard function which may not available in standard library in C.
#include<stdio.h>
#include<string.h>
int main()
{
char str[20] = "Test String";
printf("Original string is : %s", str);
printf("Test string after strset() : %s",strset(str,'#'));
printf("After string set: %s",str);
return 0;
}
OUTPUT:
Original string is
: Test String
Test string after strset() : ###########
C strnset() function
strnset( ) function sets portion of characters in a string to given character. Syntax for strnset( ) function is given
below.
char *strnset(char *string, int c);
strnset( ) function is non standard function which may not available in standard library in C.
In this program, first 4 characters of the string Test String is set to # using strnset( ) function and output is displayed
as #### String.
1
2
3
4
5
6
7
8
9
10
11
#include<stdio.h>
#include<string.h>
int main()
{
char str[20] = "Test String";
printf("Original string is : %s", str);
printf("Test string after string n set" \
" : %s", strnset(str,'#',4));
printf("After string n set : %s", str);
return 0;
}
OUTPUT:
Original string is
: Test String
Test string after string set : #### String
C strtok() function
strtok( ) function in C tokenizes/parses the given string using delimiter. Syntax for strtok( ) function is given below.
char * strtok ( char * str, const char * delimiters );
EXAMPLE PROGRAM FOR STRTOK() FUNCTION IN C:
In this program, input string Test,string1,Test,string2:Test:string3 is parsed using strtok() function. Delimiter comma
(,) is used to separate each sub strings from input string.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
#include <string.h>
int main ()
{
char string[50] ="Test,string1,Test,string2:Test:string3";
char *p;
printf ("String \"%s\" is split into tokens:\n",string);
p = strtok (string,",:");
while (p!= NULL)
{
printf ("%s\n",p);
p = strtok (NULL, ",:");
}
return 0;
}
OUTPUT:
String Test,string1,Test,string2:Test:string3 is split into tokens:
Test
string1
Test
string2
Test
string3
C Pointer
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.
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).
#include <stdio.h>
int main()
{
int *ptr, q;
q = 50;
/* address of q is assigned to ptr */
ptr = &q;
/* display q's value using ptr variable */
printf("%d", *ptr);
return 0;
}
OUTPUT:
50
malloc()
calloc()
realloc()
free()
S.no
Function
Syntax
malloc ()
calloc ()
realloc ()
free ()
free (pointer_name);
1. MALLOC() FUNCTION IN C:
malloc () function is used to allocate space in memory during the execution of the program.
malloc () does not initialize the memory allocated during execution. It carries garbage value.
malloc () function returns null pointer if it couldnt able to allocate requested amount of memory.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"fresh2refresh.com");
}
printf("Dynamically allocated memory content : " \
"%s\n", mem_allocation );
free(mem_allocation);
}
OUTPUT:
Dynamically allocated memory content : fresh2refresh.com
2. CALLOC() FUNCTION IN C:
calloc () function is also like malloc () function. But calloc () initializes the allocated memory to zero. But,
malloc() doesnt.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = calloc( 20, sizeof(char) );
if( mem_allocation== NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"fresh2refresh.com");
}
printf("Dynamically allocated memory content : " \
"%s\n", mem_allocation );
free(mem_allocation);
}
OUTPUT:
Dynamically allocated memory content : fresh2refresh.com
3. REALLOC() FUNCTION IN C:
realloc () function modifies the allocated memory size by malloc () and calloc () functions to new size.
If enough space doesnt exist in memory of current block to extend, new block is allocated for the full size of
reallocation, then copies the existing data to new block and then frees the old block.
4. FREE() FUNCTION IN C:
free () function frees the allocated memory by malloc (), calloc (), realloc () functions and returns the memory
to the system.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char *mem_allocation;
/* memory is allocated dynamically */
mem_allocation = malloc( 20 * sizeof(char) );
if( mem_allocation == NULL )
{
printf("Couldn't able to allocate requested memory\n");
}
else
{
strcpy( mem_allocation,"fresh2refresh.com");
}
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 }
OUTPUT:
Dynamically allocated memory content : fresh2refresh.com
Resized memory : space is extended upto 100 characters
DIFFERENCE BETWEEN STATIC MEMORY ALLOCATION AND DYNAMIC MEMORY
ALLOCATION IN C:
S.n
o
malloc()
calloc()
C Function
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.
1.
2.
3.
4.
5.
6.
7.
8.
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?
1.
Call by value
2.
Call by reference
C function arguments and return values
1.
C function with arguments and with return value
2.
C function with arguments and without return value
3.
C function without arguments and without return value
4.
C function without arguments and with return value
Types of C functions
1.
Library functions in C
2.
User defined functions in C
1.
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.
Function declaration or prototype This informs compiler about the function name, function parameters and
return values data type.
Function call This calls the actual function
Function definition This contains all the statements to be executed.
C functions aspects
syntax
function definition
function call
function declaration
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.
#include<stdio.h>
// function prototype, also called function declaration
float square ( float x );
// main function, program starts from here
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int main( )
{
float m, n ;
printf ( "\nEnter some number for finding square \n");
scanf ( "%f", &m ) ;
// function call
n = square ( m ) ;
printf ( "\nSquare of the given number %f is %f",m,n );
}
float square ( float x ) // function definition
{
float p ;
p=x*x;
return ( p ) ;
}
OUTPUT:
Enter some number for finding square
2
Square of the given number 2.000000 is 4.000000
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,
1.
2.
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int a, int b);
int main()
{
int m = 22, n = 44;
// calling swap function by value
printf(" values before swap m = %d \nand n = %d", m, n);
swap(m, n);
}
void swap(int a, int b)
{
int tmp;
tmp = a;
a = b;
b = tmp;
printf(" \nvalues after swap m = %d\n and n = %d", a, b);
}
OUTPUT:
values before swap m = 22
and n = 44
values after swap m = 44
and n = 22
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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.
#include<stdio.h>
// function prototype, also called function declaration
void swap(int *a, int *b);
int main()
{
int m = 22, n = 44;
// calling swap function by reference
printf("values before swap m = %d \n and n = %d",m,n);
swap(&m, &n);
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
17
*a = *b;
18
*b = tmp;
19
printf("\n values after swap a = %d \nand b = %d", *a, *b);
20 }
OUTPUT:
values before swap m = 22
and n = 44
values after swap a = 44
and b = 22
C functions aspects
syntax
function declaration:
int function ( int );
function call: function ( a );
function definition:
int function( int a )
{
statements;
return a;
}
function declaration:
void function ( int );
function call: function( a );
function definition:
void function( int a )
{
statements;
}
function declaration:
void function();
function call: function();
function definition:
void function()
{
statements;
}
function declaration:
int function ( );
function call: function ( );
function definition:
int function( )
{
statements;
return a;
}
NOTE:
If the return data type of a function is void, then, it cant 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.
#include<stdio.h>
#include<string.h>
int function(int, int[], char[]);
int main()
{
int i, a = 20;
int arr[5] = {10,20,30,40,50};
char str[30] = "\"fresh2refresh\"";
printf(" ***values before modification***\n");
printf("value of a is %d\n",a);
for (i=0;i<5;i++)
{
// Accessing each variable
printf("value of arr[%d] is %d\n",i,arr[i]);
}
printf("value of str is %s\n",str);
printf("\n ***values after modification***\n");
a= function(a, &arr[0], &str[0]);
printf("value of a is %d\n",a);
for (i=0;i<5;i++)
{
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
OUTPUT:
***values before modification***
value of a is 20
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
value of str is fresh2refresh
***values after modification***
value of a is 40
value of arr[0] is 60
value of arr[1] is 70
value of arr[2] is 80
value of arr[3] is 90
value of arr[4] is 100
value of str is modified string
#include<stdio.h>
void function(int, int[], char[]);
int main()
{
int a = 20;
int arr[5] = {10,20,30,40,50};
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
OUTPUT:
value of a is 20
value of arr[0] is 10
value of arr[1] is 20
value of arr[2] is 30
value of arr[3] is 40
value of arr[4] is 50
value of str is fresh2refresh
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include<stdio.h>
void test();
int main()
{
test();
return 0;
}
void test()
{
int a = 50, b = 80;
printf("\nvalues : a = %d and b = %d", a, b);
}
OUTPUT:
values : a = 50 and b = 80
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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include<stdio.h>
int sum();
int main()
{
int addition;
addition = sum();
printf("\nSum of two given values = %d", addition);
return 0;
}
int sum()
{
int a = 50, b = 80, sum;
sum = a + b;
return sum;
}
OUTPUT:
Sum of two given values = 130
DO YOU KNOW HOW MANY VALUES CAN BE RETURN FROM C FUNCTIONS?
C 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.
Please check the below links for actual C source code for the respective C header files.
1. C stdio.h source code
2. C conio.h source code
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.
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.
Header file
Description
stdio.h
conio.h
string.h
stdlib.h
math.h
time.h
ctype.h
stdarg.h
signal.h
setjmp.h
locale.h
errno.h
assert.h
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.
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.
STEP 6:
Let us see how to use our newly added library function in a C program.
1
2
3
4
5
6
7
8
9
10
# include <stdio.h>
// Including our user defined function.
# include c:\\addition.h
int main ()
{
int total;
// calling function from library
total = addition (10, 20);
printf ("Total = %d \n", total);
}
OUTPUT:
Total = 30
argc
argv[]
where,
argc Number of arguments in the command line including program name
argv[] 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.
=
=
=
=
=
=
=
5
test
this
is
a
program
NULL
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) // command line arguments
{
if(argc!=5)
{
printf("Arguments passed through command line " \
"not equal to 5");
return 1;
}
printf("\n Program name : %s \n", argv[0]);
printf("1st arg : %s \n", argv[1]);
printf("2nd arg : %s \n", argv[2]);
printf("3rd arg : %s \n", argv[3]);
printf("4th arg : %s \n", argv[4]);
printf("5th arg : %s \n", argv[5]);
return 0;
}
OUTPUT:
Program name : test
1st arg : this
2nd arg : is
3rd arg : a
4th arg : program
5th arg : (null)
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.
#include <stdio.h>
#include <stdarg.h>
int add(int num,...);
int main()
{
printf("The value from first function call = " \
"%d\n", add(2,2,3));
printf("The value from second function call= " \
"%d \n", add(4,2,3,4,5));
/*Note - In function add(2,2,3),
first 2 is total number of arguments
2,3 are variable length arguments
In function add(4,2,3,4,5),
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
OUTPUT:
The value from first function call = 5
The value from second function call= 14
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
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:
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 Arithmetic functions
C functions which are used to perform mathematical operations in a program are called Arithmetic functions.
Example program for abs(), floor(), round(), ceil(), sqrt(), exp(), log(), sin(), cos(), tan(), pow() and trunc()
functions are given below.
If you want to know what is the structure and declaration of a C function, Please refer C_Function topic in
this tutorial.
math.h and stdlib.h header files support all the arithmetic functions in C language. All the
arithmetic functions used in C language are given below.
Click on each function name below for detail description and example programs.
S.n
o
Functio
n
Description
abs ( )
floor ( )
This function returns the nearest integer which is less than or equal to
the argument passed to this function.
round.(.)
ceil ( )
sin ( )
cos ( )
cosh ( )
exp ( )
tan ( )
10
tanh ( )
11
sinh ( )
12
log ( )
13
log10 ( )
14
sqrt ( )
This function is used to find square root of the argument passed to this
function.
15
pow ( )
16
trunc.(.)
This function truncates the decimal value from floating point value
and returns integer value.
C abs() function
abs( ) function in C returns the absolute value of an integer. The absolute value of a number is always positive.
Only integer values are supported in C.
stdlib.h header file supports abs( ) function in C language. Syntax for abs( ) function in C is given below.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int m = abs(200); // m is assigned to 200
int n = abs(-400); // n is assigned to -400
printf("Absolute value of m = %d\n", m);
printf("Absolute value of n = %d \n",n);
return 0;
}
OUTPUT:
Absolute value of m = 200
Absolute value of n = 400
C floor() function
floor( ) function in C returns the nearest integer value which is less than or equal to the floating point argument
passed to this function.
math.h header file supports floor( ) function in C language. Syntax for floor( ) function in C is given below.
#include <stdio.h>
#include <math.h>
int main()
{
5
6
7
8
9
10
11 }
OUTPUT:
floor of 5.100000 is 5.000000
floor of 5.900000 is 5.000000
floor of -5.400000 is -6.000000
floor of -6.900000 is -7.000000
C round() function
round( ) function in C returns the nearest integer value of the float/double/long double argument passed to this
function.
If decimal value is from .1 to .5, it returns integer value less than the argument. If decimal value is from .6
to .9, it returns the integer value greater than the argument.
math.h header file supports round( ) function in C language. Syntax for round( ) function in C is given
below.
#include <stdio.h>
#include <math.h>
int main()
{
float i=5.4, j=5.6;
printf("round of %f is %f\n", i, round(i));
printf("round of %f is %f\n", j, round(j));
return 0;
}
OUTPUT:
round of 5.400000 is 5.000000
round of 5.600000 is 6.000000
C ceil() function
ceil( ) function in C returns nearest integer value which is greater than or equal to the argument passed to this
function.
math.h header file supports ceil( ) function in C language. Syntax for ceil( ) function in C is given below.
#include <stdio.h>
#include <math.h>
int main()
{
float i=5.4, j=5.6;
printf("ceil of %f is %f\n", i, ceil(i));
printf("ceil of %f is %f\n", j, ceil(j));
return 0;
}
OUTPUT:
ceil of 5.400000 is 6.000000
ceil of 5.600000 is 6.000000
C sin() cos() tan() exp() log() function
sin( ), cos( ) and tan( ) functions in C are used to calculate sine, cosine and tangent values.
sinh( ), cosh( ) and tanh( ) functions are used to calculate hyperbolic sine, cosine and tangent values.
exp( ) function is used to calculate the exponential e to the xth power. log( ) function is used to calculates
natural logarithm and log10( ) function is used to calculates base 10 logarithm.
math.h header file supports all these functions in C language.
#include <stdio.h>
#include <math.h>
int main()
{
float i = 0.314;
float j = 0.25;
float k = 6.25;
float sin_value = sin(i);
float cos_value = cos(i);
float tan_value = tan(i);
float sinh_value = sinh(j);
float cosh_value = cosh(j);
float tanh_value = tanh(j);
float log_value = log(k);
float log10_value = log10(k);
float exp_value = exp(k);
printf("The value of sin(%f) : %f \n", i, sin_value);
printf("The value of cos(%f) : %f \n", i, cos_value);
printf("The value of tan(%f) : %f \n", i, tan_value);
printf("The value of sinh(%f) : %f \n", j, sinh_value);
printf("The value of cosh(%f) : %f \n", j, cosh_value);
printf("The value of tanh(%f) : %f \n", j, tanh_value);
printf("The value of log(%f) : %f \n", k, log_value);
printf("The value of log10(%f) : %f \n",k,log10_value);
printf("The value of exp(%f) : %f \n",k, exp_value);
return 0;
}
OUTPUT:
The value of sin(0.314000) : 0.308866
The value of cos(0.314000) : 0.951106
The value of tan(0.314000) : 0.324744
The value of sinh(0.250000) : 0.252612
The value of cosh(0.250000) : 1.031413
The value of tanh(0.250000) : 0.244919
The value of log(6.250000) : 1.832582
The value of log10(6.250000) : 0.795880
The value of exp(6.250000) : 518.012817
C sqrt() function
sqrt( ) function in C is used to find the square root of the given number.
math.h header file supports sqrt( ) function in C language. Syntax for sqrt( ) function in C is given below.
#include <stdio.h>
#include <math.h>
int main()
{
printf ("sqrt of 16 = %f\n", sqrt (16) );
printf ("sqrt of 2 = %f\n", sqrt (2) );
return 0;
}
OUTPUT:
sqrt of 16 = 4.000000
sqrt of 2 = 1.414214
C pow() function
#include <stdio.h>
#include <math.h>
int main()
{
printf ("2 power 4 = %f\n", pow (2.0, 4.0) );
trunc( ) function in C truncates the decimal value from floating point value and returns integer value.
math.h header file supports trunc( ) function in C language. Syntax for trunc( ) function in C is given below.
#include <stdio.h>
#include <math.h>
int main()
{
printf ("truncated value of 16.99 = %f\n", trunc (16.99) );
printf ("truncated value of 20.1 = %f\n", trunc (20.1) );
return 0;
}
OUTPUT:
truncated value of 16.99 = 16.000000
truncated value of 20.1 = 20.000000
ctype.h header file support all the below functions in C language. Click on each function name below for
detail description and example programs.
S.n
o
Function
Description
isalpha()
isdigit()
isalnum()
isspace()
islower()
isupper()
isxdigit()
iscntrl()
isprint()
10
ispunct()
11
isgraph()
12
tolower()
13
toupper()
C isalpha() function
isalpha( ) function in C language checks whether given character is alphabetic or not. Syntax for isalpha( )
function is given below.
#include <stdio.h>
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isalpha ( ch ) )
printf ( "\nEntered character is alphabetic" ) ;
else
printf ( "\nEntered character is not alphabetic" ) ;
}
OUTPUT:
isdigit( ) function in C language checks whether given character is digit or not. Syntax for isdigit( ) function is
given below.
#include <stdio.h>
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isdigit ( ch ) )
printf ( "\nEntered character is digit" ) ;
else
printf ( "\nEntered character is not digit" ) ;
}
OUTPUT:
Enter any character
200
Entered character is digit
C isalnum() function
isalnum() function in C language checks whether given character is alphanumeric or not. Syntax for isalnum( )
function is given below.
#include <stdio.h>
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isalnum ( ch ) )
printf ( "\nEntered character is alphanumeric" ) ;
else
printf ( "\nEntered character is not alphanumeric" ) ;
}
OUTPUT:
Enter any character
@
Entered character is not alphanumeric
C isspace() function
isspace( ) function in C language checks whether given character is space or not. Syntax for isspace( ) function
is given below.
#include <stdio.h>
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isspace ( ch ) )
printf ( "\nEntered character is space" ) ;
else
printf ( "\nEntered character is not space" ) ;
}
OUTPUT:
Enter any character
a
Entered character is not space
C islower() function
islower( ) function in C language checks whether given character is lower case or not. Syntax for islower( )
function is given below.
11 else
12 printf("\nEntered character is not lower case character");
13 }
OUTPUT:
Enter any character
a
Entered character is lower case character
C isupper() function
isupper( ) function in C language checks whether given character is upper case or not. Syntax for isupper( )
function is given below.
#include <stdio.h>
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if ( isupper ( ch ) )
printf ("\nEntered character is uppercase character");
else
printf("\nEntered character is not uppercase character");
}
OUTPUT:
Enter any character
A
Entered character is upper case character
C isxdigit() function
isxdigit( ) function in C language checks whether given character is hexadecimal or not. Syntax for isxdigit( )
function is given below.
#include <stdio.h>
int main()
{
char ch;
6
printf("Enter any character\n");
7
scanf("%c", &ch);
8
9
if ( isxdigit ( ch ) )
10
printf ( "\nEntered character is hexadecimal" ) ;
11 else
12
printf ( "\nEntered character is not hexadecimal" ) ;
13 }
OUTPUT:
Enter any character
#
Entered character is not hexadecimal
C iscntrl() function
iscntrl( ) function in C language checks whether given character is control character or not. Syntax for iscntrl( )
function is given below.
Control characters in C language are \a ( alert ), \b ( backspace ), \f ( form feed ), \n ( new line ), \r
( carriage return ), \t ( horizondal tab), \v ( vertical tab) and \0 ( null ).
Note:
#include <stdio.h>
int main()
{
char ch[5] ="abc\a";
int i = 0;
while(1)
{
if(iscntrl(ch[i]))
{
printf ( "control character is found at " \
"%dth position\n", i+1);
break;
}
i++;
}
return 0;
}
OUTPUT:
isprint( ) function in C language checks whether given character is printable character or not. Syntax for
isprint( ) function is given below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
OUTPUT:
fresh2refresh
C ispunct() function
ispunct( ) function in C language checks whether given character is punctuation or not. Syntax for ispunct( )
function is given below.
#include <stdio.h>
int main()
{
char ch = '!';
if ( ispunct ( ch ) )
printf ( "Character is a punctuation character" ) ;
else
printf ( "\nCharacter is not a punctuation character" ) ;
}
OUTPUT:
Character is a punctuation character
C isgraph() function
isgraph( ) function in C language checks whether given character is graphical character or not. Syntax for
isgraph( ) function is given below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
In this program, isgraph( ) function checks whether character is graphical character or not.
If its a graphical character, it is printed in output. Else, control is coming out of while loop. Output is printed as
fresh since space ( ) is not a graphical character and it cant be printed in output.
#include <stdio.h>
int main()
{
char string[50] ="fresh 2 refresh \n string";
int i = 0;
while(1)
{
if(isgraph(string[i]))
{
putchar(string[i]);
i++;
}
else break;
}
return 0;
}
OUTPUT:
fresh
C tolower() function
tolower( ) function in C language checks whether given character is alphabetic and converts to
lowercase. Syntax for tolower( ) function is given below.
#include <stdio.h>
int main()
{
char ch;
printf("Enter any character\n");
7
scanf("%c", &ch);
8
9
if(isalpha(ch))
10
printf ( "\nEntered character is converted into " \
11
"lower character : %c\n",tolower ( ch ) ) ;
12 else
13
printf("Entered character is not an alphabetic");
14 }
OUTPUT:
Enter any character
A
Entered character is converted into lower character : a
C toupper() function
toupper( ) function in C language checks whether given character is alphabetic and converts to
uppercase. Syntax for toupper( ) function is given below.
#include <stdio.h>
int main()
{
char ch;
printf("Enter any character\n");
scanf("%c", &ch);
if(isalpha(ch))
printf ( "\nEntered character is converted into " \
"upper character : %c\n",toupper ( ch ) ) ;
else
printf("Entered character is not an alphabetic");
}
OUTPUT:
Enter any character
a
Entered character is converted into upper character : A
Buffer manipulation functions in C work on the address of the memory block rather than the values inside the
address.
Example programs for memset(), memcpy(), memmove(), memcmp(), memicmp() and memchr() functions are
given below.
S.n
o
Function
Description
memset()
memcpy()
memmove()
memcmp()
memicmp()
memchr()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
memset( ) function is used to initialize specified number of bytes to null or to any other value in the buffer.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int i;
/* allocate memory for array of 5 elements */
char *a = (char *) malloc(5*sizeof(char));
printf("Values before memset\n");
for (i = 0; i < 5; ++i)
printf(" a[%d] = %d ,", i, a[i]);
/* All elements are set to 3. It can be set to any value */
memset(a, 3, 5*sizeof(char));
printf("\nValues after memset\n");
for (i = 0; i < 5; ++i)
printf(" a[%d] = %d ,", i, a[i]);
// remove x from memory
free(a);
return 0;
}
OUTPUT:
Values before memset
a[0] = 0 , a[1] = 0 , a[2] = 0 , a[3] = 0 , a[4] = 0
Values after memset
a[0] = 3 , a[1] = 3 , a[2] = 3 , a[3] = 3 , a[4] = 3
EXAMPLE PROGRAM FOR MEMCPY() FUNCTION IN C:
memcpy( ) function is used to copy a specified number of bytes from one memory to another.
1 #include <stdio.h>
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <string.h>
int main()
{
// define two identical arrays
char str1[10] = "fresh";
char str2[10] ;
if (memcpy(str2,str1, strlen(str1)))
{
printf("Elements in str1 are copied to str2 .\n");
printf("str1 = %s\n str2 = %s \n", str1, str2);
}
else
printf("Error while coping str1 into str2.\n");
return 0;
}
OUTPUT:
Elements in str1 are copied to str2 .
str1 = fresh
str2 = fresh
EXAMPLE PROGRAM FOR MEMMOVE() FUNCTION IN C:
memmove( ) function is used to copy a specified number of bytes from one memory to another or to overlap
on same memory.
#include <stdio.h>
#include <string.h>
int main()
{
// define two identical arrays
char str1[10] = "fresh";
1
2
3
4
5
6
7
8
printf("str1 before memmove\n");
9
printf("str1 = %s\n ", str1);
10
11 if (memmove(str1+2,str1, strlen(str1)))
12 {
13
printf("Elements in str1 are moved/overlapped on str1.\n");
14
printf("str1 = %s \n", str1);
15 }
16 else
17
printf("Error while coping str1 into str2.\n");
18 return 0;
19 }
OUTPUT:
str1 before memmove
str1 = fresh
Elements in str1 are moved/overlapped on str1 .
str1 = frfresh
memcmp( ) function is used to compare specified number of characters from two buffers.
1 #include <stdio.h>
2 #include <string.h>
3 int main()
4 {
5
// define two identical arrays
6
char str1[10] = "fresh";
7
char str2[10] = "refresh";
8
if (!memcmp(str1,str2, 5*sizeof(char)))
9
printf("Elements in str1 and str2 are same.\n");
10 else
11
printf("Elements in str1 and str2 are not same.\n");
12 return 0;
13 }
OUTPUT:
Elements in str1 and str2 are not same.
EXAMPLE PROGRAM FOR MEMICMP() FUNCTION IN C:
1
2
3
4
5
6
7
8
9
10
11
12
13
memicmp( ) function is used to compare specified number of characters from two buffers regardless of the
case of the characters.
If we use memcmp() function instead of memicmp, the output of the below program will be Elements in str1
and str2 are not same.
#include <stdio.h>
#include <string.h>
int main()
{
// define two identical arrays
char str1[10] = "fresh";
char str2[10] = "FRESH";
if (!memicmp(str1,str2, 5*sizeof(char)))
printf("Elements in str1 and str2 are same.\n");
else
printf("Elements in str1 and str2 are not same.\n");
return 0;
}
OUTPUT:
Elements in str1 and str2 are same.
EXAMPLE PROGRAM FOR MEMCHR() FUNCTION IN C:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
memchr( ) function is used to locate the first occurrence of the character in the specified string.
#include <stdio.h>
#include <string.h>
int main ()
{
char *ptr;
char string[] = "fresh2refresh";
ptr = (char *) memchr (string, 'h', strlen(string));
if (ptr != NULL)
printf ("character 'h' is found at " \
"position %d.\n", ptr-string+1);
else
printf ("character 'h' is not found.\n");
return 0;
15 }
OUTPUT:
character h is found at position 5.
Function
Description
setdate()
getdate()
clock()
time()
difftime()
This function is used to get the difference between two given times
strftime()
mktime()
localtime(
)
This function shares the tm structure that contains date and time informations
gmtime()
This function shares the tm structure that contains date and time informations
10
ctime()
This function is used to return string that contains date and time informations
11
asctime()
Tm structure contents are interpreted by this function as calendar time. This time is
converted into string.
#include<stdio.h>
#include<dos.h>
#include<conio.h>
int main()
{
struct date dt;
printf("Enter new date in the format(day month year)");
scanf("%d%d%d",&dt.da_day,&dt.da_mon,&dt.da_year);
setdate(&dt);
12
13 printf("Now, current system date is %d-%d-%d\n"
14 ,dt.da_day,dt.da_mon,dt.da_year);
15
16 return 0;
17 }
OUTPUT:
Enter new date in the format (day month year)
01 12 2012
Now, current system date is 01-12-2012
EXAMPLE PROGRAM FOR GETDATE() FUNCTION IN C:
This function is used to get the CPU time. Please note that other C compilers may not support this getdate() function
except turbo C.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include<stdio.h>
#include<dos.h>
int main()
{
struct date dt;
getdate(&dt);
printf("Operating system's current date is %d-%d-%d\n"
,dt.da_day,dt.da_mon,dt.da_year);
return 0;
}
OUTPUT:
Operating systems current date is 12-01-2012
EXAMPLE PROGRAM FOR CLOCK() FUNCTION IN C:
This function is used to get current system time
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
#include <time.h>
#include <math.h>
int main()
{
int i;
clock_t CPU_time_1 = clock();
printf("CPU start time is : %d \n", CPU_time_1);
for(i = 0; i < 150000000; i++);
clock_t CPU_time_2 = clock();
printf("CPU end time is : %d", CPU_time_2);
}
OUTPUT:
#include <stdio.h>
#include <time.h>
int main ()
{
time_t seconds;
seconds = time (NULL);
printf ("Number of hours since 1970 Jan 1st " \
"is %ld \n", seconds/3600);
return 0;
}
OUTPUT:
Number of hours since 1970 Jan 1st is 374528
EXAMPLE PROGRAM FOR DIFFTIME() FUNCTION IN C:
This function is used to get the difference between two given times
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#include <time.h>
int main()
{
time_t begin,end;
long i;
begin= time(NULL);
for(i = 0; i < 150000000; i++);
end = time(NULL);
printf("for loop used %f seconds to complete the " \
"execution\n", difftime(end, begin));
return 0;
}
OUTPUT:
for loop used 15.000000 seconds to complete the execution
EXAMPLE PROGRAM FOR STRFTIME(), ASCTIME() AND LOCALTIME() IN C:
localtime() This function shares the tm structure that contains date and time informations.
1 #include <stdio.h>
2 #include <time.h>
3
4 #define LEN 150
5 int main ()
6 {
7
char buf[LEN];
8
time_t curtime;
9
struct tm *loc_time;
10
11 //Getting current time of system
12 curtime = time (NULL);
13
14 // Converting current time to local time
15 loc_time = localtime (&curtime);
16
17 // Displaying date and time in standard format
18 printf("%s", asctime (loc_time));
19
20 strftime (buf, LEN, "Today is %A, %b %d.\n", loc_time);
21 fputs (buf, stdout);
22 strftime (buf, LEN, "Time is %I:%M %p.\n", loc_time);
23 fputs (buf, stdout);
24
25 return 0;
26 }
OUTPUT:
Sat Sep 22 01:15:03 2012
Today is Saturday, Sep 22.
Time is 01:15 AM.
EXAMPLE PROGRAM FOR MKTIME() AND CTIME() FUNCTIONS IN C:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
OUTPUT:
Mon Feb 4 02:30:38 2008
#include <stdio.h>
#include <time.h>
int main()
{
time_t orig_format;
time(&orig_format);
printf ("Universal Time is %s",
asctime(gmtime(&orig_format)));
return 0;
}
OUTPUT:
Universal Time is Sat Sep 22 08:11:40 2012
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.
So, type cast is done before division to retain float value (1.4).
1 #include <stdio.h>
2 int main ()
3 {
4
float x;
5
x = (float) 7/5;
6
printf("%f",x);
7 }
OUTPUT:
1.400000
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.
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.
S.no
Typecast function
Description
atof()
atoi()
atol()
itoa()
ltoa()
C atof() function
atof() function in C language converts string data type to float data type. Syntax for atof() function is given
below.
stdlib.h header file supports all the type casting functions in C language.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[10] = "3.14";
float pi = atof(a);
printf("Value of pi = %f\n", pi);
return 0;
}
OUTPUT:
Value of pi = 3.140000
C atoi() function
atoi() function in C language converts string data type to int data type. Syntax for atoi() function is given
below.
stdlib.h header file supports all the type casting functions in C language.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[10] = "100";
int value = atoi(a);
printf("Value = %d\n", value);
return 0;
}
OUTPUT:
Value = 100
C atol() function
atol() function in C language converts string data type to long data type. Syntax for atol() function is given
below.
stdlib.h header file supports all the type casting functions in C language.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char a[20] = "100000000000";
long value = atol(a);
printf("Value = %ld\n", value);
return 0;
}
OUTPUT:
Value = 100000000000
C itoa() function
itoa() function in C language converts int data type to string data type. Syntax for itoa() function is given
below.
stdlib.h header file supports all the type casting functions in C language. But, it is a non standard function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int a=54325;
char buffer[20];
itoa(a,buffer,2); // here 2 means binary
printf("Binary value = %s\n", buffer);
itoa(a,buffer,10); // here 10 means decimal
printf("Decimal value = %s\n", buffer);
itoa(a,buffer,16); // here 16 means Hexadecimal
printf("Hexadecimal value = %s\n", buffer);
return 0;
}
OUTPUT:
Binary value = 1101010000110101
Decimal value = 54325
Hexadecimal value = D435
C ltoa() function
ltoa() function in C language converts long data type to string data type. Syntax for ltoa() function is given
below.
stdlib.h header file supports all the type casting functions in C language.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
long a=10000000;
char buffer[50];
ltoa(a,buffer,2); // here 2 means binary
printf("Binary value = %s\n", buffer);
ltoa(a,buffer,10); // here 10 means decimal
printf("Decimal value = %s\n", buffer);
ltoa(a,buffer,16); // here 16 means Hexadecimal
printf("Hexadecimal value = %s\n", buffer);
return 0;
}
OUTPUT:
S.no
Function
Description
getenv()
setenv()
putenv()
perror()
Displays most recent error that happened during library function call
rand()
delay()
1
2
3
4
5
6
7
8
OUTPUT:
File = /usr/bin/example.c
EXAMPLE PROGRAM FOR PUTENV() FUNCTION IN C:
1
2
3
4
5
6
7
8
9
10
11
12
13
OUTPUT:
Directory name before modifying = /usr/bin/example/
Directory name after modifying = /usr/home/
EXAMPLE PROGRAM FOR PERROR() FUNCTION IN C:
This function displays most recent error that happened during library function call.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
int main()
{
FILE *fp;
char filename[40] = "test.txt";
/* Let us consider test.txt not available */
fp = f open(filename, "r");
if(fp == NULL)
{
perror("File not found");
printf("errno : %d.\n", errno);
return 1;
}
printf("File is found and opened for reading");
fclose(fp);
return 0;
}
OUTPUT:
errno : 22.
File not found: No such file or
directory
EXAMPLE PROGRAM FOR RAND() FUNCTION IN C:
This function returns the random integer numbers range from 0 upto 32767
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main ()
{
printf ("1st random number : %d\n", rand() % 100);
printf ("2nd random number : %d\n", rand() % 100);
printf ("3rd random number: %d\n", rand());
return 0;
}
OUTPUT:
1st random number : 83
2nd random number : 86
3rd random number: 16816927
EXAMPLE PROGRAM FOR DELAY() FUNCTION IN C:
This function suspends the execution of the program for particular time.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<stdio.h>
#include<stdlib.h>
int main ()
{
printf("Suspends the execution of the program " \
"for particular time");
delay(5000);
return 0;
}
OUTPUT:
Suspends the execution of the program for particular time
C Structure
C Structure is a collection of different data types which are grouped together and each element in a C structure is
called member.
A normal C variable can hold only one data of one data type at a time.
An array can hold group of data of same data type.
A structure can hold group of data of different data types
Data types can be int, char, float, double and long double etc.
Datatype
C VARIABLE
C ARRAY
Syntax
Syntax
Example
Example
C STRUCTURE
int
int a
a = 20
int a[3]
a[0] = 10
a[1] = 20
a[2] = 30
a[3] = \0
char
char b
b=Z
char b[10]
b=Hello
Syntax
Example
struct student
{
int a;
char b[10];
}
a = 10
b = Hello
Type
Syntax
struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
struct tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example
struct student
{
int mark;
char name[10];
float average;
};
struct student
{
int mark;
char name[10];
float average;
};
Declaring
structure variable
Initializing
structure variable
Accessing
structure members
report.mark
report.name
report.average
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
int main()
{
struct student record = {0}; //Initializing to null
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
EXAMPLE PROGRAM ANOTHER WAY OF DECLARING C STRUCTURE:
In this program, structure variable record is declared while declaring structure itself. In above structure
example program, structure variable struct student record is declared inside main function which is after declaring
structure.
1
2
3
4
5
6
7
8
9
10
11
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
} record;
int main()
12 {
13
14
15
16
17
18
19
20
21
22 }
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
return 0;
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
C STRUCTURE DECLARATION IN SEPARATE HEADER FILE:
In above structure programs, C structure is declared in main source file. Instead of declaring C structure in main
source file, we can have this structure declaration in another file called header file and we can include that header file
in main source file as shown below.
HEADER FILE NAME STRUCTURE.H
Before compiling and executing below C program, create a file named structure.h and declare the below structure.
struct student
{
int id;
char name[20];
float percentage;
} record;
MAIN FILE NAME STRUCTURE.C:
In this program, above created header file is included in structure.c source file as #include Structure.h. So,
the structure declared in structure.h file can be used in structure.c source file.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 }
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
USES OF C STRUCTURES:
1.
2.
3.
4.
5.
6.
C Array of Structures
As you know, C Structure is collection of different datatypes ( variables ) which are grouped together. Whereas, array of
structures is nothing but collection of structures. This is also called as structure array in C.
EXAMPLE PROGRAM FOR ARRAY OF STRUCTURES IN C:
This program is used to store and access id, name and percentage for 3 students. Structure array is used in this
program to store and display records for many students. You can store n number of students record by declaring
structure variable as struct student record[n], where n can be 1000 or 5000 etc.
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
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record[2];
// 1st student's record
record[0].id=1;
strcpy(record[0].name, "Raju");
record[0].percentage = 86.5;
// 2nd student's record
record[1].id=2;
strcpy(record[1].name, "Surendren");
record[1].percentage = 90.5;
// 3rd student's record
record[2].id=3;
strcpy(record[2].name, "Thiyagu");
29
30
31
32
33
34
35
36
37
38
39 }
record[2].percentage = 81.5;
for(i=0; i<3; i++)
{
printf(" Records of STUDENT : %d \n", i+1);
printf(" Id is: %d \n", record[i].id);
printf(" Name is: %s \n", record[i].name);
printf(" Percentage is: %f\n\n",record[i].percentage);
}
return 0;
OUTPUT:
Records of STUDENT : 1
Id is: 1
Name is: Raju
Percentage is: 86.500000
Records of STUDENT : 2
Id is: 2
Name is: Surendren
Percentage is: 90.500000
Records of STUDENT : 3
Id is: 3
Name is: Thiyagu
Percentage is: 81.500000
EXAMPLE PROGRAM FOR DECLARING MANY STRUCTURE VARIABLE IN C:
In this program, two structure variables record1 and record2 are declared for same structure and different values are
assigned for both structure variables. Separate memory is allocated for both structure variables to store the data.
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
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student record2 = {2, "Mani", 93.5};
printf("Records of STUDENT1: \n");
printf(" Id is: %d \n", record1.id);
printf(" Name is: %s \n", record1.name);
printf(" Percentage is: %f \n\n", record1.percentage);
printf("Records of STUDENT2: \n");
printf(" Id is: %d \n", record2.id);
printf(" Name is: %s \n", record2.name);
printf(" Percentage is: %f \n\n", record2.percentage);
return 0;
}
OUTPUT:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
Records of STUDENT2:
Id is: 2
Name is: Mani
Percentage is: 93.500000
A structure can be passed to any function from main function or from any sub function.
Structure definition will be available within the function only.
It wont be available to other functions unless it is passed to those functions by value or by address(reference).
Else, we have to declare structure variable as global variable. That means, structure variable should be declared
outside the main function. So, this structure will be visible to all the functions in a C program.
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student record);
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(record);
return 0;
23
24
25
26
27
28
29
30
}
void func(struct student record)
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
EXAMPLE PROGRAM PASSING STRUCTURE TO FUNCTION IN C BY ADDRESS:
In this program, the whole structure is passed to another function by address. It means only the address of the
structure is passed to another function. The whole structure is not passed to another function with all members and their
values. So, this structure can be accessed from called function by its address.
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
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
void func(struct student *record);
int main()
{
struct student record;
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
func(&record);
return 0;
}
void func(struct student *record)
{
printf(" Id is: %d \n", record->id);
printf(" Name is: %s \n", record->name);
printf(" Percentage is: %f \n", record->percentage);
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[20];
float percentage;
};
struct student record; // Global declaration of structure
void structure_demo();
int main()
{
record.id=1;
strcpy(record.name, "Raju");
record.percentage = 86.5;
structure_demo();
return 0;
}
void structure_demo()
{
printf(" Id is: %d \n", record.id);
printf(" Name is: %s \n", record.name);
printf(" Percentage is: %f \n", record.percentage);
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Dot(.) operator is used to access the data using normal structure variable and arrow (->) is used to access the data
using pointer variable. You have learnt how to access structure data using normal variable in C Structure topic. So, we
are showing here how to access structure data using pointer variable in below C program.
EXAMPLE PROGRAM FOR C STRUCTURE USING POINTER:
In this program, record1 is normal structure variable and ptr is pointer structure variable. As you know,
Dot(.) operator is used to access the data using normal structure variable and arrow(->) is used to access data using
pointer variable.
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
#include <stdio.h>
#include <string.h>
struct student
{
int id;
char name[30];
float percentage;
};
int main()
{
int i;
struct student record1 = {1, "Raju", 90.5};
struct student *ptr;
ptr = &record1;
printf("Records of STUDENT1: \n");
printf(" Id is: %d \n", ptr->id);
printf(" Name is: %s \n", ptr->name);
printf(" Percentage is: %f \n\n", ptr->percentage);
return 0;
}
OUTPUT:
Records of STUDENT1:
Id is: 1
Name is: Raju
Percentage is: 90.500000
EXAMPLE PROGRAM TO COPY A STRUCTURE IN C:
There are many methods to copy one structure to another structure in C.
1.
2.
3.
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49 }
OUTPUT:
Records of STUDENT1 record1 structure
Id : 1
Name : Raju
Percentage : 90.500000
Records of STUDENT1 Direct copy from record1
Id : 1
Name : Raju
Percentage : 90.500000
Records of STUDENT1 copied from record1 using memcpy
Id : 1
Name : Raju
Percentage : 90.500000
Records of STUDENT1 Copied individual members from record1
Id : 1
Name : Raju
Percentage : 90.500000
C Nested Structure
Nested structure in C is nothing but structure within structure. One structure can be declared inside other
structure as we declare structure members inside a structure. The structure variables can be a normal structure variable
or a pointer variable to access the data. You can learn below concepts in this section.
1.
2.
#include <stdio.h>
#include <string.h>
struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data;
int main()
{
struct student_detail stu_data = {1, "Raju", 90.5, 71145,
"Anna University"};
printf(" Id is: %d \n", stu_data.id);
printf(" Name is: %s \n", stu_data.name);
printf(" Percentage is: %f \n\n", stu_data.percentage);
printf(" College Id is: %d \n",
stu_data.clg_data.college_id);
printf(" College Name is: %s \n",
stu_data.clg_data.college_name);
return 0;
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 90.500000
College Id is: 71145
College Name is: Anna University
STRUCTURE WITHIN STRUCTURE IN C USING POINTER VARIABLE:
This program explains how to use structure within structure in C using pointer variable. student_college_detail
structure is declared inside student_detail structure in this program. one normal structure variable and one pointer
structure variable is used in this program.
Please note that combination of .(dot) and ->(arrow) operators are used to access the structure member which is
declared inside the structure.
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
34
35
36
#include <stdio.h>
#include <string.h>
struct student_college_detail
{
int college_id;
char college_name[50];
};
struct student_detail
{
int id;
char name[20];
float percentage;
// structure within structure
struct student_college_detail clg_data;
}stu_data, *stu_data_ptr;
int main()
{
struct student_detail stu_data = {1, "Raju", 90.5, 71145,
"Anna University"};
stu_data_ptr = &stu_data;
printf(" Id is: %d \n", stu_data_ptr->id);
printf(" Name is: %s \n", stu_data_ptr->name);
printf(" Percentage is: %f \n\n",
stu_data_ptr->percentage);
printf(" College Id is: %d \n",
stu_data_ptr->clg_data.college_id);
printf(" College Name is: %s \n",
stu_data_ptr->clg_data.college_name);
return 0;
}
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 90.500000
College Id is: 71145
College Name is: Anna University
1.
2.
3.
#include <stdio.h>
#include <string.h>
struct student
{
int id1;
int id2;
char a;
char b;
float percentage;
};
int main()
{
int i;
struct student record1 = {1, 2, 'A', 'B', 90.5};
printf("size of structure in bytes : %d\n",
sizeof(record1));
printf("\nAddress of id1
= %u", &record1.id1 );
printf("\nAddress of id2
= %u", &record1.id2 );
printf("\nAddress of a
= %u", &record1.a );
printf("\nAddress of b
= %u", &record1.b );
printf("\nAddress of percentage = %u",&record1.percentage);
return 0;
}
OUTPUT:
size of structure in bytes : 16
Address of id1 = 675376768
Address of id2 = 675376772
Address of a = 675376776
Address of b = 675376777
Address of percentage = 675376780
There are 5 members declared for structure in above program. In 32 bit compiler, 4 bytes of memory is occupied
by int datatype. 1 byte of memory is occupied by char datatype and 4 bytes of memory is occupied by float datatype.
Please refer below table to know from where to where memory is allocated for each datatype in contiguous (adjacent)
location in memory.
Datatype
From Address
To Address
Total bytes
int id1
675376768
675376771
int id2
675376772
675376775
char a
675376776
char b
675376777
float percentage
675376780
675376783
The pictorial representation of above structure memory allocation is given below. This diagram will help you to
understand the memory allocation concept in C very easily.
C Structure Padding
In order to align the data in memory, one or more empty bytes (addresses) are inserted (or left empty) between
memory addresses which are allocated for other structure members while memory allocation. This concept is
called structure padding.
Architecture of a computer processor is such a way that it can read 1 word (4 byte in 32 bit processor) from
memory at a time.
To make use of this advantage of processor, data are always aligned as 4 bytes package which leads to insert
empty addresses between other members address.
Because of this structure padding concept in C, size of the structure is always not same as what we think.
For example, please consider below structure that has 5 members.
..
struct student
{
int id1;
int id2;
char a;
char b;
float percentage;
};
..
As per C concepts, int and float datatypes occupy 4 bytes each and char datatype occupies 1 byte for 32 bit
processor. So, only 14 bytes (4+4+1+1+4) should be allocated for above structure.
Architecture of a computer processor is such a way that it can read 1 word from memory at a time.
1 word is equal to 4 bytes for 32 bit processor and 8 bytes for 64 bit processor. So, 32 bit processor always
reads 4 bytes at a time and 64 bit processor always reads 8 bytes at a time.
#include <stdio.h>
#include <string.h>
/* Below structure1 and structure2 are same.
They differ only in member's allignment */
struct structure1
{
int id1;
int id2;
char name;
char c;
float percentage;
};
struct structure2
{
int id1;
char name;
int id2;
char c;
float percentage;
};
int main()
{
struct structure1 a;
struct structure2 b;
printf("size of structure1 in bytes : %d\n",
sizeof(a));
printf ( "\n Address of id1
= %u", &a.id1 );
printf ( "\n Address of id2
= %u", &a.id2 );
printf ( "\n Address of name
= %u", &a.name );
printf ( "\n Address of c
= %u", &a.c );
printf ( "\n Address of percentage = %u",
&a.percentage );
printf(" \n\nsize of structure2 in bytes : %d\n",
sizeof(b));
printf ( "\n Address of id1
= %u", &b.id1 );
printf ( "\n Address of name
= %u", &b.name );
printf ( "\n Address of id2
= %u", &b.id2 );
printf ( "\n Address of c
= %u", &b.c );
printf ( "\n Address of percentage = %u",
&b.percentage );
getchar();
return 0;
}
OUTPUT:
In above program, memory for structure1 is allocated sequentially for first 4 members.
Whereas, memory for 5th member percentage is not allocated immediate next to the end of member c.
There are only 2 bytes remaining in the package of 4 bytes after memory allocated to member c.
Range of this 4 byte package is from 1297339864 to 1297339867.
Addresses 1297339864 and 1297339865 are used for members name and c. Addresses 1297339866
and 1297339867 only is available in this package.
But, member percentage is datatype of float and requires 4 bytes. It cant be stored in the same memory
package as it requires 4 bytes. Only 2 bytes are free in that package.
So, next 4 byte of memory package is chosen to store percentage data which is from 1297339868 to
1297339871.
Because of this, memory 1297339866 and 1297339867 are not used by the program and those 2 bytes are left
empty.
So, size of structure1 is 16 bytes which is 2 bytes extra than what we think. Because, 2 bytes are left empty.
Memory for structure2 is also allocated as same as above concept. Please note that structure1 and structure2
are same. But, they differ only in the order of the members declared inside the structure.
4 bytes of memory is allocated for 1st structure member id1 which occupies whole 4 byte of memory
package.
Then, 2nd structure member name occupies only 1 byte of memory in next 4 byte package and remaining 3
bytes are left empty. Because, 3rd structure member id2 of datatype integer requires whole 4 byte of memory in
the package. But, this is not possible as only 3 bytes available in the package.
So, next whole 4 byte package is used for structure member id2.
Again, 4th structure member c occupies only 1 byte of memory in next 4 byte package and remaining 3
bytes are left empty.
Because, 5th structure member percentage of datatype float requires whole 4 byte of memory in the package.
But, this is also not possible as only 3 bytes available in the package. So, next whole 4 byte package is used
for structure member percentage.
So, size of structure2 is 20 bytes which is 6 bytes extra than what we think. Because, 6 bytes are left empty.
#pragma pack ( 1 ) directive can be used for arranging memory for structure members very next to the end of
other structure members.
VC++ supports this feature. But, some compilers such as Turbo C/C++ does not support this feature.
Please check the below program where there will be no addresses (bytes) left empty because of structure
padding.
#include <stdio.h>
#include <string.h>
/* Below structure1 and structure2 are same.
They differ only in member's allignment */
#pragma pack(1)
struct structure1
{
int id1;
int id2;
char name;
char c;
float percentage;
};
struct structure2
{
int id1;
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
char name;
int id2;
char c;
float percentage;
};
int main()
{
struct structure1 a;
struct structure2 b;
printf("size of structure1 in bytes : %d\n",
sizeof(a));
printf ( "\n Address of id1
= %u", &a.id1 );
printf ( "\n Address of id2
= %u", &a.id2 );
printf ( "\n Address of name
= %u", &a.name );
printf ( "\n Address of c
= %u", &a.c );
printf ( "\n Address of percentage = %u",
&a.percentage );
printf(" \n\nsize of structure2 in bytes : %d\n",
sizeof(b));
printf ( "\n Address of id1
= %u", &b.id1 );
printf ( "\n Address of name
= %u", &b.name );
printf ( "\n Address of id2
= %u", &b.id2 );
printf ( "\n Address of c
= %u", &b.c );
printf ( "\n Address of percentage = %u",
&b.percentage );
getchar();
return 0;
}
OUTPUT:
size of structure1 in bytes : 14
Address of id1 = 3438103088
Address of id2 = 3438103092
Address of name = 3438103096
Address of c = 3438103097
Address of percentage = 3438103098
size of structure2 in bytes : 14
Address of id1 = 3438103072
Address of name = 3438103076
Address of id2 = 3438103077
Address of c = 3438103081
Address of percentage = 3438103082
C Typedef
Typedef is a keyword that is used to give a new symbolic name for the existing name in a C program. This is
same like defining alias for the commands.
Consider the below structure.
struct student
{
int mark [2];
char name [10];
float average;
}
1st way :
struct student record;
struct student *record;
2nd way :
typedef struct student status;
When we use typedef keyword before struct <tag_name> like above, after that we can simply use type
definition status in the C program to declare structure variable.
Now, structure variable declaration will be, status record.
This is equal to struct student record. Type definition for struct student is status. i.e. status = struct
student
status record1;
status record2;
22 return 0;
23 }
OUTPUT:
Id is: 1
Name is: Raju
Percentage is: 86.500000
Typedef can be used to simplify the real commands as per our need.
For example, consider below statement.
In above statement, LLI is the type definition for the real C command long long int. We can use type
definition LLI instead of using full command long long int in a C program once it is defined.
#include <stdio.h>
#include <limits.h>
int main()
{
typedef long long int LLI;
printf("Storage size for long long int data " \
"type : %ld \n", sizeof(LLI));
return 0;
}
OUTPUT:
Storage size for long long int data type : 8
C Union
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 cant 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. Where as 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.
Type
Syntax
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
union tag_name
{
data type var_name1;
data type var_name2;
data type var_name3;
};
Example
union student
{
int mark;
char name[10];
float average;
};
union student
{
int mark;
char name[10];
float average;
};
Declaring
union variable
Initializing
union variable
Accessing
union members
report.mark
report.name
report.average
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
};
int main()
{
union student record1;
union student record2;
// assigning values to record1 union variable
strcpy(record1.name, "Raju");
strcpy(record1.subject, "Maths");
record1.percentage = 86.50;
printf("Union record1 values example\n");
printf(" Name
: %s \n", record1.name);
printf(" Subject : %s \n", record1.subject);
printf(" Percentage : %f \n\n", record1.percentage);
// assigning values to record2 union variable
printf("Union record2 values example\n");
strcpy(record2.name, "Mani");
printf(" Name
: %s \n", record2.name);
strcpy(record2.subject, "Physics");
printf(" Subject : %s \n", record2.subject);
34
35
36
37 }
record2.percentage = 99.50;
printf(" Percentage : %f \n", record2.percentage);
return 0;
OUTPUT:
Union record1 values example
Name :
Subject :
Percentage : 86.500000;
Union record2 values example
Name : Mani
Subject : Physics
Percentage : 99.500000
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 cant access other
member values.
So, only record1.percentage value is displayed in output. record1.name and record1.percentage are
empty.
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 dont 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 cant access all members in union at same time but structure can do that.
#include <stdio.h>
#include <string.h>
union student
{
char name[20];
char subject[20];
float percentage;
}record;
10
11 int main()
12 {
13
14
strcpy(record.name, "Raju");
15
strcpy(record.subject, "Maths");
16
record.percentage = 86.50;
17
18
printf(" Name
: %s \n", record.name);
19
printf(" Subject : %s \n", record.subject);
20
printf(" Percentage : %f \n", record.percentage);
21
return 0;
22 }
OUTPUT:
Name :
Subject :
Percentage : 86.500000
NOTE:
We can access only one member of union at a time. We cant 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. Where as Structure allocates storage space for all its members separately.
DIFFERENCE BETWEEN STRUCTURE AND UNION IN C:
S.no
C Structure
C Union
Union allocates one common storage space for all its members.
Union finds that which of its member needs high storage space
over other members and allocates that much space
Structure example:
struct student
{
int mark;
char name[6];
double average;
};
Union example:
union student
{
int mark;
char name[6];
double average;
};
double average 8B
Total memory allocation
= 2+6+8 = 16 Bytes
C Preprocessor directives
C PREPROCESSOR DIRECTIVES:
Before a C program is compiled in a compiler, source code is processed by a program called preprocessor. This
process is called preprocessing.
Commands used in preprocessor are called preprocessor directives and they begin with # symbol.
Below is the list of preprocessor directives that C language offers.
S.n
o
Preprocessor
Syntax
Description
Macro
#define
Header file
inclusion
#include <file_name>
Conditional
compilation
#undef, #pragma
Other directives
A program in C language involves into different processes. Below diagram will help you to understand all the
processes that a C program comes across.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#define This macro defines constant value and can be any of the basic data types.
#include <file_name> The source code of the file file_name is included in the main C program where
#include <file_name> is mentioned.
#include <stdio.h>
#define height 100
#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '\?'
void main()
{
printf("value of height : %d \n", height );
printf("value of number : %f \n", number );
printf("value of letter : %c \n", letter );
printf("value of letter_sequence : %s \n", letter_sequence);
printf("value of backslash_char : %c \n", backslash_char);
}
OUTPUT:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
#ifdef directive checks whether particular macro is defined or not. If it is defined, If clause statements are
included in source file.
Otherwise, else clause statements are included in source file for compilation and execution.
1 #include <stdio.h>
2 #define RAJU 100
3
4 int main()
5 {
6
#ifdef RAJU
7
printf("RAJU is defined. So, this line will be added in " \
8
"this C file\n");
9
#else
10 printf("RAJU is not defined\n");
11 #endif
12 return 0;
13 }
OUTPUT:
RAJU is defined. So, this line will be added in this C file
B) EXAMPLE PROGRAM FOR #IFNDEF AND #ENDIF IN C:
#ifndef exactly acts as reverse as #ifdef directive. If particular macro is not defined, If clause statements are
included in source file.
Otherwise, else clause statements are included in source file for compilation and execution.
#include <stdio.h>
#define RAJU 100
int main()
{
#ifndef SELVA
{
printf("SELVA is not defined. So, now we are going to " \
"define here\n");
#define SELVA 300
}
#else
printf("SELVA is already defined in the program);
1
2
3
4
5
6
7
8
9
10
11
12
13
14 #endif
15 return 0;
16
17 }
OUTPUT:
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#define a 100
int main()
{
#if (a==100)
printf("This line will be added in this C file since " \
"a \= 100\n");
#else
printf("This line will be added in this C file since " \
"a is not equal to 100\n");
#endif
return 0;
}
OUTPUT:
This line will be added in this C file since a = 100
EXAMPLE PROGRAM FOR UNDEF IN C:
This directive undefines existing macro in the program.
1
2
3
4
5
6
7
8
9
10
#include <stdio.h>
#define height 100
void main()
{
printf("First defined value for height : %d\n",height);
#undef height
// undefining variable
#define height 600 // redefining the same for new value
printf("value of height after undef \& redefine:%d",height);
}
OUTPUT:
First defined value for height : 100
value of height after undef & redefine : 600
EXAMPLE PROGRAM FOR PRAGMA IN C:
Pragma is used to call a function before and after main function in a C program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>
void function1( );
void function2( );
#pragma startup function1
#pragma exit function2
int main( )
{
printf ( "\n Now we are in main function" ) ;
return 0;
}
void function1( )
16
17
18
19
20
21
22
23
24
{
printf("\nFunction1 is called before main function call");
}
void function2( )
{
printf ( "\nFunction2 is called just before end of " \
"main function" ) ;"
}
OUTPUT:
Function1 is called before main function call
Now we are in main function
Function2 is called just before end of main function
MORE ON PRAGMA DIRECTIVE IN C:
S.n
o
Pragma command
description
#Pragma startup
<function_name_1>
#Pragma exit
<function_name_2>
Addition
Subtraction
Multiplication
Division
Modulus
Power
Factorial
In the below c code example, the user is prompted to choose the operations( i.e addition, subtraction etc) to be
performed and then prompted to key in the values which are used to perform the operations. Then, the result will be
shown as output to the user.
C CODE FOR CALCULATOR APPLICATION:
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
case 'H':
case 'h': calculator_operations();
break;
case 'Q':
case 'q': exit(0);
break;
case 'c':
case 'C': system("cls");
calculator_operations();
break;
default : system("cls");
printf("\n**********You have entered unavailable option");
printf("***********\n");
printf("\n*****Please Enter any one of below available ");
printf("options****\n");
calculator_operations();
}
}
}
//Function Definitions
void calculator_operations()
{
//system("cls"); use system function to clear
//screen instead of clrscr();
printf("\n
Welcome to C calculator \n\n");
printf("******* Press 'Q' or 'q' to quit ");
printf("the program ********\n");
printf("***** Press 'H' or 'h' to display ");
printf("below options *****\n\n");
printf("Enter 'C' or 'c' to clear the screen and");
printf(" display available option \n\n");
printf("Enter + symbol for Addition \n");
printf("Enter - symbol for Subtraction \n");
printf("Enter * symbol for Multiplication \n");
printf("Enter / symbol for Division \n");
printf("Enter ? symbol for Modulus\n");
printf("Enter ^ symbol for Power \n");
printf("Enter ! symbol for Factorial \n\n");
}
void addition()
{
int n, total=0, k=0, number;
printf("\nEnter the number of elements you want to add:");
scanf("%d",&n);
printf("Please enter %d numbers one by one: \n",n);
while(k<n)
{
scanf("%d",&number);
total=total+number;
k=k+1;
}
printf("Sum of %d numbers = %d \n",n,total);
}
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
void subtraction()
{
int a, b, c = 0;
printf("\nPlease enter first number : ");
scanf("%d", &a);
printf("Please enter second number : ");
scanf("%d", &b);
c = a - b;
printf("\n%d - %d = %d\n", a, b, c);
}
void multiplication()
{
int a, b, mul=0;
printf("\nPlease enter first numb : ");
scanf("%d", &a);
printf("Please enter second number: ");
scanf("%d", &b);
mul=a*b;
printf("\nMultiplication of entered numbers = %d\n",mul);
}
void division()
{
int a, b, d=0;
printf("\nPlease enter first number : ");
scanf("%d", &a);
printf("Please enter second number : ");
scanf("%d", &b);
d=a/b;
printf("\nDivision of entered numbers=%d\n",d);
}
void modulus()
{
int a, b, d=0;
printf("\nPlease enter first number : ");
scanf("%d", &a);
printf("Please enter second number : ");
scanf("%d", &b);
d=a%b;
printf("\nModulus of entered numbers = %d\n",d);
}
void power()
{
double a,num, p;
printf("\nEnter two numbers to find the power \n");
printf("number: ");
scanf("%lf",&a);
printf("power : ");
scanf("%lf",&num);
p=pow(a,num);
printf("\n%lf to the power %lf = %lf \n",a,num,p);
}
int factorial()
{
int i,fact=1,num;
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200 }
C programming tutorial
C Programming is an ANSI/ISO standard and powerful programming language for developing real time applications. C
programming language was invented by Dennis Ritchie at the Bell Laboratories in 1972. It was invented for
implementing UNIX operating system. C is most widely used programming language even today. All other
programming languages were derived directly or indirectly from C programming concepts. This tutorial explains all
basic concepts in C like history of C language, data types, keywords, constants, variables, operators, expressions,
control statements, array, pointer, string, library functions, structures and unions etc.
This C tutorial is designed for the new learners, students and also for the corporate level developers who want to learn
and refresh their C programming skills.
START C PROGRAMMING TUTORIAL
C PROGRAMMING HISTORY:
The C language is a structure oriented programming language, was developed at Bell Laboratories in 1972 by Dennis
Ritchie. C language features were derived from an earlier language called B (Basic Combined Programming
Language BCPL). C language was invented for implementing UNIX operating system.more
C PROGRAMMING BASICS:
Steps to be followed for any C program to create and get the output are explained . This is common to all C programs
and there is no exception, whether its a very small C program or very large program. Structure of a C program is
defined by a set of rules called protocol, to be followed by programmer while writing a C programmore
C PRINTF AND SCANF:
printf() and scanf() functions are inbuilt library functions in C which are available in the 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.more
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 using in a program. Size of variable, const and array are determined by data
types. There are four data types in the C language. They are.more
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 are the basic building blocks in C language which are constructed together to write
a C program. Each program element in a C program is given a name called identifiers.more
C CONSTANTS:
C Constants are also like normal variables. But, the only difference is, their values cant 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.more
C VARIABLES:
C 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 changed in the program. The C variable might be belonging
to any of the data types like int, float, char etc.more
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.more
C DECISION CONTROL STATEMENTS:
In decision control statements (C if else and nested if), group of statement is executed when the condition is true. If
the condition is false, then, else part statements are executed. In C programming, there are 3 types of decision making
control statements in C language. They are.more
C LOOP CONTROL STATEMENTS:
Loop control statements in C programming are used to perform looping operations until the given condition is true.
Control comes out of the loop statements once the condition becomes false. There are 3 types of loop control statements
in C language. They are.more
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 programming. They are 1) switch 2) break 3) continue 4)
goto.more
C TYPE QUALIFIERS:
The keywords which are used to modify the properties of a variable are called type qualifiers. There are two types of
qualifiers available in C programming. They are 1) const 2) volatile. Constants are also like normal variables.more
C STORAGE CLASS SPECIFIERS:
Storage class specifiers in C programming tell the compiler where to store a variable, how to store the variable, what is
the initial value of the variable and the lifetime of the variable. There are 4 storage class specifiers available in C
language. They are.more
C ARRAY:
C Array is a collection of variables belongings to the same data type. You can store group of data of the same data type
in an array. There are 2 types of arrays in C programming. They are 1) One dimensional array 2) Multidimensional
array.more
C STRING:
C Strings are nothing but array of characters ended with null character (\0). This null character indicates the end of the
string. In C programming, strings are always enclosed by double quotes. Whereas, character is enclosed by single
quotes in Cmore
C POINTER:
C Pointer is a variable that stores/points the address of the other variable. C Pointer is used to allocate memory
dynamically, i.e. at run time. The variable might be any of the data types such as int, float, char, double, short etc.
Normal variable stores the value, whereas pointer variable stores the address of the variable.more
C FUNCTIONS:
Functions in C programming are basic building blocks in a program. All C programs are written using functions to
improve re-usability, understandability and to keep track of them. A large C program is divided into basic building
blocks called C function. C function contains set of instructions enclosed by { } which performs specific.more
C LIBRARY FUNCTIONS:
Library functions in C language are inbuilt functions which are grouped together and placed in a common place called a
library. Each library function in C programming language performs a 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.more
C COMMAND LINE ARGUMENTS:
main() function of a C program accepts arguments from command line or from other shell scripts by following
commands. They are 1. argc 2. argv[]. 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.more
C VARIABLE LENGTH ARGUMENT:
Variable length arguments in C programming are an advanced concept offered by C99 standard. In C89 standard, fixed
arguments only can be passed to the functions. When a function gets the number of arguments that changes at run time,
we can go for a variable length arguments. It is denoted as (3 dots).more
C TUTORIAL WITH EXAMPLE PROGRAMS:
C for, while and do while Example Programs
C switch, break, continue and goto Example Programs
C auto, static, extern and register Example Programs
C array Example Programs
C string Example Programs
C pointer Example Programs
C function Example Programs
C structure Example Programs
C typedef Example Programs
C union Example Programs
C typecast Example Programs
C undef and #define Example Programs
When you complete this c programming tutorial, you can able to write real time C programs by your own. We
are walking you through all topics in this c programming tutorial which are explained clearly even for very
beginners for C programming.
We have given few real time application programs with output in this C tutorial.
ANSI 89 American National Standards Institute, American National Standard for Information Systems
Programming Language C, 1989.
Kernighan 78 B. W. Kernighan and D. M. Ritchie, The C Programming Language, Prentice-Hall: Englewood
Cliffs, NJ, 1978. Second edition, 1988.
Thinking 90 C* Programming Guide, Thinking Machines Corp. Cambridge Mass., 1990.