Arrays in C

Arrays in C

Arrays in C Language

An array is an order sequence of finite data items of the same type that share a common name. The common name is the array name.

Each individual data item in the in the list is known as element of the array.

The name of an array is actually the memory address from where the storing of the elements of an array starts. Which is at index 0.

The elements of an array are stored in the contiguous addresses in the memory starting from the address referred to by the array name.

An array may be one-dimensional, two-dimensional or multidimensional. One-dimensional array represents a list of data items and is also known as vector.

A two dimensional array represents a table of data items consisting of rows and columns and is known as a matrix.

Declaring one dimensional array

type array_name[size];

int marks[5];

char name[10];

Initializing an one dimensional array

int marks[5]={23,45,32,34,33};

Arrays in C
Arrays in C

char name[5]=”RAMA”;

Addressing array elements

An array can accommodate only as much elements as per its predefined size. Suppose marks[5] is an array with size equal to 5. The lower bound always starts with index value 0 and upper bound is size-1 i.e. 4. So valid array addresses are marks[0]-marks[4]. These storage locations are called array index or subscript, So to access array elements of array

int marks[5]={1,2,3,4,5};

marks[0]=1;  

marks[1]=2;

marks[2]=3;  

marks[3]=4;  

marks[4]=5;  

marks[0], marks[1], marks[2], marks[3], marks[4], are the addresses of the array elements.

Important points about array –

  • Array is an ordered sequence of same type of objects, called elements of the array.
  • Any array name has lvalue and this lvalue is non-modifiable.
  • We can’t assign one array to another array of the same type.
  • Since the array name refers to the starting address from where the storage of the elements of the array starts, you can assign array to a pointer of the same type as it is of the each element of the array.
  • The array elements are stored in contiguous locations in the memory. This means that if an array whose type is int, starts storing its elements from the address 1111 then the first element will be stored at the address 1111, second at 1113, third at 1115 and so on.
  • The array is not self describing that is array does not contain within it any information regarding what is the type of the element it stores or what is its size etc.
  • Array has no control over its bounds. That is if the size of an array is 5 then legally you can access elements from arr[0] to arr[4]. But illegal access like arr[-2] also run without any error message flagged by the compiler.
  • Memory is statically allocated for an array in c. That is all the information regarding allocation of memory is needed at the compile time. So any incomplete information will be insufficient and will lead to compile- time error. such as a[]; error because size of array is not mentioned.
  • Since array name is a pointer constant no arithmetic can be performed on it. So the following expressions are invalid for an array named arr.

arr++;

arr–;

arr+1;

arr-1;

  • An array of characters whose last element is ‘\0’ is known as a string.
  • An array cannot be passed to a function. However its starting address can be passed.
  • An array cannot be returned from a function. However, its starting address can be returned.
  • In traditional c the storage classes that can be applied on an array are static or external but not register. However in ANSI C it may also include automatic .
  • If an automatic array is not initialized, all its elements will contain garbage values. static or external arrays, if not initialized, have all their elements initialized to 0.
  • To initialize character arrays there are two methods –

         char name[]=”RAMA”;

         char name[]={‘R’,’A’,’M’,’A’};

  • The size of an array should be mentioned in its declaration and it must not be a variable. The array size must be a constant expression.
  • In C you can’t use a constant defined using the const keyword to specify the size of an array
main()
{
  const int size=10;
   int a[size];    /* invalid in c */
}

Two Dimensional Array

When an array have more than one rows and columns then it is called two dimensional array. A two dimensional array can be declared like this –

 int a[2][3];

here first array index is called row denoted by i and second column denoted by j. Hence you can initialize an array of 2×3 size

int a[2][3]={{1,2,3},{4,5,6}};

To access the array elements –

a[0][0]=1;

a[0][1]=2;

a[0][2]=3;

a[1][0]=4;

a[1][1]=5;

a[1][2]=6;

#include<stdio.h>
void main()
{
int i,j;
int Matrix[2][3]={{1,2,3},{3,4,5}};
printf("Processing array elements \n");
for(i=0;i<2;i++)
{
                for(j=0;j<3;j++)
                                printf("%d \t",Matrix[i][j]);
                printf("\n");
}
}

Three Dimensional / Multidimensional Array

A three dimensional array can be thought of a book where each page is like a table or a two dimensional array and page no represent the third dimension. A three dimensional array can be declared as:

int a[2][3][4];

To initialize the above mentioned array –

int a[2][3][4]={   {

                             {1,2,3,4},

                             {2,3,4,5},

                             {8,7,6,5}

                             },

                             {

                             {7,5,4,4},  

                             {3,4,5,3},

                             {9,7,6,5}

                             }

                             };

The above mentioned array can be initialized as below-

First two dimensional Array

a[0][0][0]=1;       a[0][0][1]=2;       a[0][0][2]=3;       a[0][0][3]=4;

a[0][1][0]=2;       a[0][1][1]=3;       a[0][1][2]=4;       a[0][1][3]=5;

a[0][2][0]=8;       a[0][2][1]=7;       a[0][2][2]=6;       a[0][2][3]=5;

Similarly second table can be display as under –

a[1][0][0]=7;       a[1][0][1]=5;       a[1][0][2]=4;       a[1][0][3]=4;

a[1][1][0]=3;       a[1][1][1]=4;       a[1][1][2]=5;       a[1][1][3]=3;

