C Programming


      -C is a powerful and, flexible and portable and elegantly structured programming language  .since c combines the features of high-level language with the elements of the  assembler it is suitable both system and application programming .
-'C' was evolved from ALGOL , BCPL and B by Dennis Ritchie at the Bell Laboratories in 1972 . 
-'C' uses many concepts from these languages and the concepts of data types and other power full features
Features Of C:

1)      It is robust language whose rich set of built in functions and operators can be used to write any complex program
2)      Program written in C are efficient and fast
3)      C support only 32-keywords ANSI C
4)      C language is well suited for structured programming 
5)      C ability to extend itself because collection of functions we can continuously added our own functions to c library

Basic Structure of C programs:

Documentation Section
Link section
Definition section
Global Declaration Section
Main()
{
Declaration part;
Executable part
}
Subprogram section
{
User defined functions;
}

C tokens:  

C tokens in passage of text ,individual words and punctuation marks are called tokens ( In C program the smallest individual units are known as 'C' tokens ).
 C has 6 types of tokens
1)Keywords
2)constants
3)Identifiers
4)Strings
5)Operators
6)Special Symbols

Keywords And Identifiers :

Every C word is classified as either a key word or an identifier .All keywords have fixed meaning and this meaning cannot be changed keywords serve as basic building blocks for program statements
C support more than 32-keywords
Ex: break ,if ,else ,long ,Int ,switch
Identifiers refers to the names of variables , functions and arrays .These are user defined names and consist of a sequences of letters , and digits with a letter as first character both uppercase and lowercase are permitted although lowercase letters commonly used and underscore character  also permitted.

Constants : 

Constants in C refers to fixed values that don’t change  during the execution of a program  . C supports several types of constants as Illustrated
1)Numeric constants( integer constants , Real constants)
2)Character constants (sting constants , single character constants)

 Variables  :

Variables are simply names used to refer  some location in memory (or) variable is a some stored area .
Variable names in C are made up of letters (upper and lower case) and digits. The underscore character ("_") is also permitted. Names must not begin with a digit.

Valid variable names :

Int x;
Int _x;
Char x_y[10];

invalid variable names :

int 2x;
char x  y[10];
int&x;
intsome_number;
This statement means we're declaring some space for a variable called some_number, which will be used to store integer data
Literals :

a literal is a notation for representing a fixed value .
int a=1;
String s="cat";
in the above example shows the representation of  integer and string literals.

Data Types:

C has a concept of 'data types' which are used to define a variable before its use .
ANSI C support three classes of data types
1)Primary Data types (Fundamental Types)
2)Derived Data types
3)User-Defined data types
1)Primary Data types (Fundamental Types) :

Character , integer , float,  void
printf("%p", (void*)&x);
Data type                             Range                                 Format specifiers
Char                               - 128 to 127                                       %c
Int                                    -32,768  to  32,767                          %d
Float                                 3.4e-38 to 3.4e+38                           %f
Double                             1.7 e-308 to 1.7 e+308                      %lf
Integer :

Int                        %d
Short Int               %d
Long Int               %ld

Char :

Signed char          %c
Unsigned char      %c

Floating point Type:

Float                          %f
Double                      %lf
Long double               %lf

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

            Double                      8 bytes               1.7 e-308 to 1.7 e+308  
            Float                         4bytes              3.4e-38 to 3.4e+38
             Long Double           10bytes               3.4 e-4932 to 1.1e+4932 .

Operators :

Operators are the symbol which operates on value or a variable. For example: + is a operator to perform addition. C programming language has wide range of operators to perform various operations. For better understanding of operators, these operators can be classified as  
Arithmetic Operators

Increment and Decrement Operators

Assignment Operators

Relational Operators

Logical Operators

Conditional Operators

Bitwise Operators

Special Operators

Arithmetic Operators : 

 C Language having following arithmetic operators

Operator
Meaning Of Operator
+
addition or unary plus
-
subtraction or  unary minus
*
Multiplication
/
Division
%
remainder after division( modulo division)

