Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 77

DAVINCI [C PROGRAMMING]

Contents
C – Language History.............................................................................................................................3
Features of C language:.....................................................................................................................3
Uses of C language:...........................................................................................................................3
Which level the C language is belonging to?..............................................................................3
C language is a structured language...........................................................................................4
1. C Basic Program:...........................................................................................................................4
Hello World!.........................................................................................................................................4
Explanation for above C basic Program:.........................................................................................4
2. Steps to write C programs and get the output:...........................................................................5
3. Basic structure of C program:.......................................................................................................5
Example C program to compare all the sections:...........................................................................6
Description for each section of a C program:..................................................................................7
C – printf and scanf................................................................................................................................7
1. C printf() function:.......................................................................................................................8
Example program for C printf() function:..................................................................................8
2. C scanf() function:..........................................................................................................................9
Example program for printf() and scanf() functions in C:.......................................................9
C – Data Types.....................................................................................................................................10
C – Data types:..............................................................................................................................10
1. Basic data types in C:..............................................................................................................10
1.1. Integer data type:..............................................................................................................10
1.2. Character data type:.........................................................................................................11
1.3. Floating point data type:...................................................................................................11
1.3.1. sizeof() function in C:.........................................................................................................11
1.3.2. Modifiers in C:.................................................................................................................12
2. Enumeration data type in C:....................................................................................................13
C – enum example program:...................................................................................................14
3. Derived data type in C:............................................................................................................14
4. Void data type in C:..................................................................................................................14
C – Tokens and keywords....................................................................................................................14
1. C tokens:......................................................................................................................................14
C tokens example program:........................................................................................................15

1
DAVINCI [C PROGRAMMING]

2. Identifiers in C language:.........................................................................................................15
Rules for constructing identifier name in C:...............................................................................15
3. Keywords in C language:.........................................................................................................15
C – Constant........................................................................................................................................16
Types of C constant:.....................................................................................................................16
Rules for constructing C constant:..........................................................................................17
C – Variable..........................................................................................................................................19
Rules for naming C variable:.......................................................................................................20
Declaring & initializing C variable:..............................................................................................20
There are three types of variables in C program They are,....................................................20
1. Example program for local variable in C:..............................................................................20
2. Example program for global variable in C:............................................................................21
3. Environment variables in C:....................................................................................................22
Difference between variable declaration & definition in C:......................................................24
C – Operators and Expressions............................................................................................................24
C – Decision Control statement......................................................................................................38
C – Loop control statements...........................................................................................................40
C – Case control statements...........................................................................................................43
C – Array............................................................................................................................................47
C – String...........................................................................................................................................50
C – strcat() function.........................................................................................................................52
C – strcpy() function........................................................................................................................53
C – strlen() function.........................................................................................................................53
C – strcmp() function.......................................................................................................................54
C – strlwr() function.........................................................................................................................55
C – strupr() function........................................................................................................................55
C – strrev() function.........................................................................................................................56
C – Pointer.........................................................................................................................................57
C – Function......................................................................................................................................58
C – Argument & return value...........................................................................................................62
C – Structure.....................................................................................................................................67
C – Typedef.......................................................................................................................................71
C – Union...........................................................................................................................................74

2
DAVINCI [C PROGRAMMING]

C – Language History
 C language is a structure oriented programming language, was developed at Bell Laboratories in 1972 by
Dennis Ritchie
 C language features were derived from earlier language called “B” (Basic Combined Programming Language
– BCPL)
 C language was invented for implementing UNIX operating system
 In 1978, Dennis Ritchie and Brian Kernighan published the first edition  “The C Programming Language”
and commonly known as K&R C
 In 1983, the American National Standards Institute (ANSI) established a committee to provide a modern,
comprehensive definition of C. The resulting definition, the ANSI standard, or “ANSI C”, was completed late 1988.

Features of C language:
Reliability
Portability
Flexibility
Interactivity
Modularity
Efficiency and Effectiveness

Uses of C language:
C language is used for developing system applications that forms major portion of operating
systems such as Windows, UNIX and Linux. Below are some examples of C being used.

Database systems
Graphics packages
Word processors
Spread sheets
Operating system development
Compilers and Assemblers
Network drivers
Interpreters

Which level the C language is belonging to?


S.no High Level Middle Level Low Level

Middle level languages don’t


High level languages Low level languages
provide all the built-in functions
provides almost everything provides nothing other
found in high level languages, but
1 that the programmer might than access to the
provides all building blocks that
need to do as already built machines basic
we need to produce the result we
into the language instruction set
want

Examples:
2 C, C++ Assembler
Java, Python

3
DAVINCI [C PROGRAMMING]

C language is a structured language


S.no Structure oriented Object oriented Non structure

In this type of language, large There is no specific


In this type of language,
programs are divided into structure for
1 programs are divided into
small programs called programming this
objects
functions language

Prime focus is on the data


Prime focus is on functions
that is being operated and not
2 and procedures that operate N/A
on the functions or
on data
procedures

Data moves freely around the Data is hidden and cannot be


3 systems from one function to accessed by external N/A
another functions

Program structure follows Program structure follows


4 N/A
“Top Down Approach” “Bottom UP Approach”

Examples:
 BASIC, COBOL,
5 C++, JAVA and C# (C sharp)
C, Pascal, ALGOL and FORTRAN
Modula-2

1. C Basic Program:
#include <stdio.h>
 
int main()
{
     /* Our first simple C basic program */
     printf("Hello World! ");
     getch();
     return 0;
}
Output:

Hello World!

Explanation for above C basic Program:

Let’s see all the sections of the above simple C program line by line.

S.no Command Explanation

4
DAVINCI [C PROGRAMMING]

This is a preprocessor command that includes standard input


1 #include <stdio.h> output header file(stdio.h) from the C library before compiling a
C program

This is the main function from where execution of any C


2 int main()
program begins.

3 { This indicates the beginning of the main function.

whatever is given inside the command “/*   */” in any C


4 /*_some_comments_*/
program, won’t be considered for compilation and execution.

printf(“Hello_World!
5 printf command prints the output onto the screen.
“);

6 getch(); This command waits for any character input from keyboard.

This command terminates C program (main function) and


7 return 0;
returns 0.

8 } This indicates the end of the main function.

2. Steps to write C programs and get the output:

      Below are the steps to be followed for any C program to create and get the output. This is common to all C
program and there is no exception whether its a very small C program or very large C program.

3. 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

5
DAVINCI [C PROGRAMMING]

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:

This is a C basic program


Sum of two numbers : 2

Description for each section of a C program:

 Let us see about each section of a C basic program in detail below.

6
DAVINCI [C PROGRAMMING]

 Please note that a C program mayn’t have all below mentioned sections except main function
and link sections.
 Also, a C program structure mayn’t be in below mentioned order.

S.No Sections Description

We can give comments about the program, creation or modified


date, author name etc in this section. The characters or words or
Documentation anything which are given between “/*” and “*/”, won’t be
1
section considered by C compiler for compilation process.These will be
ignored by C compiler during compilation.
Example : /* comment line1 comment line2 comment 3 */

Header files that are required to execute a C program are included


2 Link Section
in this section

In this section, variables are defined and values are set to these
3 Definition Section
variables.