a[1][2][0]=9;       a[1][2][1]=7;       a[1][2][2]=6;       a[1][2][3]=5;

 

Similar Topics :

Control Structures in C        Input/Output functions in C                 Variables in C

You may also like :

What is New in HTML5      How To Enable JavaScript in Browsers           Multiple GST and Interstate Sales invoice

 

 

To Download Official TurboC Compiler from here

Control Structures in C

Control Structures in c

Control Structures in C

The structures of a program which affects the order of execution of the statements are called control structures. The normal execution of statements is in sequential fashion but to change the sequential flow, various control structures are used. Broadly, control structures are of three types-

  • Selection /conditional – executes as per choice of action.
  • Iteration – Performs a repetitive action.
  • Jumping – used to skip the action, or particular statements.


Selection/Conditional control structures

Also called conditional control constructs and are used to choose from alternative course of actions based on certain conditions. It has various forms

  • if
  • if-else
  • nested if-else
  • if-else if
  • switch -case

If Statements

If statement tests a condition and if it results in non-zero(true) value then the statements following if are executed.

Syntax

if(condition)
{
                body of if
}

Note :

  • There is no semi colon after if statement
  • The conditional expression of c can have relational (<,<=, >,>=,==,)or logical(&&,||,!) operator but can’t have assignment operator.

Example to print the largest of three numbers

#include
void main()
{
int a,b,c,d;
printf("Enter any three numbers");
if(scanf("%d%d%d",&a,&b,&c))
          {
                d=a;
                if(b%d) d=b;
                if(c%d) d=c;
           }
printf("The largest number is %d",d);
}

Explanation – In the first if statement, it will scan for three variables a,b and c. This if statement will be TRUE only if all three variables are entered through standard input device.

d=a;

 Then value of a is assigned to d.

if(b%d) d=b;

In the second if statement modulus value of b against d is calculated , it will result in non zero if b is greater than d(which is actually value of a). hence value of b would be assigned to d. It actually means that b is greater than a. Now 

if(c%d) d=c;

value of c is compared with b and if it returns as non zero then c is greatest of all. Otherwise b is greatest.

In second and third if statements are false then a is the greatest of all.

if statement does not give any output if condition is false. To get the result for both true and false, if-else statement is used.

If-Else Statement

This control structure tests the if conditions and if it is true then the body of if is executed otherwise body of else is executed. If-else is more complete version as compare to simple if statement where you have statements for TRUE and FALSE conditions.

Syntax

if(condition)
  {
                body of if
}
else
{
                body of else
}

Example

 

#include
void main()
{
int a,b;
printf("Enter any two numbers");
scanf("%d%d",&a,&b);
if(a>b)
                printf("%d is greater than %d",a,b);
else
                printf("%d is greater than %d",b,a);
}

Note: Body of if -else statement should be enclosed in curly braces if it have more than one statements. The same is not mandatory for single statement.

Nested if-else statement

Sometimes, the body of if-else statement may be placed within  another if-else statement then it is called nested if-else statement. This control structure is particularly helpful to simultaneously test more than one conditions. For example a group of friends are planning a picnic on Sunday if it is a sunny day. So here two conditions are simultaneously tested, the day should be sunday and second it should be a sunny day.

Syntax

if(condition1)
{
                if(condition2)
                {
                                body of inner if
                }
                else
                {
                body of inner else
                }
}
else
{
if(condition3)
                {
                                body of inner else if
                }
                else
                {
                body of inner else
                }
}

Example to find out the largest of three numbers.

#include
void main()
{
int a,b,c;
printf("Enter any three numbers");
scanf("%d%d%d",&a,&b,&c);
if(a>b)
                {
                if(a>c) printf("%d is greatest of %d%d%d",a,a,b,c);
                else printf("%d is greatest of %d%d%d",c,a,b,c);
                }
else
                {
                if(b>c) printf("%d is greatest of %d%d%d",b,a,b,c);
                else printf("%d is greatest of %d%d%d",c,a,b,c);
                }
}

If-else if Statement

When you have to evaluate more than two conditions then you need to use if-else if ladder. This control structure is particularly helpful when you have more conditions to evaluate.

Syntax

if(condition1)
body of if
else if(condition2)
body of else if
else if(condition3)
body  of else if
else
body of else

Example to demonstrate grade of a student

#include
void main()
{
int marks;
printf("Enter the marks");
scanf("%d",&marks);
if(marks>=80)
printf("Excellent");
else if(marks>=70)
printf("A grade");
else if(marks>=60)
printf("B grade");
else if(marks>=50)
printf("Pass");
else
printf("Work Hard! You have failed");
}

Switch Statement

Switch control structure can cut short the long series of if-else if statements . The switch statement can select a case from several available cases. The case can be integral expression(int or char) only. If the case value matches with any of the available cases then statements below it are executed until break statement is encountered. If no matching case is found then default label is executed. If no default label has been defined then switch terminates.

Syntax

switch(expression)
{
case item1: action; break;  
case item2: action; break;  
case item3: action; break;  
case item4: action; break;  
default: default action;
}

Example