Increment and decrement operators:

In C, ++ and -- are called increment and decrement operators respectively. Both of these operators are unary operators, i.e, used on single operand. ++ adds 1 to operand and -- subtracts 1 to operand respectively.


Operator
Meaning Of Operator
--
Decrement (post and pre)
++
Increment(post and pre)
Assignment oprators:

The most common assignment operator is =. This operator assigns the value in right side to the left side


Operator
Example
Same As
=
a=b
a=b
+=
a+=b
a=a+b
-=
a-=b
a=a-b
*=
a*=b
a=a*b
/=
a/=b
a=a/b
%=
a%=b
a=a%b

Relational Operator:

Relational operators checks relationship between two operands. If the relation is true, it returns value 1 and if the relation is false, it returns value 0

Operator
Meaning of Operator
Example
==
Equal to
5==3 returns false (0)
Greater than
5>3 returns true (1)
Less than
5<3 returns false (0)
!=
Not equal to
5!=3 returns true(1)
>=
Greater than or equal to
5>=3 returns true (1)
<=
Less than or equal to
5<=3 return false (0)
Logical Operators:


Logical operators are used to combine expressions containing relation operators. In C, there are 3 logical operators:


Operator
Meaning of Operator
Example
&&
Logial AND 
If c=5 and d=2 then,((c==5) && (d>5)) returns   false.
||
Logical OR
If c=5 and d=2 then, ((c==5) || (d>5)) returns true.
!
Logical NOT
If c=5 then, !(c==5) returns false.

Conditional Operator :
Conditional operator takes three operands and consists of two symbols ?and : . Conditional operators are used for decision making in C.
 For example:
a=(c>0)?10:-10;
If c is greater than 0, value of  a will be 10  if c is less than 0, value of a will be -10.

Bitwise Operators:


A bitwise operator works on each bit of data. Bitwise operators are used in bit level programming.

Operator
Meaning Of Operator
&
Bitwise AND
|
Bitwise OR
^
Bitwise exclusive OR
~
Bitwise complement
<< 
Shift left
>> 
Shift right


Other Operators:

Comma operator(,) : It is used to separate  names
sizeof operator:  It is used to calculate size of  a variables( It may be Built in,Derive & User defined data types)

Operator associativity and precedence :

C has a precedence associated with it .this precedence is used to determine how an expression evaluated if it’s contain more than one operators . there  distinct levels of precedence  . an operator may belong to one of these levels . operator which is having highest precedence  is evaluated  first .
The operators of the same precedence are evaluated either from left to right or  from right to left . depending  onthere level this known as associativity .
Exmple:
9-(12/3)+3*2 -1
12/3-- evaluate first because bracket having highest priority
3*2 –evaluate second because bracket having second highest priority
Remain expr is evaluate left to right because operators having same precedence
Answer :9-4+6-1 =5+5=10

This table lists C operators in order of precedence (highest to lowest):
Their associativity indicates in what order operators of equal precedence in an expression are applied.

Operator
Description
Associativity
( )
[ ]
.
->
++, --
Parentheses (function call) (see Note 1)
Brackets (array subscript)
Member selection via object name
Member selection via pointer
Postfix increment/decrement (see Note 2)
left-to-right
++,   --
+ ,-
!, ~
(type)
*
&
sizeof
Prefix increment/decrement
Unary plus/minus
Logical negation/bitwise complement
Cast (convert value to temporary value of type)
Dereference
Address (of operand)
Determine size in bytes on this implementation
right-to-left
* , /  ,%
Multiplication/division/modulus
left-to-right
+ , -
Addition/subtraction
left-to-right
<<,    >>
Bitwise shift left, Bitwise shift right
left-to-right
<  ,<=
> , >=
Relational less than/less than or equal to
Relational greater than/greater than or equal to
left-to-right
= = , !=
Relational is equal to/is not equal to
left-to-right
&
Bitwise AND
left-to-right
^
Bitwise exclusive OR
left-to-right
|
Bitwise inclusive OR
left-to-right
&&
Logical AND
left-to-right
| |
Logical OR
left-to-right
? :
Ternary conditional
right-to-left
=
+=  ,-=
*= , /=
%= , &=
^= , |=
<<=  ,>>=
Assignment
Addition/subtraction assignment
Multiplication/division assignment
Modulus/bitwise AND assignment
Bitwise exclusive/inclusive OR assignment
Bitwise shift left/right assignment
right-to-left
,
Comma (separate expressions)
left-to-right