Global declaration Global variables are defined in this section. When a variable is to
4
section be used throughout the program, can be defined in this section.

Function prototype Function prototype gives many information about a function like
5
declaration section return type, parameter names used inside the function.

Every C program is started from main function and this function


6 Main function contains two major sections called declaration section and
executable section.

User defined User can define their own functions in this section which perform
7
function section particular task as per the user requirement.

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.

7
DAVINCI [C PROGRAMMING]

 To generate a newline,we use “\n” in C printf() statement.


Note:

 C language is case sensitive. For example, printf() and scanf() are different from Printf() and
Scanf(). All characters in printf() and scanf() functions must be in lower case.

Example program for C printf() function:

#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

8
DAVINCI [C PROGRAMMING]

 %d got replaced by value of an integer variable  (no),


 %c got replaced by value of a character variable  (ch),
 %f got replaced by value of a float variable  (flt),
 %lf got replaced by value of a double variable  (dbl),
 %s got replaced by value of a string variable  (str),
 %o got replaced by a octal value corresponding to integer variable  (no),
 %x got replaced by a hexadecimal value corresponding to integer variable
 \n got replaced by a newline.

2. C scanf() function:

 scanf() function is used to read character, string, numeric data from keyboard
 Consider below example program where user enters a character. This value is assigned to the
variable “ch” and then displayed.
 Then, user enters a string and this value is assigned to the variable ”str” and then displayed.

Example program for printf() and scanf() functions in C:


#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:

Enter any character


a
Entered character is a
Enter any string ( upto 100 character )
hai
Entered string is hai

 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

9
DAVINCI [C PROGRAMMING]

C – Data Types
 C data types are defined as the data storage format that a variable can store a data to perform a specific
operation.
 Data types are used to define a variable before to use in a program.
 Size of variable, constant and array are determined by data types.

C – Data types:
There are four data types in C language. They are,

S.no Types Data Types

1 Basic data types int, char, float, double

2 Enumeration data type enum

3 Derived data type pointer, array, structure, union

4 Void data type void

1. Basic data types in C:

1.1. Integer data type:


 Integer data type allows a variable to store numeric values.
 “int” keyword is used to refer integer data type.
 The storage size of int data type is 2 or 4 or 8 byte.
 It varies depend upon the processor in the CPU that we use.  If we are using 16 bit processor, 2 byte  (16 bit)
of memory will be allocated for int data type.
 Like wise, 4 byte (32 bit) of memory for 32 bit processor and 8 byte (64 bit) of memory for 64 bit processor is
allocated for int datatype.
 int (2 byte) can store values from -32,768 to +32,767
 int (4 byte) can store values from -2,147,483,648 to +2,147,483,647.
 If you want to use the integer value that crosses the above limit, you can go for “long int” and “long long int”
for which the limits are very high.
Note:

 We can’t store decimal values using int data type.


 If we use int data type to store decimal values, decimal values will be truncated and we will get only whole
number.
 In this case, float data type can be used to store decimal values in a variable.

1.2. Character data type:


 Character data type allows a variable to store only one character.
 Storage size of character data type is 1. We can store only one character using character data type.
 “char” keyword is used to refer character data type.

10
DAVINCI [C PROGRAMMING]

 For example, ‘A’ can be stored using char datatype. You can’t 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:
 Float data type allows a variable to store decimal values.
 Storage size of float data type is 4. This also varies depend upon the processor in the CPU as “int” data type.
 We can use up-to 6 digits after decimal using float data type.
 For example, 10.456789 can be stored in a variable using float data type.
2. double:

 Double data type is also same as float data type which allows up-to 10 digits after decimal.
 The range for double datatype is from 1E–37 to 1E+37
.

1.3.1. sizeof() function in C:


sizeof() function is used to find the memory space allocated for each C data types.

#include <stdio.h>

#include <limits.h>

 int main()

   int a;

   char b;

   float c;

   double d;

   printf("Storage size for int data type:%d \n",sizeof(a));

   printf("Storage size for char data type:%d \n",sizeof(b));

   printf("Storage size for float data type:%d \n",sizeof(c));

   printf("Storage size for double data type:%d\n",sizeof(d));

   return 0;

11
DAVINCI [C PROGRAMMING]

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.3.2. Modifiers in C:
 The amount of memory space to be allocated for a variable is derived by modifiers.
 Modifiers are prefixed with basic data types to modify (either increase or decrease) the amount of storage
space allocated to a variable.
 For example, storage space for int data type is 4 byte for 32 bit processor.  We can increase the range by using
long int which is 8 byte. We can decrease the range by using short int which is 2 byte.
 There are 5 modifiers available in C language. They are,
1. short
2. long
3. signed
4. unsigned
5. long long
 Below table gives the detail about the storage size of each C basic data type in 16 bit processor.
Please keep in mind that storage size and range for int and float datatype will vary depend on the CPU processor (8,16,
32 and 64 bit)

storage
S.No C Data types Range
Size

1 Char 1 –127 to 127

2 Int 2 –32,767 to 32,767

3 Float 4 1E–37 to 1E+37 with six digits of precision

4 double 8 1E–37 to 1E+37 with ten digits of precision

5 long double 10 1E–37 to 1E+37 with ten digits of precision

6 long int 4 –2,147,483,647 to 2,147,483,647

7 short int 2 –32,767 to 32,767

8 unsigned short int 2 0 to 65,535

9 signed short int 2 –32,767 to 32,767

12
DAVINCI [C PROGRAMMING]

10 long long int 8 –(2power(63) –1) to 2(power)63 –1

11 signed long int 4 –2,147,483,647 to 2,147,483,647

12 unsigned long int 4 0 to 4,294,967,295

13 unsigned long long int 8 2(power)64 –1

2. Enumeration data type in C:


 Enumeration data type consists of named integer constants as a list.
 It start with 0 (zero) by default and value is incremented by 1 for the sequential identifiers in the list.
 Enum syntax in C:
enum identifier [optional{ enumerator-list }];
 Enum example in C: 
enum month { Jan, Feb, Mar }; or
/* Jan, Feb and Mar variables will be assigned to 0, 1 and 2 respectively by default */
enum month { Jan = 1, Feb, Mar };
/* Feb and Mar variables will be assigned to 2 and 3 respectively by default */
enum month { Jan = 20, Feb, Mar };
/* Jan is assigned to 20. Feb and Mar variables will be assigned to 21 and 22 respectively by default */

 The above enum functionality can also be implemented by “#define” preprocessor directive as given below.
Above enum example is same as given below.
#define Jan 20;
#define Feb 21;
#define Mar 22;

C – enum example program:


#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");

13
DAVINCI [C PROGRAMMING]

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:


 Void is an empty data type that has no value.
 This can be used in functions and pointers.
 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 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.

1. C tokens:
 C tokens are the basic buildings blocks in C language which are constructed together to write a
C program.
 Each and every smallest individual units in a C program are known as C tokens.
 C tokens are of six types. They are,
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);

14
DAVINCI [C PROGRAMMING]

where,

 main – identifier
 {,}, (,) – delimiter
 int – keyword
 x, y, total – identifier
 main, {, }, (, ), int, x, y, total – tokens
    Do you know how to use C token in real time application programs? We have given simple real time
application programs where C token is used. You can refer the below C programs to know how to use C token in
real time program.

