Ravi Tutorials Provide Project Training

C Prog.



C programming is an ANSI/ISO standard and powerful programming language for developing real time applications. C programming language was invented by Dennis Ritchie at the Bell Laboratories in 1972. It was invented for implementing UNIX operating system. C programming is most widely used programming language even today. All other programming languages were derived directly or indirectly from C programming concepts. C programming is the basis for all programming languages. This C programming tutorial explains all basic concepts in C like history of C language, data types, keywords, constants, variables, operators, expressions, control statements, array, pointer, string, library functions, structures and unions etc.
This C programming tutorial is designed for the new learners, students and also for the corporate level developers who want to learn and refresh their C programming skills.

C – Language History





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

C programming language standards:

  • C89/C90 standard – First standardized specification for C language was developed by the American National Standards Institute in 1989. C89 and C90 standards refer to the same programming language.
  • C99 standard – Next revision was published in 1999 that introduced new features like advanced data types and other changes.

C11 and Embedded C language:

  • C11 standard adds new features to C programming language and library like type generic macros, anonymous structures, improved Unicode support, atomic operations, multi-threading and bounds-checked functions. It also makes some portions of the existing C99 library optional and improves compatibility with C++.
  • Embedded C includes features not available in C like fixed-point arithmetic, named address spaces, and basic I/O hardware addressing.
  • Operating systems, C compiler and all UNIX application programs are written in C language
  • It is also called as procedure oriented programming language. The C language is reliable, simple and easy to use. C has been coded in assembly language.

Features of C programming language:

  • Reliability
  • Portability
  • Flexibility
  • Interactivity
  • Modularity
  • Efficiency and Effectiveness

Uses of C programming language:

The C programming language is used for developing system applications that forms a major portion of operating systems such as Windows, UNIX and Linux. Below are some examples of C being used.
  • Database systems
  • Graphics packages
  • Word processors
  • Spreadsheets
  • Operating system development
  • Compilers and Assemblers
  • Network drivers
  • Interpreters




Which level is C language belonging to?

S.no
High Level
Middle Level
Low Level
1 High level languages provide almost everything that the programmer might need to do as already built into the language Middle level languages don’t provide all the built-in functions found in high level languages, but provides all building blocks that we need to produce the result we want Low level languages provides nothing other than access to the machines basic instruction set
2 Examples:
Java, Python
C, C++ Assembler

The C language is a structured language

S.no
Structure oriented
Object oriented
Non structure
1 In this type of language, large programs are divided into small programs called functions In this type of language, programs are divided into objects There is no specific structure for programming this language
2 Prime focus is on functions and procedures that operate on the data Prime focus is in the data that is being operated and not on the functions or procedures N/A
3 Data moves freely around the systems from one function to another Data is hidden and cannot be accessed by external functions N/A
4 Program structure follows “Top Down Approach” Program structure follows “Bottom UP Approach” N/A
5
Examples:
C, Pascal, ALGOL and Modula-2
C++, JAVA and C# (C sharp)
 BASIC, COBOL, FORTRAN

Key points to remember in C language:

  1. The C language is structured, middle level programming language developed by Dennis Ritchie
  2. Operating system programs such as Windows, Unix, Linux are written in C language
  3. C89/C90 and C99 are two standardized editions of C language
  4. C has been written in assembly language




C – Basic Program


We are going to learn a simple “Hello World” C program in this section. Also, all the below topics are explained in this section which are the basics of a C program.
  1. C basic program with output and explanation
  2. Steps to write C programs and get the output
  3. Creation, Compilation and Execution of a C program
    1. How to install C compiler and IDE
  4. Basic structure of a C program

Basic commands in C programming to write basic C Program:

Below are few commands and syntax used in C programming to write a simple C program. Let’s see all the sections of a simple C program line by line.
S.no Command Explanation
1 #include This is a preprocessor command that includes standard input output header file(stdio.h) from the C library before compiling a C program
2 int main() This is the main function from where execution of any C program begins.
3 { This indicates the beginning of the main function.
4 /*_some_comments_*/ whatever is given inside the command “/*   */” in any C program, won’t be considered for compilation and execution.
5 printf(“Hello_World! “); printf command prints the output onto the screen.
6 getch(); This command waits for any character input from keyboard.
7 return 0;
This command terminates C program (main function) and returns 0.
8 }
This indicates the end of the main function.