Type conversions in expressions:
When variables and constants of different types are combined in an expression then they are converted to same data type. The process of converting one predefined type into another is called type conversion.
Type conversion in c can be classified into the following two types:
1) Implicit Type Conversion
2) Explicit Type Conversion

1.Implicit Type Conversion:

When the type conversion is performed automatically by the compiler without programmers intervention, such type of conversion is known as implicit type conversion or type promotion.
->if the operands are different types the lower type is automatically converted into higher type  before the operation process .
1.      If either of the operand is of type long double, then others will be converted to long double and result will be long double.
2.      Else, if either of the operand is double, then others are converted to double.
3.      Else, if either of the operand is float, then others are converted to float.
4.      Else, if either of the operand is unsigned long int, then others will be converted to unsigned long int.
5.      Else, if one of the operand is long int, and the other is unsigned int, then
1.      if a long int can represent all values of an unsigned int, the unsigned int is converted to long int.
2.      otherwise, both operands are converted to unsigned long int.
6.      Else, if either operand is long int then other will be converted to long int.
7.      Else, if either operand is unsigned int then others will be converted to unsigned int.
2.Explicit Type Conversion
The type conversion performed by the programmer by posing the data type of the expression of specific type is known as explicit type conversion.
The explicit type conversion is also known as type casting.
Type casting in c is done in the following form:
(data_type)expression;
where, data_type is any valid c data type, and expression may be constant, variable or expression.
For example,
x=(int)a+b*d;
Control statements (or) Control structures :

Two types of control structures are there
I) Decision making and branching statements :
II) Decision making and looping statements :
 they determine the flow of control in the program .
I)Decision making and branching statements –
A ‘C’ program is a set of statements which are normally executed sequentially in the order in which they appearHowever sometimes we change the order of execution of the of statements based on certain conditions .These type of statements are called as decision making and branching statements .C language possesses following type of decision making statements –
I)if statement
II)switch statement
III)conditional operator statement
IV)goto statement

      if statement:

           if statement may be implemented in different forms depending on the complexity of the problem
         1.      Simple if statement
         2.      If…..else statement
         3.      Nested if…..else statement
         4.      else…if  ladder
     
       Simple if statement :

 The if statement is a powerful decision making statement. It is used to control the flow of execution of             statements .
This allow to computer evaluate expression first and then depending value of expression is true or transfer
control to the particular statement .


if(conditional-expression)

{
   statement-block ;
}

The ‘statement-block’ may be a single statement or a group of statements . In above simple if statement example if the ‘conditional-expression’ results true then the ‘statement-block’ will be executed .

If…..else statement :

The general form of if….else statement is as following: -
In case of if…else statement if the ‘conditional-expression’ results true then the ‘statement-block 1’ of if part will be executed and ‘statement-block-2’ of else part will be skipped . If ‘conditional-expression’ results false then the ‘statement-block1’ of if part will be skipped and the ‘statement-block2’ of else part will be executed 


if(conditional-expression)
{
statement-block 1 ;
}
else
{
statement-block 2 ;
}


Nested if…..else statement:

In case of below Nested if….else statement if ‘conditional-expression1’ of outermost if statement results false then both the statement-block will be skipped out . Otherwise the control goes to check ‘conditional-expression2’ of inner if statement . If ‘conditional-expression2’ results true then ‘statement-block1’ will be executed otherwise control will jump to ‘statement-block2’ of else part .