2. Identifiers in C language:
 Each program elements in a C program are given a name called identifiers.
 Names given to identify Variables, functions and arrays are examples for identifiers. eg. x is a
name given to integer variable in above program.

Rules for constructing identifier name in C:


1. First character should be an alphabet or underscore.
2. Succeeding characters might be digits or letter.
3. Punctuation and special characters aren’t allowed except underscore.
4. Identifiers should not be keywords.

3. Keywords in C language:
 Keywords are pre-defined words in a C compiler.
 Each keyword is meant to perform a specific function in a C program.
 Since keywords are referred names for compiler, they can’t be used as variable name.
C language supports 32 keywords which are given below. Click on each keywords below for detail description and
example programs.

auto double int struct

break else long switch

case enum register typedef

char extern return union

const float short unsigned

continue for signed void

default goto sizeof volatile

do if static while

15
DAVINCI [C PROGRAMMING]

C – Constant
 C Constants are also like normal variables. But, only difference is, their values can not be modified by the
program once they are defined.
 Constants refer to fixed values. They are also called as literals
 Constants may be belonging to any of the data type.
 Syntax:
const data_type variable_name; (or) const data_type *variable_name;

Types of C constant:
1. Integer constants
2. Real or Floating point constants
3. Octal & Hexadecimal constants
4. Character constants
5. String constants
6. Backslash character constants

S.no Constant type data type Example

int 53, 762, -478 etc 


unsigned int 5000u, 1000U etc
1 Integer constants
long int 483,647
long long int 2,147,483,680

float 10.456789
2 Real or Floating point constants
doule 600.123456789

3 Octal constant int 013          /* starts with 0  */

4 Hexadecimal constant int 0×90        /* starts with 0x */

5 character constants  char ‘A’   ,   ‘B’,     ‘C’

6 string constants char “ABCD”   ,   “Hai”

Rules for constructing C constant:


1. Integer Constants in C:
 An integer constant must have at least one digit.
 It must not have a decimal point.
 It can either be positive or negative.
 No commas or blanks are allowed within an integer constant.
 If no sign precedes an integer constant, it is assumed to be positive.
 The allowable range for integer constants is -32768 to 32767.

16
DAVINCI [C PROGRAMMING]

2. Real constants in C:
 A real constant must have at least one digit
 It must have a decimal point
 It could be either positive or negative
 If no sign precedes an integer constant, it is assumed to be positive.
 No commas or blanks are allowed within a real constant.

3. Character and string constants in C:


 A character constant is a single alphabet, a single digit or a single special symbol enclosed
within single quotes.
 The maximum length of a character constant is 1 character.
 String constants are  enclosed within double quotes.

4. Backslash Character Constants in C:


 There are some characters which have special meaning in C language.
 They should be preceded by backslash symbol to make use of special function of them.
 Given below is the list of special characters and their purpose.
Backslash_character 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 Octal constant (N is an octal constant)

\XN Hexadecimal constant (N – hex.dcml cnst)

How to use constants in a C program?

 We can define constants in a C program in the following ways.


1. By “const” keyword

17
DAVINCI [C PROGRAMMING]

2. By “#define” preprocessor directive


 Please note that when you try to change constant values after defining in C program, it will
through error.
1. Example program using const keyword in C:

#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);

   printf("value of backslash_char  : %c \n", backslash_char);

Output:

value of height : 100 2.


value of number : 3.140000 Example
value of letter : A
program
value of letter_sequence : ABC
value of backslash_char : ? 
using
#define

preprocessor directive in C:

#include <stdio.h>

#define height 100

#define number 3.14

#define letter 'A'

#define letter_sequence "ABC"

18
DAVINCI [C PROGRAMMING]

#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 : ? C–
Variable
 C v a r i a b l e i s a n a m e
the variable.
 The value of the C variable may get change in the program.
 C variable might be belonging to any of the data type like int, float, char etc.

Rules for naming C variable:


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:


 Variables should be declared in the C program before to use.
 Memory space is not allocated for a variable while declaration. It happens only on variable
definition.
 Variable initialization means assigning a value to the variable.

S.No  Type  Syntax Example

1 Variable declaration data_type variable_name; int x, y, z; char flat, ch;

2 Variable data_type variable_name = int x = 50, y = 30; char flag = ‘x’,

19
DAVINCI [C PROGRAMMING]

initialization value; ch=’l’;

There are three types of variables in C program They are,


1. Local variable
2. Global variable
3. Environment variable

1. Example program for local variable in C:


 The scope of local variables will be within the function only.
 These variables are declared within the function and can’t be accessed outside the function.
 In the below example, m and n variables are having scope within the main function only. These are not visible
to test function.
 Like wise, a and b variables are having scope within the test function only. These are not visible to main
function.
#include<stdio.h>

void test();          

int main()

       int m = 22, n = 44;  

       // m, n are local variables of main function

       /*m and n variables are having scope

              within this main function only.

              These are not visible to test funtion.*/

       /* If you try to access a and b in this function,

          you will get 'a' undeclared and 'b' undeclared

          error */

       printf("\nvalues : m = %d and n = %d", m, n);

       test();                        

void test()  

       int a = 50, b = 80;  

       // a, b are local variables of test function

       /*a and b variables are having scope

              within this test function only.

20
DAVINCI [C PROGRAMMING]

              These are not visible to main function.*/

       /* If you try to access m and n in this function,

          you will get 'm' undeclared and 'n' undeclared

          error */

       printf("\nvalues : a = %d and b = %d", a, b);

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.
#include<stdio.h>

void test();  

int m = 22, n = 44;

int a = 50, b = 80;

int main()

  printf("All variables are accessed from main function");

  printf("\nvalues : m= %d : n= %d : a= %d : b= %d",m,n,a,b);

  test();                        

void test()  

  printf("\n\nAll variables are accessed from" \

         " test function");

  printf("\nvalues : m= %d : n= %d : a= %d : b= %d",m,n,a,b);

21
DAVINCI [C PROGRAMMING]

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/”.

#include <stdio.h>

#include <stdlib.h>

int main()

   printf("Directory = %s\n", getenv("DIR"));

   return 0;

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”

#include <stdio.h>

22
DAVINCI [C PROGRAMMING]

#include <stdlib.h>

int main()

   setenv("FILE","/usr/bin/example.c",50);

   printf("File = %s\n", getenv("FILE"));

   return 0;

Output:

Example
File = /usr/bin/example.c
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.

#include <stdio.h>

#include <stdlib.h>

int main()

   setenv("DIR","/usr/bin/example/",50);

   printf("Directory name before modifying = " \

          "%s\n", getenv("DIR"));

   putenv("DIR=/usr/home/");

   printf("Directory name after modifying = " \

             "%s\n", getenv("DIR"));

   return 0;

Output:

Directory name before modifying = /usr/bin/example/ Difference


Directory name after modifying = /usr/home/ between
variable

declaration & definition in C:


 S.no   Variable declaration Variable definition

23
DAVINCI [C PROGRAMMING]

Declaration tells the compiler about data type Definition allocates memory for the
1
and size of the variable. variable.

Variable can be declared many times in a It can happen only one time for a
2
program. variable in a program.

The assignment of properties and identification Assignments of storage space to a


3
to a variable. variable.