#include
void main()
{
int day;
printf("Enter the day between 1-7");
scanf("%d",&day);
switch(day)
                {
                   case 1:
                   printf("Monday"); break;  
                   case 2:
                    printf("Tuesday"); break;  
                    case 3:
                    printf("Wednesday");  break;  
                    case 4:
                    printf("Thursday");  break;  
                    case 5:
                    printf("Friday");  break;
                    case 6:
                    printf("Saturday");  break;
                    case 7:
                    printf("Sunday");  break;
                    default:
                    printf("Invalid choice enter value between 1-7");
                }
}

What are the differences between if and switch statement?

  1. If statement can test any type of expression (integral, floating point, logical, relational etc.) but switch can test only integral expression only.
  2. If statement encloses multiple statements inside curly braces but you can never put multiple statements of switch inside curly braces.
  3. Break can be used inside switch body but can’t be used inside if body.

Iterations

Iterations means repetitions. When you wish to repeat a task more than once then it is called iterative task. The iterative tasks can be performed in c language through loops.  Looping means to execute a task  repeatedly and simultaneously checking the condition when to stop.  

Loops control structures can be used to –

  • take same action on each character of a file until end of file is reached.
  • take the same action until the number becomes zero.
  • take the same action on each elements of an array until all array elements are processed.
  • take the same action until newline character is reached
  • take the same action on each item in the data set.
  • take the same action until the file gets printed.

C Language has three types of loops

  1. for loop
  2. while loop
  3. do-while loop

For Loop

For loop steps through a series of specified action once for each value monitoring the specified condition to terminate each time.

Syntax

for(initial_exp;cond_exp;modifier_exp)

loop body

here initial_exp – initialization expression. It initializes a variable with initial value

cond_exp – conditional expression. This condition decides whether to continue the loop or exit it.

modifier_exp – modifier expression. It changes the value of the variable after each iteration.

Example to write a counting from 0 to the value of i

#include
void main()
{
int x,i;
printf("Enter the value up to which you wish to write counting");
scanf("%d",&x);
for(i=0;i<=x;i++)
printf("%d\n",i);
}

Infinite Loop 

Infinite loop is a control structure which keep on executing it’s body indefinitely. Either it will keep on giving output continuously or no output at all. This kind of loops are also called indefinite or endless loop. 

Note – A loop control structure should always be finite means  it should terminate after some iterations, else it becomes infinite loop. Infinite loops are highly undesirable and due care should be taken to keep the loops finite.

for loop usage

  1           for loop control structure is best suited for the situations where we know in advance how many times the loop will execute.

2              for loop control structure is natural choice for processing the array elements of all dimensions

example

  #include
void main()
{
int i,j;
int a[2][2]={{1,2},{3,4}};
printf("Processing array elements \n");
for(i=0;i<2;i++)
        {
                for(j=0;j<2;j++)
                                printf("%d \t",a[i][j]);
                printf("\n");
        }
}

Conditions for infinite for loop

  • A for loop without conditional test is infinite for loop
  • A for loop whose conditional test is true for loop variables initial value but it’s not modified then loop becomes infinite loop.

While Loop

While loop is also called pre-test loop. It first tests the specified conditional expression and as long as the conditional expression evaluates to non-zero, action is taken.

Syntax

while(conditional expression)

body of while

here conditional expression can be condition or expression. so

while(1)

while(x=x+1)

while(n–) are all legal conditional expression in while loop.

Important points about while loop

  • While loop is mostly suited in the situations where it is not known for how many times the loop will continue executing. e.g. while(number!=0)
  • If conditional expression in a while loop is always evaluated as non zero then it infinite while loop. e.g. while(1) or while(!0).
  • Never us assignment operator in place of equality operator in the test condition
  • If the conditional expression evaluates to zero in the very starting then loop body will not execute even once.

Example – to reverse a positive number

 #include
void main()
{
int num, rem, num1=0;
printf("Enter a number");
scanf("%d",&num);
while(num)
          {
                rem=num%10;
                num1=num1*10+rem;
                num/=10;
          }
printf("The reversed number is %d",num1);
}

Do-while loop

Also called post test loop because it executes it’s body at least once without testing specified conditional expression and then makes the test. Do-while terminates when the conditional expression evaluates to zero.

Syntax

do
{
     body
} while(condition);

Notice the semicolon after condition

Important points about do-while loop

  • A do-while loop tests the condition after executing the body at least once.
  • A do-while will make minimum iteration as 1 even if the condition is false.
  • A do-while loop is good choice for processing menus because of it’s first task then test nature.

Difference between while and do-while loops

SNo While Do-while
1 While is a pre-test loop. It tests the condition first, if condition is true loop body will execute Do-while is a post test loop. It executes its body at least once without testing the condition
2 The minimum number of iterations is 0 The minimum number of iterations is 1
3 While and for loops are inter changeable in almost every situation Do-while and for loops are not inter changeable in most of the situations

3              Jumping

There are three jumping statements

  1. break
  2. continue
  3. goto

Break Statement

Break is a jumping statement that when encountered in a –

  • Switch block – skips the rest of the switch block at once and jump to the next statement just after the switch block
  • Loop- skips the rest of the loop statements and jumps to the next statement just after loop body

Example – To find the given number as prime

#include
#include
void main()
{
int n,i,s;
printf("Enter a number ");
scanf("%d",&n);
s=sqrt(n);
for(i=2;i<=s;i++)
                {
                   if(n%i==0) break;
                }
if(i>s)
                printf("%d is a prime number",n);
else
                printf("%d is a not a prime number",n);
}