if(conditional-expression1)
{
if (conditional-expression2)
    {         
    statement-block-1 ;
    }
else
    {
    statement-block-2 ;
    }         
}
else
{
    statement-block-3 ;
}


else…if  ladder :

In case of Else….If ladder the control checks the conditional-expressions from top to bottom and when an expression results true then the statement-block of that condition is executed and all the remaining conditional statements will be skipped out . If no conditional-expression results true then the ‘statement-block4’ of else part is executed . This type of conditional statement is used where you have to choose one option from multiple options 


if(conditional-expression1)
{          
statement-block-1
}     
else if(conditional-expression2)
{
statement-block-2 ;
}
else if(conditional-expression3)
{
statement-block-3 ;
}
else
{
statement-block-4 ;
}


switch statement:

We have studied that if statements are used to select one option among multiple options .The use of if statements becomes complex when the number of choices increases . To overcome this problem C has an alternative decision statement known as switch statement .The switch statement is also called as built-in multi way decision statement. In switch statement the value of a given variable or expression is compared against a list of case values and when a match is found , the block of statement inside that case and all subsequent case statement as well as default statement will be executed .To prevent execution of subsequent cases we use break statement at the end of each case 


switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
default:
block-4;
}


conditional operator statement :

The ?: operator is useful for making two way decisions . It is a combination of ?and : . It takes three operands due to which it is called as ternary operator.It is popularly known as conditional operator also .
 conditional-expression ? expression1: expression2
The conditional-expression is evaluated first .If the result is nonzero ,then expression1 is evaluated and it’s value is returned as the value of conditional-expression .Otherwise , expression2 is evaluated and t it’s value is returned as as the value of conditional-expression.

goto statement :

Like other languages ,C supports the goto statement to branch unconditionally from one point to another point In the program . goto requires a level in to identify the place where the branch is to be made .A level is any valid variable name ,and must be followed by a colon . The level is placed just before the statement where control is to be transferred .The general forms of goto and level statement is as follows:-
GOTO statements is used two ways :–
1.      Forward Jump
2.      Backward Jump


1 .Forward Jump

goto label;
…………..
…………..
lebel;
statement ;

2 .Backward Jump
label;
statement ;
…………...
goto label;

II) Decision making and looping statements :

In looping ,a sequence of statements are executed until some conditions evaluated as false 
A loop consists two segments:-
1.      Body of the loop
2.      Control statement
The control statement tests the certain conditions and then directs the repeated execution of the statements contained in the body for the loop . Depending on the position of the control statement in the loop , there are three loops available in C .
1.      The While statement .
2.      The do-while statement .
3.      The for statement
The While statement .:

The while loop is the simplest loop structure in C .
The general form of WHILE loop is as following: -


while(check-condition)
{
 Body of loop;
}

The while loop is entry controlled loop in which the check condition is evaluated and if condition is true, then body of the loop is executed. After the execution of the body the control again checks the condition and if the condition results true then once again the body of the loop is executed . This process is repeated until the check condition results false. When check condition results false the control is transferred to the statement out of the body of loop .
The do-while statement .


do
{
Body of loop;
}while(check-condition);

In case of do-while loop, body of loop is executed first then the condition is evaluated .If the condition results true , the body of the loop executed . This process repeats until the check condition results false. When the check condition results false then control goes out of the loop body. It is called exit control loop because the test condition is evaluated at the bottom of the loop. Due to this body of loop is executed at least once even when the test condition false.

Difference between while and do-while :

 While
 Do-while
·         In While loop the condition is
tested first and then the statements are executed if the condition turns out to
be true.
·         Its is pre condition checking is there in while
·         simple while is more commonly
used its execute statements if and only if condition evaluated as true
·         while loop do not run in case the condition given is false
·         In a while loop the condition is
first tested and if it returns true then it goes in the loop
·         While loop is entry control loop
·         syntax