C – Operators and Expressions


 The symbols which are used to perform logical and mathematical operations in a C program are called C
operators.
 These C operators join individual constants and variables to form expressions.
 Operators, functions, constants and variables are combined together to form expressions.
 Consider the expression A + B * 5. where, +, * are operators, A, B  are variables, 5 is constant and A + B * 5
is an expression.
Types of C operators:

S.no Types of Operators              Description              

These are used to perform mathematical calculations like


1 Arithmetic_operators addition, subtraction, multiplication, division and
modulus

These are used to assign the values for the variables in C


2 Assignment_operators
programs.

These operators are used to compare the value of two


3 Relational operators
variables.

These operators are used to perform logical operations on


4 Logical operators
the given two variables.

These operators are used to perform bit operations on


5 Bit wise operators
given two variables.

Conditional (ternary) Conditional operators return one value if condition is true


6
operators and returns another value is condition is false.

7 Increment/decrement These operators are used to either increase or decrease the

24
DAVINCI [C PROGRAMMING]

operators value of the variable by one.

8 Special operators &, *, sizeof( ) and ternary 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

1 + Addition A+B

2 - Subtraction A-B

3 * multiplication A*B

4 / Division A/B

5 % Modulus A%B

Example program for C arithmetic operators:

 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.
#include <stdio.h>

int main()

    int a=40,b=20, add,sub,mul,div,mod;

    add = a+b;

    sub = a-b;

    mul = a*b;

    div = a/b;

    mod = a%b;                                          

    printf("Addition of a, b is   : %d\n", add);

    printf("Subtraction of a, b is   : %d\n", sub);

    printf("Multiplication of a, b is   : %d\n", mul);

    printf("Division of a, b is   : %d\n", div);

25
DAVINCI [C PROGRAMMING]

    printf("Modulus of a, b is   : %d\n", mod);

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

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;”
 Other assignment operators in C language are given below.

Operators Example  Explanation 

Simple assignment operator = sum=10 10 is assigned to variable sum

+= sum+=10 This_is_same_as_sum=sum+10…………

-= sum-=10 This is same as sum = sum-10

*= sum*=10 This is same as sum = sum*10

Compound assignment operators /+ sum/=10 This is same as sum = sum/10

%= sum%=10 This is same as sum = sum%10

&= sum&=10 This is same as sum = sum&10

^= sum^=10 This is same as sum = sum^10

Example program for C assignment operators:

 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.
# include <stdio.h>

int main()

26
DAVINCI [C PROGRAMMING]

    int Total=0,i;

    for(i=0;i<10;i++)

    {

        Total+=i; // This is same as Total = Toatal+i

    }

    printf("Total = %d", Total);

Output:

Total = 45

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

1 > x>y x is greater than y

2 < x<y x is less than y

3 >= x >= y x is greater than or equal to y

4 <= x <= y x is less than or equal to y

5 == x == y x is equal to y

6 != x != y x is not equal to y

Example program for relational operators in C:

 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 (=).
#include <stdio.h>

int main()

    int m=40,n=20;

27
DAVINCI [C PROGRAMMING]

    if (m == n)

    {

       printf("m and n are equal");

    }

    else

    {

       printf("m and n are not equal");

    }

Output:

m and n are not equal

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 It returns true when both conditions are


1 && (x>5)&&(y<5)
AND true

logical It returns true when at-least one of the


2 || (x>=10)||(y>=10)
OR condition is true

It reverses the state of the operand “((x>5)


&& (y<5))”
logical
3 ! !((x>5)&&(y<5))
NOT
If “((x>5) && (y<5))” is true, logical NOT
operator makes it false

 Example program for logical operators in C:

#include <stdio.h>

int main()

     int m=40,n=20;

     int o=20,p=30;

28
DAVINCI [C PROGRAMMING]

     if (m>n && m !=0)

     {

          printf("&& Operator : Both conditions are true\n");

     }

   else  if (o>p || p!=20)

     {

          printf("|| Operator : Only one condition is true\n");

     }

   else  if (!(m>n && m !=0))

     {  

         printf("! Operator  : Both conditions are true\n");  

     }

     else

     {  

         printf("! Operator  : Both conditions are true. " \

                "But, status is inverted as   false\n");  

getch();

     }

Output:

&& Operator : Both conditions are true


|| Operator : Only one condition is true
! Operator : Both conditions are true. But, status is inverted as false

 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).

29
DAVINCI [C PROGRAMMING]

Bit wise operators in C:
 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 y  x|y x&y x^y Operator_symbol Operator_name

0 0 0 0 0 & Bitwise_AND

0 1 1 0 1 | Bitwise OR

1 0 1 0 1 ~ Bitwise_NOT

1 1 1 1 0 ^ XOR

<< Left Shift

>> Right Shift

 Consider x=40 and y=80. Binary form of these values are given below.
x = 00101000
y=  01010000

 All bit wise operations for x and y are given below.


x&y = 00000000 (binary) = 0 (decimal)
x|y = 01111000 (binary) = 120 (decimal)
~x =1111111111111111111111111111111111111111111111111111111111010111
.. ..= -41 (decimal)
x^y = 01111000 (binary) = 120 (decimal)
x << 1 = 01010000 (binary) = 80 (decimal)
x >> 1 = 00010100 (binary) = 20 (decimal)
Note:

 Bit wise NOT : Value of 40 in binary is


0000000000000000000000000000000000000000000000000000000000101000. So, all 0′s are converted into 1′s in bit
wise NOT operation.
 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.

30
DAVINCI [C PROGRAMMING]

#include <stdio.h>

int main()

    int m=40,n=80,AND_opr,OR_opr,XOR_opr,NOT_opr ; 

    AND_opr = (m&n);

    OR_opr = (m|n);

    NOT_opr = (~m);

    XOR_opr = (m^n);

    printf("AND_opr value = %d\n",AND_opr );

    printf("OR_opr value = %d\n",OR_opr );

    printf("NOT_opr value = %d\n",NOT_opr );

    printf("XOR_opr value = %d\n",XOR_opr );

    printf("left_shift value = %d\n", m << 1);

    printf("right_shift value = %d\n", m >> 1);

Output:

AND_opr value = 0
OR_opr value = 120
NOT_opr value = -41
XOR_opr value = 120
left_shift value = 80
right_shift value = 20

Conditional or ternary operators in C:

 Conditional operators return one value if condition is true and returns another value is
condition is false.
 This operator is also called as ternary operator.
Syntax     :        (Condition? true_value: false_value);

Example :        (A > 100  ?  0  :  1);

 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:

#include <stdio.h>

31
DAVINCI [C PROGRAMMING]

int main()

        int x=1, y ;

        y = ( x ==1 ? 2 : 0 ) ;

        printf("x value is %d\n", x);

        printf("y value is %d", y);

Output:

x value is 1
y value is 2

 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 – - ;

Example program for increment operators in C:

 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”.
//Example for increment operators

#include <stdio.h>

int main()

     int i=1;

     while(i<10)

     {

         printf("%d ",i);

32
DAVINCI [C PROGRAMMING]

         i++;

     }    

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

#include <stdio.h>

int main()

 int i=20;

    while(i>10)

    {

         printf("%d ",i);

         i--;

    }    

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.no Operator type Operator Description