Continue Statement

Continue is also a jump statement which skips rest of the statements in the loop body and jumps to the next iteration. It differs from break in a way that break simply comes out of a block in which it is defined but continue just skips the rest of statements after it and continue to execute the loop body with next iteration.

Goto statement

Although goto statement is avoided in c language still it is available in two forms unconditional goto and conditional goto. it is a jump statement which causes the control to jump from the place where goto is encountered to the place indicated by label.

  • Unconditional goto – Used to make jump to the specified label without testing a condition.

Syntax

goto labelname;
...
labelname:
statements;
  • Conditional goto – Used to make jump to the specified label after testing condition.

Syntax

if(condition)
goto labelname;
...
labelname:
statements;

 

Similar Posts :      Input/Output functions in C           Operators and Expressions in C           Variables in C

You may also like :

Let us Learn JavaScript from Step By Step       Reverse Charge Mechanism in Tally.ERP9    What is New in HTML5

To Download Official TurboC Compiler from here

Difference between break and continue

1) Break causes exit from the loop leaving rest of the iterations while continue causes control to continue with the next iteration
2) break can be used in all control structures (for, while, do-while loops and switch statements ) except constructs of if family. Continue can be used only in the looping constructs but not in switch and if family.
3) Break can be used inside an infinite loop to stop them. Continue can be used inside infinite loops to skip one iterations but it can not stop it.

Similarities between break and continue

1) Both are used to jump from one place to another by skipping rest of the statements after them.
2) Both can be used inside the loops.
3) Inside a loop both can be used with if or switch statements.

Infinite Loops

An infinite loop is a loop that keeps on executing its body as there is not control . Reason for loop to be infinite are –
1 When conditional expression always evaluates to TRUE
2 No condition is imposed to come out of the loop
3 No modifier expression to modify the loop variable

How to stop an infinite loop

By pressing Ctrl+break keys

Input/Output functions in C

Input/Output functions in C

 

 

Input/Output Functions in C

C Language doesn’t have built in input output functions to carry out input output operations. Instead, it is implemented via standard library functions called header files.

What is a header file

Header file contains the declarations and prototypes of the basic input/output functions used in the program files called source file. Whole set of library functions is divided into category wise and saved in different header files having extension “.h” as per its purpose. These header files have the references to the input/output functions within them, which are connected to their actual definitions when the actual program is run.

Some most commonly used header files-

stdio.h – contains functions related to standard input output

math.h –     contains functions related to mathematics

conio.h – contains functions related to Console input output

string.h – contains functions related to string handling

alloc.h – contains functions related to dynamic memory allocation

dos.h – contains functions related to DOS interface

stdlib.h – contains functions related to data conversion

Basic Input /Output Functions

Input/Output Functions in C by Sanjiv Kumar

The basic input/output sub system consists of keyboard and monitor. keyboard serves as default input device and monitor/console as basic output device. So the functions used for basic input and output operations can be divided into two categories- formatted and unformatted.

Formatted Input/Output functions

Formatted Input/Output functions allows better presentable view of data from standard input and standard output devices. It allows the output be formatted as per user requirements.  Example printf() and scanf().

printf Function

printf stands for print in formatted manner. It is used to write data in the required format from the computer to a standard output device. printf function is used to output the arguments of the following types-

  • Single character
  • Constants
  • Variables
  • Expressions resulting in numerical values
  • Strings

Syntax

1              printf(“string”);

It is the simplest form and will write the string in the standard output device.

2              printf(“format string”,argumentlist);

This is the typical printf() command where output is generated under the control of format string .

  • Format string controls how printf function converts, formats and prints its arguments.
  • Argumentlist can be a single or multiple variable, constant or expression.

A simple program to print a table of 2. where printf() formats the output to look pleasant.

#include
void main()
{
int x, i;
for (i=1;i<=10;i++)
{
       x=2*i;
       printf("2 \t*\t 1\t =\t%d\n",x);
}
}

Scanf Function

Scanf meaning is to scan or read in formatted manner. Scanf function is used to read the data in the required format from the standard input device into the computer. This function can be used to input the arguments of the following types-

  • Single Character
  • Variables
  • Expressions resulting in numerical values
  • strings

Syntax

scanf(“format string”,address_list);

here format string controls how scanf scans , converts and stores it’s arguments as per format specifiers. address_list is a list of addresses where the input data items are to be stored.

#include
void main()
{
char name[10];
printf("May I know your name , Please\n");
scanf("%s",&name);
printf("Hello! %s, How are you ",name);
}

Note: Two format strings may or may not have spaces, if it have then it is ignored but if there is space after the last format string then scanf scans for one extra value but the same is not saved anywhere hence ignored.

Unformatted IO function

C Language also have unformatted io functions which are displayed on the standard output devices on as it basis. You can’t use formatting on these functions. There are character and string io functions which falls under unformatted input/output category.

Character Input/Output functions

Character io functions are mainly helpful in reading/writing single character at a time. Which in turn can be used to read/write a complete file until End Of File signal is encountered.

There are three basic io functions

getchar()

getchar() function returns a character that has been most recently typed by the user and echoes it on the screen when user presses an Enter key. It is mandatory to press enter key to get the character shown on the standard output device.

getche()