while(check-condition)
{
 Body of loop;
}
·         In do while the statements are executed for the first time and then the conditions
are tested, if the condition turns out to be true then the statements are
executed again.
·         Its is post condition checking is there in while
·         A do while is used for a block
of code that must be executed at least once.
·         A do while loop runs at least once
even though the the condition given is false
·         In a do-while loop the condition is
tested at the last
·         where as do while is exit control loop.
·         syntax


do
{
Body of loop;
}while(check-condition);

The for statement :

The for- loop is implemented where the number of times a statement or a block of statement to be executed is known in advance


for(counter-initialization;check-condition;counter-updation)
{
block-statement;
}

The counter-initialization is generally assignment statement which is used to set the loop control variable .
The condition is a relational expression that determines when the loop will exit . Counter–updation defines how loop control variable will change every time the loop body executed .These three parts of the forloopshould be ended with semicolon.

ARRAYS :

·         Arrays are derived data type in ‘C’ .
·         It is a fixed-size sequential collection of elements of the same type
·         Array is container for similar type of data
·         An array is used to store a collection of data,
·         Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index.
Arrays are three types

1)      One-Dimensional Array 
2)      Two-Dimensional Array 
3)      Multi-Dimensional Array 

1.One-Dimensional Array :


Syntax:

data-type<array name>[subscript];

·         subscript value always start from ‘0’ end with ‘arraysize-1’
·         using index value only we can perform reading and writing operation in arrays
·         data-type means any primary datatype

2.Two-Dimensional Array :
Declaration: 
Syntex:
data-type< array name >< [subscript-1] [subscript -2] > ;
using two-dimensional array we can store table of data
ex: int arr[3][3] ;

Row number (i)
Column numbers (j)
0
11
3
5
-9
-6
1
5
6
-8
7
24
2
-8
9
2
12
45
3
10
13
-10
4
5

int values [3] [4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10. 11, 12, };

3.Multi DimensionalArray :

C allows us declare three or more dimensions also
Syntax:
Type array_name[s1][s2][s3]……s[m];
Int x[3][5][2] ;

Strings :

“Group of characters which are enclosed in double quotes” is called strings
or
“A string is a sequence of characters that is treated as a single data item “.
The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello."

char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
or
char greeting[] = "Hello";

Following is the memory presentation of above defined string in C

SL.No
   Function & Purpose
1
strcpy(s1, s2);
Copies string s2 into string s1.
2
strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3
strlen(s1);
Returns the length of string s1.
4
strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2.
5
strchr(s1, ch);
Returns a pointer to the first occurrence of character ch in string s1.
6
strstr(s1, s2);
Returns a pointer to the first occurrence of string s2 in string s1.
7
Strrev(s1);
It reverse the  existing string of s1
8
Strlwr(s1);
It prints string s1 in lower case characters
9
Strupr(s1)
It prints string s1 in upper case characters

Functions:

Function is derived data type in c language
A function is a self block of code that perform a particular task .
Or
A function is a block of executable statement that perform the tasks that are define with in its block. 
Or
A function is a group of statements that together perform a task. Every C program has at least one function which is main().
Syntax:

return type <function- declaration>(argument-list)
                               { }

Functions are categorized as :

1.      Predefined (System defined) functions: 

These are the library function along with the software.Predefined function are avialble for use through header files like< stdio.h> ,<math.h><stdlib.h> etc.
Ex : main(),printf(),scanf() ;:

2.      User – defined function:

 These function are defined by the programmer for a specific purpose in a program. For example :

     #include <stdio.h>
       
       
         int add( int x, int y ) // function prototype
.       
          void main() 
         {
   
     
   
       }
    
      int add( int x, int y ) // function defintion
   {. 
   ……………….
     block of statements
   }
Parts of Functions :
 There are three main parts of a function, these are :