++i
1 Pre increment Value of i is incremented before assigning it to variable i.

i++
2 Post-increment Value of i is incremented after assigning it to variable i.

33
DAVINCI [C PROGRAMMING]

– –i
3 Pre decrement Value of i is decremented before assigning it to variable i.

i– –
4 Post_decrement Value of i is decremented after assigning it to variable i.

 Example program for pre – increment operators in C:

//Example for increment operators

#include <stdio.h>

int main()

           int i=0;

           while(++i < 5 )

           {

                printf("%d ",i);

           }

           return 0;

Output:

1234

 Step 1 : In above program, value of “i” is incremented from 0 to 1 using pre-increment


operator.
 Step 2 : This incremented value “1″ is compared with 5 in while expression.
 Step 3 : Then, this incremented value “1″ is assigned to the variable “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:

#include <stdio.h>

int main()

           int i=0;

           while(i++ < 5 )

           {

34
DAVINCI [C PROGRAMMING]

                printf("%d ",i);

           }

           return 0;

Output:

12345

 Step 1 : In this program, value of  i ”0″ is compared with 5 in while expression.


 Step 2 : Then, value of “i” is incremented from 0 to 1 using post-increment operator.
 Step 3 : Then, this incremented value “1″ is assigned to the variable “i”.
 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:

#include <stdio.h>

int main()

           int i=10;

           while(--i > 5 )

           {

                printf("%d ",i);

           }

           return 0;

Output:

9876

 Step 1 : In above program, value of “i” is decremented from 10 to 9 using pre-decrement


operator.
 Step 2 : This decremented value “9″ is compared with 5 in while expression.
 Step 3 : Then, this decremented value “9″ is assigned to the variable “i”.
 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:

#include <stdio.h>

35
DAVINCI [C PROGRAMMING]

int main()

           int i=10;

           while(i-- > 5 )

           {

                printf("%d ",i);

           }

           return 0;

 Output:

98765

 Step 1 : In this program, value of  i ”10″ is compared with 5 in while expression.


 Step 2 : Then, value of “i” is decremented from 10 to 9 using post-decrement operator.
 Step 3 : Then, this decremented value “9″ is assigned to the variable “i”.
 Above 3 steps are continued until while expression becomes false and output is displayed as “9
8 7 6 5″. 
Special Operators in C:

 Below are some of special operators that C language offers.

 S.no Operators Description

This is used to get the address of the variable.


1 &
Example : &a will give address of a.

This is used as pointer to a variable.


2 *
Example : * a  where, * is pointer to the variable a.

This gives the size of the variable.


3 Sizeof ()
Example : size of (char) will give us 1.

Example program for & and * operators in C:

 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.
#include <stdio.h>

36
DAVINCI [C PROGRAMMING]

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

Example program for sizeof() operator in C:

 sizeof() operator is used to find the memory space allocated for each C data types.
#include <stdio.h>

#include <limits.h>

int main()

   int a;

   char b;

   float c;

   double d;

   printf("Storage size for int data type:%d \n",sizeof(a));

   printf("Storage size for char data type:%d \n",sizeof(b));

   printf("Storage size for float data type:%d \n",sizeof(c));

   printf("Storage size for double data type:%d\n",sizeof(d));

   return 0;

37
DAVINCI [C PROGRAMMING]

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

C – Decision Control statement


 In decision control statements (C if else and nested if), group of statements are executed when condition is
true.  If condition is false, then else part statements are executed.
 There are 3 types of decision making control statements in C language. They are,
1.   if statements
2.   if else statements
3.   nested if statements
“If”, “else” and “nested if” decision control statements in C:

 Syntax for each C decision control statements are given in below table with description.

Decision
control Syntax Description
statements

if (condition)  In these type of statements, if condition is true,


if
{ Statements; } then respective block of code is executed.

if (condition)  In these type of statements, group of statements


{ Statement1; Statement2;} are executed when condition is true.  If
if…else
else  condition is false, then else part statements are
{ Statement3; Statement4; } executed.

if (condition1)
If condition 1 is false, then condition 2 is
{ Statement1; }
checked and statements are executed if it is
nested if else_if (condition2) 
true. If condition 2 also gets failure, then else
{ Statement2; }
part is executed.
else Statement 3;

Example program for if statement in C:

      In “if” control statement, respective block of code is executed when condition is true.


int main()

  int m=40,n=40;

38
DAVINCI [C PROGRAMMING]

  if (m == n)

  {

      printf("m and n are equal");

  }

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.
#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()

39
DAVINCI [C PROGRAMMING]

  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");

  }

 Output:

m is greater than n

C – Loop control statements


Loop control statements in C are used to perform looping operations until the given condition is true. Control
comes out of the loop statements once condition becomes false.

Types of loop control statements in C:

There are 3 types of loop control statements in C language. They are,

1. for
2. while
3. do-while
 Syntax for each C loop control statements are given in below table with description.

S.no Loop Name Syntax Description

Where,
exp1 – variable initialization
( Example: i=0, j=2, k=3 )
for (exp1; exp2; expr3)
1 for exp2 – condition checking
{ statements; }
( Example: i>5, j<3, k=3 )
exp3 – increment/decrement
( Example: ++i, j–, ++k )

while (condition) where, 


2 while
{ statements; } condition might be a>5, i<10

40
DAVINCI [C PROGRAMMING]

do { statements; } where,
3 do while
while (condition); condition might be a>5, i<10

Example program (for loop) in C:

      In for loop control statement, loop is executed until condition becomes false.
#include <stdio.h>

int main()

  int i;

  for(i=0;i<10;i++)

  {

      printf("%d ",i);

  }    

Output:

0 1 2 3 4 5 6 7 8 9

Example program (while loop) in C:

      In while loop control statement, loop is executed until condition becomes false.
#include <stdio.h>

int main()

  int i=3;

  while(i<10)

  {

      printf("%d\n",i);

      i++;

  }    

Output:

3 4 5 6 7 8 9

41
DAVINCI [C PROGRAMMING]

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.

#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.no while do while

Loop is executed for first time irrespective of the condition.


Loop is executed only
1 After executing while loop for first time, then condition is
when condition is true.
checked.

C – Case control statements


 The statements which are used to execute only specific block of statements in a series of blocks are called case
control statements.

There are 4 types of case control statements in C language. They are,

1. switch
2. break
3. continue
4. goto

42
DAVINCI [C PROGRAMMING]

1. switch case statement in C:

 Switch case statements are used to execute only specific case statements based on the switch
expression.
 Below is the syntax for switch case statement.
switch (expression)
{
         case label1:   statements;
                                break;
         case label2:   statements;
                                break;
         default:          statements;
                                break;
}
Example program for switch..case statement in C:

#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" );

43
DAVINCI [C PROGRAMMING]

   }

   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;
Example program for break statement in C:

#include <stdio.h>

int main()

  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:

0 1 2 3 4
Coming out of for loop when i = 5

44
DAVINCI [C PROGRAMMING]

3. Continue statement in C:

 Continue statement is used to continue the next iteration of for loop, while loop and do-while
loops.  So, the remaining statements are skipped within the loop for that particular iteration.
 Syntax : continue;
Example program for continue statement in C:

#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:

0 1 2 3 4

Skipping 5 from display using continue statement