1. C Basic Program:

#include
int main()
{
/* Our first simple C basic program */
printf(“Hello World! “);
getch();
return 0;
}                                                                                                                                                                                                    .

Output:

Hello World!                                                                                                                                                                                    .

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

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

3. Creation, Compilation and Execution of a C program:

Prerequisite:

  • If  you want to create, compile and execute C programs by your own, you have to install C compiler in your machine. Then, you can start to execute your own C programs in your machine.
  • You can refer below link for how to install C compiler and compile and execute C programs in your machine.
  •  

4. Basic structure of C program:

Structure of C program is defined by set of rules called protocol, to be followed by programmer while writing C program. All C programs are having sections/parts which are mentioned  below.
  1. Documentation section
  2. Link Section
  3. Definition Section
  4. Global declaration section
  5. Function prototype declaration section
  6. Main function
  7. User defined function definition section




Example C program to compare all the sections:

You can compare all the sections of a C program with the below C program.
/* C basic structure program Documentation section
Author: fresh2refresh.com
Date : 01/01/2012
*/#include    /* 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.
  • 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
1 Documentation section We can give comments about the program, creation or modified date, author name etc in this section. The characters or words or anything which are given between “/*” and “*/”, won’t be considered by C compiler for compilation process.These will be ignored by C compiler during compilation.
Example : /* comment line1 comment line2 comment 3 */
2 Link Section Header files that are required to execute a C program are included in this section
3 Definition Section In this section, variables are defined and values are set to these variables.
4 Global declaration section Global variables are defined in this section. When a variable is to be used throughout the program, can be defined in this section.
5 Function prototype declaration section Function prototype gives many information about a function like return type, parameter names used inside the function.
6 Main function Every C program is started from main function and this function contains two major sections called declaration section and executable section.
7 User defined function section User can define their own functions in this section which perform 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.
  • 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
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
  • %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
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.

    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.
  • For example, ‘A’ can be stored using char datatype. You can’t store more than one character using char data type.

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
#include
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;
}                                                                                                                                                                                                   .
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)
S.No C Data types storage Size Range
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
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
int main()
{
enum MONTH { Jan = 0, Feb, Mar };
enum MONTH month = Mar;
if(month == 0)
printf(“Value of Jan”);
else if(month == 1)
printf(“Month is Feb”);
if(month == 2)
printf(“Month is Mar”);
}                                                                                                                                                                                                    .
Output:
Month is March                                                                                                                                                                                .




3. Derived data type in C:

  • Array, pointer, structure and union are called derived data type in C language.
  • To know more about derived data types, please visit “C – Array“ , “C – Pointer” , “C – Structure” and “C – Union” topics in this tutorial.


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

  • 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
1 Integer constants int
unsigned int
long int
long long int
53, 762, -478 etc 
5000u, 1000U etc
483,647
2,147,483,680
2 Real or Floating point constants float
doule
10.456789
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.

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
  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 
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
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ? 

2. Example program using #define preprocessor directive in C:

#include 
#define height 100
#define number 3.14
#define letter ‘A’
#define letter_sequence “ABC”
#define backslash_char ‘\?’
void main()
{
printf(“value of height : %d \n”, height );
printf(“value of number : %f \n”, number );
printf(“value of letter : %c \n”, letter );
printf(“value of letter_sequence : %s \n”,letter_sequence);
printf(“value of backslash_char : %c \n”,backslash_char);
}

Output:

value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
  • C variable is a named location in a memory where a program can manipulate the data. This location is used to hold the value of the variable.
  • The value of the C variable may get 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 initialization
data_type variable_name = value;
int x = 50, y = 30; char flag = ‘x’, 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
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.
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
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);
}

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