1.      Function prototype : A function prototype is a function declaration that specifies the return type, function name and the data types of the arguments.
2.      Function calling : A function is called by name in the program.
3.      Function definition : It is block of executable statement that are executed during function call. Return type, function name and data type of calling function must match with the function prototype.
Categories of user defined function :
A function can be categories based on their arguments and return values and it may be one of the following categories 
·         Function with no argument and no return value 
·         Function with argument but no return value.
·         Function with no argument but return value.
·         Function with argument and return value
·         Function returning multiple values
parameter passing  mechanisms to a functions :

1. Call by value 
2. Call by reference

1. Call by value :

In this mechanism , value of the actual parameter are copied to the formal parameter. Any changes on the value of formal arguments do not affect the value of actual arguments. 
2. Call by reference :

 In this mechanism , variables address are passed to the called function. Thus any changes made on the value of formal arguments are directly affect the value of actual arguments. For example :

recursive function :

A function that calls itself is known as recursive function and the process of calling function itself is known as recursion in C programming.

storage class in C:
A storage class defines the scope (visibility) and life time of variables and/or functions within a C Program. These specifiers precede the type that they modify. There are following storage classes which can be used in a C Program
·         auto
·         register
·         static
·         extern
The auto Storage Class :


The auto storage class is the default storage class for all local variables.
{
int mount;
auto int month;
}
The example above defines two variables with the same storage class, auto can only be used within functions, i.e. local variables.
The register Storage Class:
The register storage class is used to define local variables that should be stored in a register instead of RAM.
{
register int  miles;
}
The register should only be used for variables that require quick access such as counters. It should also be noted that defining 'register' goes not mean that the variable will be stored in a register. It means that it MIGHT be stored in a register depending on hardware and implementation restrictions.
The static Storage Class
The static storage class instructs the compiler to keep a local variable in existence during the lifetime of the program instead of creating and destroying it each time it comes into and goes out of scope. Therefore, making local variables static allows them to maintain their values between function calls.
The static modifier may also be applied to global variables. When this is done, it causes that variable's scope to be restricted to the file in which it is declared.
#include<stdio.h>
voidCheck();
int main()
{
Check();
Check();
Check();
}
voidCheck()
{
staticint c=0;
printf("%d\t",c);
c++;
}

o/p is=0  1  2
The extern Storage Class :
External variable can be accessed by any function. They are also known as global variables. Variables declared outside every function are external variables.
In case of large program, containing more than one file, if the global variable is declared in file 1 and that variable is used in file 2 then, compiler will show error. To solve this problem, keyword extern is used in file 2 to indicate that, the variable specified is global variable and declared in another file.

void Check();
int a=5;   
/* a is global variable because it is outside every function */
int main(){
a+=4;
Check();
return 0;
}
void Check(){
   ++a;
/*  ----- Variable a is not declared in this function but, works in any function as they are global variable -------  */
printf("a=%d\n",a);
}
o/p=10;

Enumerated Types:


An enum is a user-defined type in  ‘C’
An enumeration consists of a set of named integer constants
An enumeration type declaration gives the name of the (optional) enumeration tag and defines the set of named integer identifiers
Or
An enum is a user-defined type consisting of a set of named constants called enumerators.

Syntax:

enum identifier { enumerator-list }
The colors of the rainbow would be mapped like this.:
enum rainbowcolors
{
red,
orange,
yellow,
green,
blue,
indigo,
violet
};
Now internally, the compiler will use an int to hold these and if no values are supplied, red will be 0, orange is 1 ,yellow is 2, green is 3 , blue is 4 etc….
Enum rainbow colors
{
red=5,orange,yellow, green, blue,indigo,violet
}
If u assign red is 5 explicitly then orange is 6 ,yellow is 7 ,green is 8 etc…

Frequently asked C-Programs click here


C Language Viva questions and answers click here

Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.

3 comments:

  1. Tula's International School is known to be one of the residential school and best boarding school in India The school is affiliated with Central Board of Secondary Education (CBSE) and has been awarded with numerous accolades in the field of education.

    Tula's International School Boarding School in India

    ReplyDelete
  2. Informative , thanks for sharing

    ReplyDelete