Skipping 6 from display using continue statement
7 8 9

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.
{
         …….

45
DAVINCI [C PROGRAMMING]

         go to label;
         …….
         …….
         LABEL:
         statements;
}
Example program for goto statement in C:

#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:

0 1 2 3 4
We are using goto statement when i = 5
Now, we are inside label name “hai”

C – Array
 C Array is a collection of variables belongings to the same data type. You can store group of data of same data
type in an array.

 Array might be belonging to any of the data types


 Array size must be a constant value.

46
DAVINCI [C PROGRAMMING]

 Always, Contiguous (adjacent) memory locations are used to store array elements in memory.
 It is a best practice to initialize an array to zero or null while declaring, if we don’t assign any
values to array.
Example for C Arrays:

 int a[10];       // integer array


 char b[10];   // character array   i.e. string
Types of C arrays:

There are 2 types of C arrays. They are,

1. One dimensional array


2. Multi dimensional array
 Two dimensional array
 Three dimensional array, four dimensional array etc…
1. One dimensional array in C:

 Syntax : data-type arr_name[array_size];

Array declaration Array initialization Accessing array

Syntax:  data_type arr_name [arr_size]=


arr_name[index];
data_type arr_name [arr_size]; (value1, value2, value3,….);

age[0];_/*0_is_accessed*/
int age [5]; int age[5]={0, 1, 2, 3, 4, 5}; age[1];_/*1_is_accessed*/
age[2];_/*2_is_accessed*/

char str[10]={‘H’,‘a’,‘i’}; (or)
str[0];_/*H is accessed*/
char str[0] = ‘H’;
char str[10]; str[1];  /*a is accessed*/
char str[1] = ‘a’;
str[2];  /* i is accessed*/
char str[2] = ‘i;

Example program for one dimensional array in C:

#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};

47
DAVINCI [C PROGRAMMING]

    /* Above array can be initialized as below also

       arr[0] = 10;

       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]);

    }

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:

 Two dimensional array is nothing but array of array.


 syntax : data_type array_name[num_of_rows][num_of_column]

S.no Array declaration Array initialization Accessing array

Syntax: 
data_type arr_name[2][2] =
1 data_type arr_name [num_of_rows] arr_name[index];
{{0,0},{0,1},{1,0},{1,1}};
[num_of_column];

arr [0] [0] = 1; 


Example: arr [0] ]1] = 2;
2 int arr[2][2] = {1,2, 3, 4};
int arr[2][2]; arr [1][0]  = 3;
arr [1] [1] = 4;

48
DAVINCI [C PROGRAMMING]

Example program for two dimensional array in C:

#include<stdio.h>

int main()

    int i,j;

    // declaring and Initializing array

    int arr[2][2] = {10,20,30,40};

    /* Above array can be initialized as below also

       arr[0][0] = 10;   // Initializing array

       arr[0][1] = 20;

       arr[1][0] = 30;

       arr[1][1] = 40;

    */

    for (i=0;i<2;i++)

    {

       for (j=0;j<2;j++)

       {

          // Accessing variables

          printf("value of arr[%d] [%d] : %d\n",i,j,arr[i][j]);

       }

    }

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.

49
DAVINCI [C PROGRAMMING]

Example for C string:

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

#include <stdio.h> 

int main ()

   char string[20] = "fresh2refresh.com";

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

   return 0;

Output:

The string is : fresh2refresh.com

C String functions:

 String.h header file supports all the string functions in C language. All the string functions are
given below.

String
S.no Description
functions

1 strcat ( )  Concatenates str2 at the end of str1.

2 strncat ( )  appends a portion of string to another

3 strcpy ( )  Copies str2 into str1

4 strncpy ( )  copies given number of characters of one string to another

50
DAVINCI [C PROGRAMMING]

5 strlen ( )  gives the length of str1.

 Returns 0 if str1 is same as str2. Returns <0 if strl < str2. Returns >0 if


6 strcmp ( )
str1 > str2.

 Same as strcmp() function. But, this function negotiates case.  “A” and
7 strcmpi_(.)
“a” are treated as same.

8 strchr ( )  Returns pointer to first occurrence of char in str1.

9 strrchr ( )  last occurrence of given character in a string is found

10 strstr ( )  Returns pointer to first occurrence of str2 in str1.

11 strrstr ( )  Returns pointer to last occurrence of str2 in str1.

12 strdup ( )  duplicates the string

13 strlwr ( )  converts string to lowercase

14 strupr ( )  converts string to uppercase

15 strrev ( )  reverses the given string

16 strset ( )  sets all character in a string to given character

17 strnset ( )  It sets the portion of characters in a string to given character

18 strtok ( )  tokenizing given string using delimiter

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.
char * strcat ( char * destination, const char * source );

 Example :
strcat ( str2, str1 ); - str1 is concatenated at the end of str2.
strcat ( str1, str2 ); - str2 is concatenated at the end of str1.

 As you know, each string in C is ended up with null character (‘\0′).


 In strcat( ) operation, null character of destination string is overwritten by source string’s first character and
null character is added at the end of new destination string which is created after strcat( ) operation.

51
DAVINCI [C PROGRAMMING]

Example program for strcat( ) function in C:

 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>

int main( )

   char source[ ] = " fresh2refresh" ;

   char target[ ]= " C tutorial" ;

   printf ( "\nSource string = %s", source ) ;

   printf ( "\nTarget string = %s", target ) ;

   strcat ( target, source ) ;

   printf ( "\nTarget string after strcat( ) = %s", target ) ;

Output:

Source string                       = fresh2refresh


Target string                        = C tutorial
Target string after strcat( ) = C tutorial fresh2refresh

C – strcpy() function
 strcpy( ) function copies contents of one string into another string. Syntax for strcpy function is given below.
char * strcpy ( char * destination, const char * source );

 Example:
strcpy ( str1, str2) – It copies contents of str2 into str1.
strcpy ( str2, str1) – It copies contents of str1 into str2.

 If destination string length is less than source string, entire source string value won’t 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 won’t be copied and will be
truncated.
Example program for strcpy( ) function in C:

 In this program, source string “fresh2refresh” is copied into target string using strcpy( )
function.

52
DAVINCI [C PROGRAMMING]

#include <stdio.h>

#include <string.h>

int main( )

   char source[ ] = "fresh2refresh" ;

   char target[20]= "" ;

   printf ( "\nsource string = %s", source ) ;

   printf ( "\ntarget string = %s", target ) ;

   strcpy ( target, source ) ;

   printf ( "\ntarget string after strcpy( ) = %s", target ) ;

   return 0;

Output:

source string = fresh2refresh


target string =
target string after strcpy( ) = fresh2refresh

C – strlen() function
 strlen( ) function in C gives the length of the given string. Syntax for strlen( ) function is given below.
size_t strlen ( const char * str );
 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.
Example program for strlen() function 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>

int main( )

    int len;

    char array[20]="fresh2refresh.com" ;

    len = strlen(array) ;

53
DAVINCI [C PROGRAMMING]

    printf ( "\string length  = %d \n" , len ) ;

    return 0;

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.
int strcmp ( const char * str1, const char * str2 );

 strcmp( ) function is case sensitive. i.e, “A” and “a” are treated as different characters.