getche function returns the recently typed character and echoes it on the screen, user don’t have to press enter key to get it displayed. The main advantage of getche is that user don’t have to press enter key after typing each character

getch()

getch() function also returns the character that has been recently typed by the user but it doesn’t display the typed character on the screen. Also user don’t have to press enter key after typing a character. This function is used in password building programs because when user enters a password it is not displayed on the visual display unit.

putchar()  

putchar function is used to write the one character to the standard output device, although operating system can redirect the output to other devices as well.

#include
void main()
{
int ch;
while((ch=getchar())!=EOF)
                {
                putchar(ch);
                if(ch=='\n')putchar('\n');
                }
}

Note: This program needs to be terminated by EOF (End of File) signal. EOF signal is generated by pressing Control+z in MS-DOS Systems.

String IO Functions

A group of characters form a string. C language supports String input/output functions namely gets and puts

gets()

gets function is used to read string of characters from standard input file ie stdin (which is keyboard by default ). gets reads and stores characters in an array pointed to by str until \n or EOF is reached.  gets is also helpful in reading whitespaces ie blanks and tabs etc.

puts()

puts function is used to copy a null-terminated string to the standard output file (stdout) except the terminating NULL Character itself.

#include
void main()
{
char name[20];
puts(Please tell  Your Name...);
gets(name);
printf("Hello! %s",name);
}

 

Similar Posts :    Operators and Expressions in C                  Elements of C Language

You may also like :

How to Activate GST in Tally.ERP9 ?        How To Enable JavaScript in Browsers      What is New in HTML5

To Download Official TurboC Compiler from here

 

What is header file in c ?

Header file plays very important role in compiling and executing C programs, it contains the declarations and prototypes of the basic input/output functions used in the program files

What is the use of printf and scanf ?

printf means print in formatted manner and is used to display output of c program to standard output device ie monitor in formatted manner. scanf means scan in formatted manner , this function is used to read input from standard input device ie keyboard in formatted manner and saves the data in some memory location.

What is difference in getchar, getche and getch functions?

getchar() function returns a character that has been most recently typed by the user and echoes it on the screen when user presses an Enter key.
getche function returns the recently typed character and echoes it on the screen, user don’t have to press enter key to get it displayed.
getch() function also returns the character that has been recently typed by the user but it doesn’t display the typed character on the screen.

Operators and Expressions in C

Operators and Expressions in C

 

Operators and Expressions in C

What is an Operator?

An Operator is a function which works on one or more operands to produce a new value, e.g. +,-,* ,/ are some operators. Operators in C differs at some points from mathematics. So C has its own system to manipulate operators.

What is operands?

operand is the data on which operator operates, it can be constant or variable or any other identifier.

For Example

In the expression x=y+2;      // x,y,2 are operands and = and + are operators.

Types of operators based on number of operands.

Unary Operators :- Unary operator works only on one operand e.g  -, ++, –, & , * etc. are unary operators.

Binary Operators :- Binary operators work on two operands. e.g. +-*/ etc.

Ternary Operator :- Ternary operator is the only operator which works on three operands. This operator is also called conditional operator. e.g. (?:) is ternary operator.

Expression

An expression is a combination of one or more of variables, constants, operators and function calls that results in some useful value after computation.

x=2;

sum=x+y;

printf(“%d”,x);

are expressions. expressions in c are always terminated by semi colon.

Kinds of operators as per their functions

Assignment Operator =
Arithmetic Operator + – * / %
Arithmetic Assignment Operator += -= *= /= %=
Comma Operator ,
Increment /Decrement Operator ++ —
Logical Operator && || !
Comparison Operator == != <= >= < >
Compile-time Operator Sizeof
Typecast Operator (type)
Bitwise Operator & | ^
Bitwise Assignment Operator &= |= ^=
Shift Operator << >>
Shift Assignment Operator <<= >>=
Member Selection Operator . ->
Address Operator &
Pointer Operator *
Conditional Operator ?:
Array Index Operator []
Function Call Operator ()
Stringization Operator #
Token Pasting Operator ##

Precedence and Associativity of Operators

Precedence

When more than one operators are involved in an expression, then the precedence determines the order in which the operands are evaluated. Eg a+b*c in this case multiplication will be evaluated first then followed by addition operation.

Associativity

If an expression have more than one operator with  same precedence level then associativity determines the direction of grouping of operators. It is of two types-

Left Associative (Left to Right)

When two or more operators having same precedence are encountered in an expression and are evaluated starting from left towards right. Then such operators are called left associative.

Right Associative (Right to Left)

These operators are evaluated starting from right towards left.

So combination of precedence and associativity determines the order of execution of execution of operators. Which is being  shown in the table below-

SNo Operator Precedence Associativity
1 () [] -> . Left to right
2 ! ~ + – * & sizeof (type) ++ — Right to left
3 * / % Left to right
4 + – (Binary Operator) Left to right
5 < <=  >= > Left to right
6 == != Left to right
7 & Left to right
8 ^ Left to right
9 | Left to right
10 && Left to right
11 || Left to right
12 ?: Right to left
13 = *= /= %= += -= &= ^= |= <<= >>= Right to left
14 , Left to right

 1)  Assignment Operator (=)

Assignment operator is used to assign a value to a variable. e.g x=5; here value 5 has been assigned to variable x (It must not be confused as equal to in mathematics). You can also do multiple assignment like this x=y=z=0;  It means that all the three variables has been assigned  zero in a single expression.

#include
void main()
{
int x;
x=5;
printf("The value of x=%d",x);
}

2)   Arithmetic Operators (+ – * / % )

These are the basic arithmetic operators

+     Addition  To add two or more numbers       2+2=4

–      Subtraction     To Subtract two or more numbers 4-2=2

*     Multiplication   To Multiply two or more numbers 2*3=6

/      Division          To Divide two Numbers, It works in two ways

       Integer division – If both the operators are integers then any fractional part in the result is        truncated, e.g. 5/2 will result in 2.

       Floating point division – If any of the operands of division operator is floating point value then it     will result in it will have fractional part as well. e.g. 7/3.5 = 2.0 

%    Modulus  Operator gives the remainder as output when applied on two integer values. It can’t   be applied on floating point numbers. e.g. -10%3 =  -1, 10%-3= 1, -10%-3= -1, etc

#include
void main()
{
int x=5,y=3,sum;
printf("The sum of x and y=%d",x+y);
printf("The subtraction of x and y=%d",x-y);
printf("The Multiplication of x and y=%d",x*y);
printf("The  division of x and y=%d",x/y);
printf("The modulus of x and y=%d",x%y);
sum=x+y;
printf("The sum of x and y=%d",sum);
}

3)    Increment and Decrement Operators

       To increase or decrease the value of a variable by one, C uses special operators called increment     and decrement operators respectively. Increment is denoted by ++ and decrement by –.

       Characteristics :

  • More efficient and faster , shorter to write and faster to execute.
  • Can be used as prefix like ++x/–x. It signifies that the value of x is to be incremented /decremented before evaluating the expression.
  • Can be used as postfix like x++/x–. It signifies that the value of x will be incremented /decremented after the expression has been evaluated.
#include
void main()
{
int x=5;
y=++x;
z=x++;
printf("The value of y =%d\n",y);
printf("The value of z =%d",z);
}

Result

The value of y=6

The value of z=5

4)    Comma Operator

       Comma operator is used to group pair of sub-expressions. Each sub-expression is evaluated from left to right. e.g x=5,y=7;

5)    Comparison Operators

       Comparison operators compares the values of their operands. The result of these operators is of boolean type means either it is true or false.

Relational Operators Meaning Example
Less Than a<b, 4<7<=”” span=””></b,>
Greater Than b>a , 6>3
<= Less Than equal to A<=b
>= Greater than equal to a>=b
Equality Operators    
== Equal to A==b, x==5
!= Not equal to A!=b

6)    Logical Operators

       C Language has three types of Logical operators which are evaluated as boolean values zero is taken as FALSE and non-zero as TRUE.

Operators Meaning Examples
&& Logical And (a<b)&&(a<c), (4<5)&&(6<7)<=”” span=””></b)&&(a<c),>
|| Logical or (a<b)||(a<c), (4<5)||(6<7)<=”” span=””></b)||(a<c),>
! Logical Not !x, !a

Evaluation of AND Operator

Result of AND operator is TRUE only when both/all the inputs are true (1). In the below mentioned example 0 stands for FALSE and 1 Stands for TRUE

A B Result
0 0 0
0 1 0
1 0 0
1 1 1

Evaluation of OR Operator

Or operator evaluates to zero/FALSE when it’s all inputs are zero as shown in table below.

A B Result
0 0 0
0 1 1
1 0 1
1 1 1

Evaluation of NOT Operator

NOT is a unary operator and evaluates the opposite of the input. If input is TRUE result will be FALSE.

A Result
0 1
1 0
#include
void main()
{
int English,Math;
printf("Enter the Marks in English and Math");
scanf("%d%d",&English,&Math);
if(English>=50 && Math>=50)
      {
       printf("Pass");
       }
else
       printf("Fail");
}

Short Circuiting

If the left operand of &&  is FALSE or left operand of || is TRUE then it is unnecessary to evaluate the right operand because if any of the input of && are FALSE then result will always be FALSE and in case of or if any of the input is TRUE then it’s result will always be TRUE. This process is called Short Circuiting.

7)   Bitwise Operators

As discussed above C Language have bitwise AND, OR, XOR, COMPLEMENT, Left shift and right shift  operators. As the name suggest these operators work on bit level and work only on integers. Out of these complement is unary operator rest other are binary.

Bitwise AND Operator

It will produce bitwise AND result of two operands

       A = 01110

       B=  10111

    A&B=       00110

Bitwise OR Operator

It will produce bitwise OR result of two operands

      A = 01110

      B=  10111

 A|B=  11111

Bitwise Complement Operator

It will produce bitwise 2’s Complement of an operand. in C complement of a number N is equal to -(N)+1 means 1’s complement+1.

A=11001

~A = 00111  

Bitwise Exclusive OR Operator

It will produce 0 is both the inputs are equal and 1 if both inputs are unequal.

A     =101010

B     =111011

A^B =010001

Left Shift Operator

Left shift operator shifts specified number of bits towards left

A=000010

A<<2 =001000

Right Shift Operator

Right shift operator shifts specified number of bits towards right.

A=100000

A>>2 =001000

Bitwise Assignment Operator

a&=b

a|=b

a^=b

a<<=b

a>>=b

8)   Conditional Operator