Example program for strcmp( ) function in C:

 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 = strcmp ( str1, "fresh" ) ;

   j = strcmp ( str1, str2 ) ;

   k = strcmp ( str1, "f" ) ;

   printf ( "\n%d %d %d", i, j, k ) ;

   return 0;

Output:

0 -1 1

54
DAVINCI [C PROGRAMMING]

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.

Example program for strlwr() function 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”.
#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.
Example program for strupr() function in C:

 In this program, string ”Modify This String To Upper” is converted into uppercase using
strupr( ) function and result is displayed as “MODIFY THIS STRING TO UPPER”.
#include<stdio.h>

#include<string.h>

int main()

    char str[ ] = "Modify This String To Upper"; 

    printf("%s\n",strupr(str));

    return  0;

55
DAVINCI [C PROGRAMMING]

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.
Example program for strrev() function in C:

 In below program, string “Hello” is reversed using strrev( ) function and output is displayed as “olleH”.
#include<stdio.h>

#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 – Pointer
 C Pointer is a variable that stores/points the address of the another variable.
 C Pointer is used to allocate memory dynamically i.e. at run time.
 The variable might be any of the data type such as int, float, char, double, short etc.
Syntax data_type *var_name;
Example : int *p;  char *p;

 Where, * is used to denote that “p” is pointer variable and not a normal variable.
Key points to remember about pointers in C:

 Normal variable stores the value whereas pointer variable stores the address of the variable.
 The content of the C pointer always be a whole number i.e. address.
 Always C pointer is initialized to null, i.e. int *p = null.

56
DAVINCI [C PROGRAMMING]

 The value of null pointer is 0.


 & symbol is used to get the address of the variable.
 * symbol is used to get the value of the variable that the pointer is pointing to.
 If pointer is assigned to NULL, it means it is pointing to nothing.
 Two pointers can be subtracted to know how many elements are available between these two pointers.
 But, Pointer addition, multiplication, division are not allowed.
 The size of any pointer is 2 byte (for 16 bit compiler).
Example program for pointer in C:

#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

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. What is C function?
2. Uses of C functions
3. C function declaration, function call and definition with example program
4. How to call C functions in a program?
 Call by value
 Call by reference
5. C function arguments and return values
 C function with arguments and with return value
 C function with arguments and without return value
 C function without arguments and without return value
 C function without arguments and with return value
6. Types of C functions

57
DAVINCI [C PROGRAMMING]

 Library functions in C
 User defined functions in C
 Creating/Adding user defined function in C library
7. Command line arguments in C
8. Variable length arguments in C
1. What is C function?

     A large C program is divided into basic building blocks called C function. C function contains set of instructions enclosed
by “{  }” which performs specific operation in a C program. Actually, Collection of these functions creates a C program.

2. Uses of C functions:

 C functions are used to avoid rewriting same logic/code again and again in a program.
 There is no limit in calling C functions to make use of same functionality wherever required.
 We can call functions any number of times in a program and from any place in a program.
 A large C program can easily be tracked when it is divided into functions.
 The core concept of C functions are, re-usability, dividing a big task into small pieces to
achieve the functionality and to improve understandability of very large C programs.
3. C function declaration, function call and function definition:

There are 3 aspects in each C function. They are,

 Function declaration or prototype  - This informs compiler about the function name, function
parameters and  return value’s data type.
 Function call – This calls the actual function
 Function definition – This contains all the statements to be executed.
S.no C function aspects syntax

return_type function_name ( arguments list )


1 function definition
{ Body of function; }

2 function call function_name ( arguments list );

3 function declaration return_type function_name ( argument list );

Simple example program for C function:

 As you know, functions should be declared and defined before calling in a C program.
 In the below program, function “square” is called from main function.
 The value of “m” is passed as argument to the function “square”. This value is multiplied by
itself in this function and multiplied value “p” is returned to main function from function “square”.
#include<stdio.h>

// function prototype, also called function declaration

float square ( float x );                              

// main function, program starts from here

58
DAVINCI [C PROGRAMMING]

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

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. Call by value
2. Call by reference
1. Call by value:

 In call by value method, the value of the variable is passed to the function as parameter.
 The value of the actual parameter can not be modified by formal parameter.
 Different Memory is allocated for both actual and formal parameters. Because, value of actual
parameter is copied to formal parameter.
Note:

 Actual parameter – This is the argument which is used in function call.

59
DAVINCI [C PROGRAMMING]

 Formal parameter – This is the argument which is used in function definition


Example program for C function (using call by value):

 In this program, the values of the variables “m” and “n” are passed to the function “swap”.
 These values are copied to formal parameters “a” and “b” in swap function and used.
#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.

60
DAVINCI [C PROGRAMMING]

 Same memory is used for both actual and formal parameters since only address is used by both
parameters.
Example program for C function (using call by reference):

 In this program, the address of the variables “m” and “n” are passed to the function “swap”.
 These values are not copied to formal parameters “a” and “b” in swap function.
 Because, they are just holding the address of those variables.
 This address is used to access and change the values of the variables.
#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;

    *a = *b;

    *b = tmp;

    printf("\n values after swap a = %d \nand b = %d", *a, *b);

Output:

values before swap m = 22 

and n = 44
values after swap a = 44
and b = 22

61
DAVINCI [C PROGRAMMING]

C – Argument & return value


All C functions can be called either with arguments or without arguments in a C program. These functions may or
may not return values to the calling function. Now, we will see simple example C programs for each one of the
below.

1. C function with arguments (parameters) and with return value


2. C function with arguments (parameters) and without return value
3. C function without arguments (parameters) and without return value
4. C function without arguments (parameters) and with return value

S.no C function syntax

int function ( int );         // function declaration


with arguments and with function ( a );                // function call
1
return values int function( int a )       // function definition
{statements;  return a;}

void function ( int );     // function declaration


with arguments and without function( a );                // function call
2
return values void function( int a )   // function definition
{statements;}

void function();             // function declaration


without arguments and without function();                     // function call
3
return values void function()              // function definition
{statements;}

int function ( );             // function declaration


without arguments and with function ( );                  // function call
4
return values int function( )               // function definition
{statements;  return a;}

Note:

 If the return data type of a function is “void”, then, it can’t return any values to the calling
function.
 If the return data type of the function is other than void such as “int, float, double etc”, then, it
can return values to the calling function.
1. Example program for with arguments & with return value:

      In this program, integer, array and string are passed as arguments to the function. The return type of this
function is “int” and value of the variable “a” is returned from the function. The values for array and string are
modified inside the function itself.

#include<stdio.h>

#include<string.h>

int function(int, int[], char[]);

62
DAVINCI [C PROGRAMMING]

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++)

      {

         // Accessing each variable

         printf("value of arr[%d] is %d\n",i,arr[i]);  

      }

      printf("value of str is %s\n",str);

      return 0;

int function(int a, int *arr, char *str)

    int i;

    a = a+20;

    arr[0] = arr[0]+50;

63
DAVINCI [C PROGRAMMING]

    arr[1] = arr[1]+50;

    arr[2] = arr[2]+50;

    arr[3] = arr[3]+50;

    arr[4] = arr[4]+50;

    strcpy(str,"\"modified string\"");

    return a;

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”

2. Example program for with arguments & without return value:

      In this program, integer, array and string are passed as arguments to the function. The return type of this
function is “void” and no values can be returned from the function. All the values of integer, array and string are
manipulated and displayed inside the function itself.

#include<stdio.h>

void function(int, int[], char[]);

int main()

      int a = 20;

      int arr[5] = {10,20,30,40,50};  

64
DAVINCI [C PROGRAMMING]

      char str[30] = "\"fresh2refresh\"";

      function(a, &arr[0], &str[0]);

      return 0;

void function(int a, int *arr, char *str)

    int i;

    printf("value of a is %d\n\n",a);  

      for (i=0;i<5;i++)

      {

         // Accessing each variable

         printf("value of arr[%d] is %d\n",i,arr[i]);  

      }

    printf("\nvalue of str is %s\n",str);  

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.

#include<stdio.h>

void test();          

int main()

65
DAVINCI [C PROGRAMMING]

    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.

#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;      

66
DAVINCI [C PROGRAMMING]

Output:

Sum of two given values = 130

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.

 If you want to access structure members in C, structure variable should be declared.


 Many structure variables can be declared for same structure and memory will be allocated for each separately.
 It is a best practice to initialize a structure to null while declaring, if we don’t assign any values to structure
members.
Difference between C variable, C array and C structure:

 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.
C variable C array C structure
Datatype
Syntax Example Syntax Example Syntax Example

a[0] = 10
a[1] = 20 struct student
int int a a = 20 int a[3] {
a[2] = 30 a = 10
a[3] = ‘\0′ int a;
b = “Hello”
char b[10];
}
char char b b=’Z’ char b[10] b=”Hello”

Below table explains following concepts in C structure.

1. How to declare a C structure?


2. How to initialize a C structure?
3. How to access the members of a C structure?
Type Using normal variable Using pointer variabe

struct tag_name struct tag_name


{ {
data type var_name1; data type var_name1;
Syntax
data type var_name2; data type var_name2;
data type var_name3; data type var_name3;
}; };

Example struct student struct student


{ {
int  mark; int  mark;
char name[10]; char name[10];

67
DAVINCI [C PROGRAMMING]

float average; float average;


}; };

Declaring
struct student report; struct student *report, rep;
structure variable

struct student rep = {100,


Initializing struct student report = {100, “Mani”, 99.5}; 
structure variable “Mani”, 99.5};
report = &rep;

report.mark report  -> mark


Accessing
report.name report -> name
structure members
report.average report -> average

 Example program for C structure:

           This program is used to store and access “id, name and percentage” for one student. We can also store
and access these data for many students using array of structures. You can check “C – Array of Structures“ to
know how to store and access these data for many students.
#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;

68
DAVINCI [C PROGRAMMING]

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.

#include <stdio.h>

#include <string.h>

struct student

            int id;

            char name[20];

            float percentage;

} record;

int main()

            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

69
DAVINCI [C PROGRAMMING]

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.

// File name - structure.c

#include <stdio.h>

#include <string.h>

#include "structure.h"   /* header file where C structure is

                            declared */

int main()

   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;

70
DAVINCI [C PROGRAMMING]

Output:

Id is: 1
Name is: Raju
Percentage is: 86.500000

Uses of C structures:

1. C Structures can be used to store huge data. Structures act as a database.


2. C Structures can be used to send data to the printer.
3. C Structures can interact with keyboard and mouse to store the data.
4. C Structures can be used in drawing and floppy formatting.
5. C Structures can be used to clear output screen contents.
6. C Structures can be used to check computer’s memory size etc.
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;
}
 Variable for the above structure can be declared in two ways.
1st way  :

struct student record;       /* for normal variable */


struct student *record;     /* for pointer variable */

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”
An alternative way for structure declaration using typedef in C:

typedef struct student


{
         int mark [2];

71
DAVINCI [C PROGRAMMING]

         char name [10];


         float average;
} status;
 To declare structure variable, we can use the below statements.
status record1;                 /* record 1 is structure variable */
status record2;                 /* record 2 is structure variable */

Example program for C typedef:

// Structure using typedef:

#include <stdio.h>

#include <string.h>

typedef struct student

  int id;

  char name[20];

  float percentage;

} status;

int main()

  status record;

  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

 Typedef can be used to simplify the real commands as per our need.

72
DAVINCI [C PROGRAMMING]

 For example, consider below statement.


typedef long long int LLI;

 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.
Another example program for C typedef:

#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 can’t access all member values at the same time in
union. But, structure can access all member values at the same time. This is because,  Union allocates one common
storage space for all its members. 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 Using normal variable Using pointer variable

Syntax union tag_name union tag_name


{ {
data type var_name1; data type var_name1;
data type var_name2; data type var_name2;

73
DAVINCI [C PROGRAMMING]

data type var_name3; data type var_name3;


}; };

union student union student
{ {
int  mark; int  mark;
Example
char name[10]; char name[10];
float average; float average;
}; };

Declaring
union student report; union student *report, rep;
union variable

Initializing union student report = {100, union student rep = {100, “Mani”,


union variable “Mani”, 99.5}; 99.5};report = &rep;

report.mark report  -> mark


Accessing
report.name report -> name
union members
report.average report -> average

Example program for C union:

#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);

74
DAVINCI [C PROGRAMMING]

       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);

       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 can’t access other
member values.

75
DAVINCI [C PROGRAMMING]

 So, only “record1.percentage” value is displayed in output. “record1.name” and “record1.percentage” are
empty.
Record2 union variable:

 If we want to access all member values using union, we have to access the member before assigning values to
other members as shown in record2 union variable in this program.
 Each union members are accessed in record2 example immediately after assigning values to them.
 If we don’t access them before assigning values to other member, member name and value will be over
written by other member as all members are using same memory.
 We can’t access all members in union at same time but structure can do that.
Example program – Another way of declaring C union:

    In this program, union variable “record” is declared while declaring union itself as shown in the below program.

#include <stdio.h>

#include <string.h> 

union student

            char name[20];

            char subject[20];

            float percentage;

}record;

int main()

            strcpy(record.name, "Raju");

            strcpy(record.subject, "Maths");

            record.percentage = 86.50;

            printf(" Name       : %s \n", record.name);

            printf(" Subject    : %s \n", record.subject);

            printf(" Percentage : %f \n", record.percentage);

            return 0;

Output:

Name :
Subject :

76
DAVINCI [C PROGRAMMING]

Percentage : 86.500000

Note:

      We can access only one member of union at a time. We can’t access all member values at the same time in union. But,
structure can access all member values at the same time. This is because, Union allocates one common storage space for all
its members. 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


Structure allocates storage
members.
1 space for all its members
separately. Union finds that which of its member needs high storage
space over other members and allocates that much space

Structure occupies higher


2 Union occupies lower memory space over structure.
memory space.

We can access all members


3 We can access only one member of union at a time.
of structure at a time.

Structure example: Union example:


struct student union student
{ {
4 int mark; int mark;
char name[6]; char name[6];
double average; double average;
}; };

For above structure, memory


allocation will be like below.
For above union, only 8 bytes of memory will be allocated
int mark – 2B
since double data type will occupy maximum space of
 5 char name[6] – 6B
memory over other data types. 
double average – 8B 
Total memory allocation = 8 Bytes
Total memory allocation =
2+6+8 = 16 Bytes

77

You might also like