?: is the conditional operator which takes three operands. We may write it like exp1?exp2:exp3. This operator is just short notation of if-else statement.

e.g. if you wish to compare two numbers a,b then it can be solved as under:

#include
void main()
{
int a=5, b=4;
int c;
c=(a>b)?a:b;
printf("The greater value is  =%d",c);
}

9)   Typecast Operator

In order to convert one type of data to another, typecast operator is used. To typecast the int value to double here is an example

 #include
void main()
{
int a=5;
double d;
d=(double)a;
printf("The double value of a =%f",d);
}

10) Compile time operator

The sizeof operator is a unary operator also called compile time operator. It returns the size in bytes of its operands. Basically its main purpose is to allocate memory during compile time.

11) Address of Operator

Address of operator evaluates the memory address of the operand, denoted by &. It is a unary operator.

e.g. if you have x variable which has the value 5 then we can write it  x=5; to know it’s memory location  use address operator as &x.

12) Indirection Operator

Denoted by * and is a unary operator. It points to  the value at the address. Is called indirection operator and reverse of address operator.

13) Array Index Operator

An array index operator is used to access the elements of the array, denoted by opening and closing brackets []. Would be discussed in coming topics.

14) Function Call Operator

The pair of opening and closing parenthesis pair is called function call operator. It is followed by function name and encloses the arguments or parameters of the function.

e.g  int sum(); int sum(int x, int y);

15) Stringization Operator

It is a stringization operator which causes it’s operands to be surrounded by double quotes

e.g #define friends(x,y) printf(#x “and “#y” are friends”)

16) Member Selection Operator

The . and -> are called member selection operator and are used to access the members of structure and unions.

 

 

To Download Official TurboC Compiler from here

You may also like :

C Language Introduction          Elements of C Language           Variables in C

What is an operand ?

operand is the data on which operator operates, it can be constant or variable or any other identifier.

What are Arithmetic Operators ?

Arithmetic Operators (+ – * / % )
These are the basic arithmetic operators
+     Addition  To add two or more numbers       2+2=4
–      Subtraction     To Subtract two or more numbers 4-2=2
*     Multiplication   To Multiply two or more numbers 2*3=6
/      Division          To Divide two Numbers, It works in two ways
       Integer division – If both the operators are integers then any fractional part in the result is        truncated, e.g. 5/2 will result in 2.
       Floating point division – If any of the operands of division operator is floating point value then it     will result in it will have fractional part as well. e.g. 7/3.5 = 2.0 
%    Modulus  Operator gives the remainder as output when applied on two integer values. It can’t   be applied on floating point numbers. e.g. -10%3 =  -1, 10%-3= 1, -10%-3= -1, etc

What is an Expression ?

An expression is a combination of one or more of variables, constants, operators and function calls that results in some useful value after computation.

What is Precedence and Associativity ?

Precedence
When more than one operators are involved in an expression, then the precedence determines the order in which the operands are evaluated. Eg a+b*c in this case multiplication will be evaluated first then followed by addition operation.
Associativity
If an expression have more than one operator with  same precedence level then associativity determines the direction of grouping of operators. It is of two types-
Left Associative (Left to Right)
When two or more operators having same precedence are encountered in an expression and are evaluated starting from left towards right. Then such operators are called left associative.
Right Associative (Right to Left)
These operators are evaluated starting from right towards left.

Storage Classes in C

C Language Introduction
Storage Classes in C
Storage Classes in C

Storage Classes in C

Storage Class Specifiers

1) Scope

Scope of a variable is that portion of the program in which that identifier can be used. There are two types of scopes –

Block Scope

When a variable is declared inside a block then it is called block scope. It’s scope from the point of its declaration and ends at the end of the block.

All automatic variables have the block scope.

File Scope

Variables having file scope are defined outside of all blocks. Their scope starts from the point of their declaration to the end of the source file.

All global variables have the file scope.

2) Visibility

The visibility of a variable is that portion of the program source code from which legal access can be made to the variables. Both scope and visibility are tightly close together. Scope of a variable is remains fixed but the visibility can get hidden.

Storage Classes in C
Storage Classes in C

3) Lifetime

The lifetime of a variable is the period of time during which that variable physically exists and retains a particular value. Variable can have three types of lifetimes-

  • Static Lifetime

Variables having static lifetime are allocated memory as soon as execution process begins.This storage allocation lasts untill the program terminates. Static lifetime variables reside in the fixed data area of the memory. All variables with file scope have static lifetime. Variables can also be given static lifetime by using static or extern storage class specifiers. Static lifetime variables are all set to zero if they are not explicitly initialized to some value.

  • Local Lifetime

Local lifetime variables are also called automatic variables and are created on the runtime stack of memory (or in CPU registers if specified as register variables) when the enclosing block or function is entered.   They are deallocated when that block or function terminates.

The variables having local lifetime must be initialized explicitly otherwise it will take garbage value.

  • Dynamic Lifetime

Dynamic lifetime objects are created and destroyed explicitly by the request of the programmer using specific function calls e.g. malloc() and free() during the program. They get the storage area allocated from a special reserved area called heap or free area.

4) Linkage

Linkage is the connection between the actual declaration and the variable. This process is done by linker. Linkage can be of three types

  • No linkage

When the name of the variable is resolved at the context itself by the compiler, then there is no linkage is involved.

All local variables have not linkage at all.

  • Internal linkage

When the name to linked is in the current file itself then it is called internal linkage.

all variables having global scope have internal linkage.

  • External linkage

When the definition for the variable declared in the current file can be available anywhere outside the current file then it is called external linkage.

These variables are declared with ‘extern’ keyword.

Storage Classes

A storage class is used to define the scope, visibility, life-time and linkage of variables and/or functions within a C Program. They precede the type that they modify. We have five different storage classes in a C program −

  • auto
  • register
  • static
  • extern
  • typedef

The auto Storage Class

All the local variables have default automatic storage class also called as auto.

{

int month;

auto int year;

}

The two variables month and year have the same storage class. ‘auto’ can optionally be used within functions, i.e., local variables.

Register Storage Class

The register storage class variables are stored in a CPU registers instead of RAM. Which means that the variable has a maximum size equal to the register size (usually one word) and can’t have the address operator ‘&’  applied to it (because it does not have a memory location).

{

register int  miles;

}

The register storage class should only be used for variables that require quick access such as counters.

The static Storage Class

If a variable is declared with static storage class specifier then-

  • The storage of the variable is allocated from the data area of the memory
  • The variable is not available outside the function or file in which it is declared.
  • If the variable is not initialized explicitly then it takes default initial value as zero.
  • It receives the initial value before the execution of main function, and retains it until the program stops execution.
#include <stdio.h>
void func(void);
static int count = 5; /* global variable */
main()
{
   while(count--) {
      func();
   }
   return 0;
}
void func( void )
{
   static int a = 5;
   a+;
   printf("a is %d and count is %d\n", a, count);
}

The following result would appear on compiling and executing the above program −

a is 6 and count is 4

a is 7 and count is 3

a is 8 and count is 2

a is 9 and count is 1

a is 10 and count is 0

The extern Storage Class

The extern storage class is used to refer to a global variable that has been defined else where in some other program. When extern storage class is used for a variable , the variable cannot be initialized however, it points the variable name at a storage location that has been previously defined.

The extern storage specifier is used when there are two or more programs share the same global variables or functions.

First File: mainfile.c

#include <stdio.h>
#include"support.c"
int count ;
extern void write_extern();
main()
{
   count = 5;
   write_extern();
}

Second File: support.c

extern int count;
void write_extern(void)
{
   printf("count is %d\n", count);
}

In this example, extern is being used to declare count in the second file, which has been defined in the first file, mainfile.c.  To compile this program we must make forward declaration in mainfile.c by including support.c  −

on compiling  mainfile.c file. It will produce the following result −

count is 5

Typedef

The typedef storage class is different from other storage classes in that it is used tocreate user defined data types.

Syntax for typedef is

typedef type synonym

typedef char * string;

typedef unsigned char byte;

Official TurboC version can be downloaded from here

Similar Posts :

C Language Introduction         Elements of C Language              Variables in C

You May Also Like :

Reverse Charge Mechanism in Tally.ERP9            JavaScript String and Date Objects

 

What are storage classes in c?

Storage Classes
A storage class is used to define the scope, visibility, life-time and linkage of variables and/or functions within a C Program. They precede the type that they modify. We have five different storage classes in a C program −
auto
register
static
extern
typedef

What is Scope of a variable

Scope of a variable is that portion of the program in which that identifier can be used. It is of two types block scope and file scope.

What is Visibility of an identifier in c?

The visibility of a variable is that portion of the program source code from which legal access can be made to the variables. Both scope and visibility are tightly close together. Scope of a variable is remains fixed but the visibility can get hidden.

Variables in C

Variables in C

Variables in C Variable in C  is a named place in memory to store a value that can be modified by the program. Variables in C can be of three types- 1)    Synchronous Variables 2)    Asynchronous Variables 3)    Read Only Variables 1)    Synchronous Variables The value of these variables can be changed only through the … Read more

Elements of C Language

Elements in C

  Elements of C Language   Let us discuss about elements of C language. The first one is Character Set.  To view the Video session on  Elements of C Language , Play the video   The C Character Set The basic programming elements like variables, constants, keywords, operators, expressions, statements etc. can be created using … Read more

C Language Introduction

C Language Introduction

C Language Introduction C is a high-level language originally developed by Dennis M. Ritchie for UNIX operating system at Bell Labs. For the first time C Language was implemented on the DEC PDP-11 computer in 1972. In 1978, Brian Kernighan and Dennis Ritchie introduced description of C, now known as the K&R standard. The UNIX … Read more

Reverse Charge Mechanism in Tally.ERP9

REVERSE CHARGE MECHANISM -RCM Under normal circumstances, the supplier of goods or services collects the tax and pays it to the Govt. But in case of Reverse Charge mechanism , the receiver becomes liable to pay the tax to the Govt., which means the chargeability gets reversed. Reverse charge mechanism  is a mechanism where the … Read more

JavaScript String and Date Objects

Javascript string and date objects

JavaScript String The JavaScript string is a sequence of characters enclosed in double quotes. JavaScript Strings are basically Objects. JavaScript strings can be created by two different ways By string literal By string object (using new keyword) 1) By string literal The string literal in JavaScript is created using double quotes. It can take following … Read more

Please Subscribe to Stay Connected

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

DigitalSanjiv will use the information you provide on this form to be in touch with you and to provide updates and marketing.
Share via