C Language Operator Precedence Chart

Operator precedence describes the order in which C reads expressions. For example, the expression a=4+b*2 contains two operations, an addition and a multiplication. Does the C compiler evaluate 4+b first, then multiply the result by 2, or does it evaluate b*2 first, then add 4 to the result? The operator precedence chart contains the answers. Operators higher in the chart have a higher precedence, meaning that the C compiler evaluates them first. Operators on the same line in the chart have the same precedence, and the “Associativity” column on the right gives their evaluation order.

Operator TypeOperatorAssociativity
Primary Expression Operators() [] . -> expr++ expr–left-to-right
Unary Operators* & + – ! ~ ++expr –expr (typecast) sizeof()right-to-left
Binary Operators* / %left-to-right
+ –
>> <<
< <= > >=
== !=
&
^
|
&&
||
Ternary Operator?:right-to-left
Assignment Operators= += -= *= /= %= >>= <<= &= ^= |=right-to-left
Comma,left-to-right

Operators Introduction

An operator is a symbol which helps the user to command the computer to do certain mathematical or logical manipulations. Operators are used in C language programs to operate on data and variables. C has a rich set of operators which can be classified as:

  1. Arithmetic operators
  2. Relational Operators
  3. Logical Operators
  4. Assignment Operators
  5. Increment and Decrement Operators
  6. Conditional Operators
  7. Bitwise Operators
  8. Special Operators

1. Arithmetic Operators

All the basic arithmetic operations can be carried out in C. All the operators have almost the same meaning as in other languages. Both unary and binary operations are available in C language. Unary operations operate on a single operand; therefore, the number 5 when operated by unary – will have the value –5.

OperatorMeaning
+Addition or Unary Plus
Subtraction or Unary Minus
*Multiplication
/Division
%Modulus Operator

Examples of arithmetic operators are:

  • x + y
  • x – y
  • -x + y
  • a * b + c
  • -a * b

Here a, b, c, x, y are known as operands. The modulus operator is a special operator in C language which evaluates the remainder of the operands after division.

Example

#include   // include header file stdio.hvoid main()  // tell the compiler the start of the program{  int num1, num2, sum, sub, mul, div, mod;  // declaration of variables  scanf("%d %d", &num1, &num2);  // inputs the operands  sum = num1 + num2;  // addition of numbers and storing in sum  printf("nThe sum is = %d", sum);  // display the output  sub = num1 - num2;  // subtraction of numbers and storing in sub  printf("nThe difference is = %d", sub);  // display the output  mul = num1 * num2;  // multiplication of numbers and storing in mul  printf("nThe product is = %d", mul);  // display the output  div = num1 / num2;  // division of numbers and storing in div  printf("nThe division is = %d", div);  // display the output  mod = num1 % num2;  // modulus of numbers and storing in mod  printf("nThe modulus is = %d", mod);  // display the output}        

Integer Arithmetic

When an arithmetic operation is performed on two whole numbers or integers, such an operation is called integer arithmetic. It always gives an integer as the result. Let x = 27 and y = 5 be two integer numbers. Then the integer operation leads to the following results:

  • x + y = 32
  • x – y = 22
  • x * y = 135
  • x % y = 2
  • x / y = 5

In integer division, the fractional part is truncated.

Floating Point Arithmetic

When an arithmetic operation is performed on two real numbers or fraction numbers, such an operation is called floating point arithmetic. The floating point results can be truncated according to the properties requirement. The remainder operator is not applicable for floating point arithmetic operands.

Let x = 14.0 and y = 4.0 then:

  • x + y = 18.0
  • x – y = 10.0
  • x * y = 56.0
  • x / y = 3.50

Mixed Mode Arithmetic

When one of the operands is real and the other is an integer and if the arithmetic operation is carried out on these two operands, then it is called mixed mode arithmetic. If any one operand is of real type, then the result will always be real; thus 15/10.0 = 1.5.

2. Relational Operators

Often it is required to compare the relationship between operands and bring out a decision and program accordingly. This is when the relational operators come into picture. C supports the following relational operators.

OperatorMeaning
<is less than
<=is less than or equal to
>is greater than
>=is greater than or equal to
==is equal to

It is required to compare the marks of two students, salary of two persons; we can compare them using relational operators.

A simple relational expression contains only one relational operator and takes the following form:

exp1 relational operator exp2

Where exp1 and exp2 are expressions, which may be simple constants, variables or combination of them. Given below is a list of examples of relational expressions and evaluated values:

ecolebooks.com
  • 6.5 <= 25 TRUE
  • -65 > 0 FALSE
  • 10 < 7 + 5 TRUE

Relational expressions are used in decision making statements of C language such as if, while and for statements to decide the course of action of a running program.

3. Logical Operators

C has the following logical operators; they compare or evaluate logical and relational expressions.

OperatorMeaning
&&Logical AND
||Logical OR
!Logical NOT

Logical AND (&&)

This operator is used to evaluate two conditions or expressions with relational operators simultaneously. If both the expressions to the left and to the right of the logical operator are true, then the whole compound expression is true.

Example

a > b && x == 10

The expression to the left is a > b and that on the right is x == 10. The whole expression is true only if both expressions are true, i.e., if a is greater than b and x is equal to 10.

Logical OR (||)

The logical OR is used to combine two expressions or the condition evaluates to true if any one of the two expressions is true.

Example

a < m || a < n

The expression evaluates to true if any one of them is true or if both of them are true. It evaluates to true if a is less than either m or n and when a is less than both m and n.

Logical NOT (!)

The logical NOT operator takes a single expression and evaluates to true if the expression is false and evaluates to false if the expression is true. In other words, it just reverses the value of the expression.

For example

!(x >= y) – the NOT expression evaluates to true only if the value of x is neither greater than nor equal to y.

4. Assignment Operators

The Assignment Operator evaluates an expression on the right of the expression and substitutes it to the value or variable on the left of the expression.

Example

x = a + b

Here the value of a + b is evaluated and substituted to the variable x.

In addition, C has a set of shorthand assignment operators of the form:

var oper= exp;

Here var is a variable, exp is an expression and oper is a C binary arithmetic operator. The operator oper= is known as shorthand assignment operator.

Example

x += 1 is same as x = x + 1

The commonly used shorthand assignment operators are as follows:

Statement with simple assignment operatorStatement with shorthand operator
a = a + 1a += 1
a = a – 1a -= 1
a = a * (n+1)a *= (n+1)
a = a / (n+1)a /= (n+1)
a = a % ba %= b

Example for using shorthand assignment operator

#define N 100  // creates a variable N with constant value 100#define A 2    // creates a variable A with constant value 2main()  // start of the program{  int a;  // variable a declaration  a = A;  // assigns value 2 to a  while (a < N)  // while value of a is less than N  {  // evaluate or do the following    printf("%dn", a);  // print the current value of a    a *= a;  // shorthand form of a = a * a  }  // end of the loop}  // end of the program        

Output:

2
4
16

5. Increment and Decrement Operators

The increment and decrement operators are unary operators which are very useful in C language. They are extensively used in for and while loops. The syntax of the operators is given below:

  • ++variable_name
  • variable_name++
  • –variable_name
  • variable_name–

The increment operator ++ adds the value 1 to the current value of operand and the decrement operator — subtracts the value 1 from the current value of operand. ++variable_name and variable_name++ mean the same thing when they form statements independently, but they behave differently when they are used in expressions on the right hand side of an assignment statement.

Consider the following:

m = 5;y = ++m;  (prefix)

In this case the value of y and m would be 6.

Suppose if we rewrite the above statement as:

m = 5;y = m++;  (postfix)

Then the value of y will be 5 and that of m will be 6. A prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left. On the other hand, a postfix operator first assigns the value to the variable on the left and then increments the operand.

6. Conditional or Ternary Operator

The conditional operator consists of two symbols: the question mark ? and the colon :.

The syntax for a ternary operator is as follows:

exp1 ? exp2 : exp3

The ternary operator works as follows:

  • exp1 is evaluated first.
  • If the expression is true then exp2 is evaluated and its value becomes the value of the expression.
  • If exp1 is false, exp3 is evaluated and its value becomes the value of the expression.

Note that only one of the expressions is evaluated.

For example

a = 10;b = 15;x = (a > b) ? a : b;

Here x will be assigned the value of b. The condition follows that the expression is false; therefore b is assigned to x.

/* Example: to find the maximum value using conditional operator */#include void main()  // start of the program{  int i, j, larger;  // declaration of variables  printf("Input 2 integers : ");  // ask the user to input 2 numbers  scanf("%d %d", &i, &j);  // take the numbers from standard input and store them  larger = i > j ? i : j;  // evaluation using ternary operator  printf("The largest of two numbers is %dn", larger);  // print the largest number}  // end of the program        

Output:

Input 2 integers : 34 45
The largest of two numbers is 45

7. Bitwise Operators

C supports special operators known as bitwise operators for manipulation of data at bit level. A bitwise operator operates on each bit of data. These operators are used for testing, complementing or shifting bits to the right or left. Bitwise operators may not be applied to a float or double.

OperatorMeaning
&Bitwise AND
|Bitwise OR
^Bitwise Exclusive OR
<<Shift left
>>Shift right

8. Special Operators

C supports some special operators of interest such as comma operator, size of operator, pointer operators (& and *) and member selection operators (. and ->). The size of and the comma operators are discussed here. The remaining operators are discussed in forthcoming chapters.

The Comma Operator

The comma operator can be used to link related expressions together. A comma-linked list of expressions are evaluated left to right and the value of rightmost expression is the value of the combined expression.

For example the statement:

value = (x = 10, y = 5, x + y);

First assigns 10 to x and 5 to y and finally assigns 15 to value. Since comma has the lowest precedence in operators, the parenthesis is necessary. Some examples of comma operator are:

In for loops:

for (n=1, m=10; n <= m; n++, m++)

In while loops:

while (c = getchar(), c != ’10’)

Exchanging values:

t = x, x = y, y = t;

The size of Operator

The operator size of gives the size of the data type or variable in terms of bytes occupied in the memory. The operand may be a variable, a constant or a data type qualifier.

Example

  • m = sizeof(sum);
  • n = sizeof(long int);
  • k = sizeof(235L);

The size of operator is normally used to determine the lengths of arrays and structures when their sizes are not known to the programmer. It is also used to allocate memory space dynamically to variables during the execution of the program.

Example program that employs different kinds of operators. The results of their evaluation are also shown in comparison.

main()  // start of program{  int a, b, c, d;  // declaration of variables  a = 15; b = 10; c = ++a - b;  // assign values to variables  printf("a = %d, b = %d, c = %dn", a, b, c);  // print the values  d = b++ + a;  printf("a = %d, b = %d, d = %dn", a, b, d);  printf("a / b = %dn", a / b);  printf("a %% b = %dn", a % b);  printf("a *= b = %dn", a *= b);  printf("%dn", (c > d) ? 1 : 0);  printf("%dn", (c < d) ? 1 : 0);}        

Notice the way the increment operator ++ works when used in an expression. In the statement c = ++a – b; new value a = 16 is used thus giving value 6 to c. That is, a is incremented by 1 before using in expression.

However, in the statement d = b++ + a; the old value b = 10 is used in the expression. Here b is incremented after it is used in the expression.

We can print the character % by placing it immediately after another % character in the control string. This is illustrated by the statement:

printf(“a %% b = %dn”, a % b);

This program also illustrates that the expression:

c > d ? 1 : 0

Assumes the value 0 when c is less than d and 1 when c is greater than d.

Type conversions in expressions

Implicit type conversion

C permits mixing of constants and variables of different types in an expression. C automatically converts any intermediate values to the proper type so that the expression can be evaluated without losing any significance. This automatic type conversion is known as implicit type conversion.

During evaluation it adheres to very strict rules and type conversion. If the operands are of different types, the lower type is automatically converted to the higher type before the operation proceeds. The result is of higher type.

The following rules apply during evaluating expressions:

  • All short and char are automatically converted to int then:
  • If one operand is long double, the other will be converted to long double and result will be long double.
  • If one operand is double, the other will be converted to double and result will be double.
  • If one operand is float, the other will be converted to float and result will be float.
  • If one of the operand is unsigned long int, the other will be converted into unsigned long int and result will be unsigned long int.
  • If one operand is long int and other is unsigned int then:
    • If unsigned int can be converted to long int, then unsigned int operand will be converted as such and the result will be long int.
    • Else both operands will be converted to unsigned long int and the result will be unsigned long int.
  • If one of the operand is long int, the other will be converted to long int and the result will be long int.
  • If one operand is unsigned int the other will be converted to unsigned int and the result will be unsigned int.

Explicit Conversion

Many times there may arise a situation where we want to force a type conversion in a way that is different from automatic conversion.

Consider for example the calculation of number of female and male students in a class:

female_students
Ratio = ——————-
male_students

Since if female_students and male_students are declared as integers, the decimal part will be rounded off and its ratio will represent a wrong figure. This problem can be solved by converting locally one of the variables to the floating point as shown below:

Ratio = (float) female_students / male_students

The operator float converts the female_students to floating point for the purpose of evaluation of the expression. Then using the rule of automatic conversion, the division is performed by floating point mode, thus retaining the fractional part of the result. The process of such a local conversion is known as explicit conversion or casting a value. The general form is:

(type_name) expression

Specifier Meaning

  • %c – Print a character
  • %d – Print an Integer
  • %i – Print an Integer
  • %e – Print float value in exponential form
  • %f – Print float value
  • %g – Print using %e or %f whichever is smaller
  • %o – Print actual value
  • %s – Print a string
  • %x – Print a hexadecimal integer (Unsigned) using lower case a – f
  • %X – Print a hexadecimal integer (Unsigned) using upper case A – F
  • %a – Print an unsigned integer
  • %p – Print a pointer value
  • %hx – hex short
  • %lo – octal long
  • %ld – long unsigned integer

Input and Output

Input and output are covered in some detail. C allows quite precise control of these. This section discusses input and output from keyboard and screen.

The same mechanisms can be used to read or write data from and to files. It is also possible to treat character strings in a similar way, constructing or analyzing them and storing results in variables. These variants of the basic input and output commands are discussed in the next section.

Sxz9P4Kn4TkA0AYNHPnOuYofNtuFEE1KjRd8uFTwfl3TyxtevKv1477Jq 3hEe5oaXMsfBPmc6XUSt5LxMfxhEOrPj5927qlP099R4ygEYsWlQWjrj 2PsvuELFZESD8JXb5wjk

This offers more structured output than putchar. Its arguments are, in order; a control string, which controls what gets printed, followed by a list of values to be substituted for entries in the control string.

Example: int a,b;

printf(” a = %d,b=%d”,a,b);

Tvxbs3NAiWIr8ucTe3WY02XSbzzZvbaSEfvstHY8e2TvC91GovkQbo8iwntGVZm7vHpIIkfc3ill971nQ1KsODG721cZWFa89F109uK4JbPnet4iT1xUfajGzlyOzn9eh YmAos

It is also possible to insert numbers into the control string to control field widths for values to be displayed. For example %6d would print a decimal value in a field 6 spaces wide, %8.2f would print a real value in a field 8 spaces wide with room to show 2 decimal places. Display is left justified by default, but can be right justified by putting a – before the format information, for example %-6d, a decimal integer right justified in a 6 space field.

scanf

scanf allows formatted reading of data from the keyboard. Like printf it has a control string, followed by the list of items to be read. However scanf wants to know the address of the items to be read, since it is a function which will change that value. Therefore the names of variables are preceded by the & sign. Character strings are an exception to this. Since a string is already a character pointer, we give the names of string variables unmodified by a leading &.

Control string entries which match values to be read are preceded by the percentage sign in a similar way to their printf equivalents.

Example: int a,b;

scanf(“%d%d”, &a, &b);

getchar

getchar returns the next character of keyboard input as an int. If there is an error then EOF (end of file) is returned instead. It is therefore usual to compare this value against EOF before using it. If the return value is stored in a char, it will never be equal to EOF, so error conditions will not be handled correctly.

As an example, here is a program to count the number of characters read until an EOF is encountered. EOF can be generated by typing Control – d.

#include main(){  int ch, i = 0;  while((ch = getchar()) != EOF)    i++;  printf("%dn", i);}

putchar

putchar puts its character argument on the standard output (usually the screen).

The following example program converts any typed input into capital letters. To do this it applies the function toupper from the character conversion library ctype.h to each character in turn.

#include   /* For definition of toupper */#include   /* For definition of getchar, putchar, EOF */main(){  char ch;  while((ch = getchar()) != EOF)    putchar(toupper(ch));}

gets

gets reads a whole line of input into a string until a new line or EOF is encountered. It is critical to ensure that the string is large enough to hold any expected input lines.

When all input is finished, NULL as defined in stdio is returned.

#include main(){  char x[20];  gets(x);  puts(x);}

puts

puts writes a string to the output, and follows it with a new line character.

Example: Program which uses gets and puts to double space typed input.

#include main(){  char line[256]; /* Define string sufficiently large to store a line of input */  while(gets(line) != NULL) /* Read line */  {    puts(line); /* Print line */    printf("n"); /* Print blank line */  }}

Note that putchar, printf and puts can be freely used together.

Expression Statements

Most of the statements in a C program are expression statements. An expression statement is simply an expression followed by a semicolon. The lines:

i = 0;
i = i + 1;
printf(“Hello, world!n”);

are all expression statements. (In some languages, such as Pascal, the semicolon separates statements, such that the last statement is not followed by a semicolon. In C, however, the semicolon is a statement terminator; all simple statements are followed by semicolons. The semicolon is also used for a few other things in C; we’ve already seen that it terminates declarations, too.)

UNIT – 3

Branching and looping

CONTROL FLOW STATEMENT

IF- Statement:

It is the basic form where the if statement evaluates a test condition and directs program execution depending on the result of that evaluation.

Syntax:

if (Expression){  Statement 1;  Statement 2;}

Where a statement may consist of a single statement, a compound statement or nothing as an empty statement. The Expression also referred to as test condition must be enclosed in parenthesis, which causes the expression to be evaluated first. If it evaluates to true (a non-zero value), then the statement associated with it will be executed otherwise ignored and the control will pass to the next statement.

Example:

if (a > b){  printf("a is larger than b");}

IF-ELSE Statement:

An if statement may also optionally contain a second statement, the “else clause,” which is to be executed if the condition is not met. Here is an example:

if (n > 0)  average = sum / n;else {  printf("can't compute averagen");  average = 0;}

NESTED-IF Statement:

It’s also possible to nest one if statement inside another. (For that matter, it’s in general possible to nest any kind of statement or control flow construct within another.) For example, here is a little piece of code which decides roughly which quadrant of the compass you’re walking into, based on an x value which is positive if you’re walking east, and a y value which is positive if you’re walking north:

if (x > 0){  if (y > 0)    printf("Northeast.n");  else    printf("Southeast.n");}else {  if (y > 0)    printf("Northwest.n");  else    printf("Southwest.n");}

/* Illuminates nested if else and multiple arguments to the scanf function. */

#include main(){  int invalid_operator = 0;  char operator;  float number1, number2, result;  printf("Enter two numbers and an operator in the formatn");  printf("number1 operator number2n");  scanf("%f %c %f", &number1, &operator, &number2);  if (operator == '*')    result = number1 * number2;  else if (operator == '/')    result = number1 / number2;  else if (operator == '+')    result = number1 + number2;  else if (operator == '-')    result = number1 - number2;  else    invalid_operator = 1;  if (invalid_operator != 1)    printf("%f %c %f is %fn", number1, operator, number2, result);  else    printf("Invalid operator.n");}

Sample Program Output:

Enter two numbers and an operator in the format
number1 operator number2
23.2 + 12
23.2 + 12 is 35.2

Switch Case

This is another form of the multi-way decision. It is well structured, but can only be used in certain cases where:

  • Only one variable is tested, all branches must depend on the value of that variable. The variable must be an integral type (int, long, short or char).
  • Each possible value of the variable can control a single branch. A final, catch-all, default branch may optionally be used to trap all unspecified cases.

Hopefully an example will clarify things. This is a function which converts an integer into a vague description. It is useful where we are only concerned in measuring a quantity when it is quite small.

estimate(number)int number;/* Estimate a number as none, one, two, several, many */{  switch(number) {    case 0:      printf("Nonen");      break;    case 1:      printf("Onen");      break;    case 2:      printf("Twon");      break;    case 3:    case 4:    case 5:      printf("Severaln");      break;    default:      printf("Manyn");      break;  }}

Each interesting case is listed with a corresponding action. The break statement prevents any further statements from being executed by leaving the switch. Since case 3 and case 4 have no following break, they continue on allowing the same action for several values of number.

Both if and switch constructs allow the programmer to make a selection from a number of possible actions.

Loops

Looping is a way by which we can execute some set of statements more than one time continuously. In C there are mainly three types of loops used:

  • while Loop
  • do while Loop
  • For Loop

While Loop

Loops generally consist of two parts: one or more control expressions which control the execution of the loop, and the body, which is the statement or set of statements which is executed over and over.

The general syntax of a while loop is:

Initializationwhile (expression){  Statement1  Statement2  Statement3}

The most basic loop in C is the while loop. A while loop has one control expression, and executes as long as that expression is true. This example repeatedly doubles the number 2 (2, 4, 8, 16, …) and prints the resulting numbers as long as they are less than 1000:

int x = 2;while (x < 1000){  printf("%dn", x);  x = x * 2;}

(Once again, we’ve used braces {} to enclose the group of statements which are to be executed together as the body of the loop.)

For Loop

Our second loop, which we’ve seen at least one example of already, is the for loop. The general syntax of a for loop is:

for (Initialization; expression; Increments/decrements){  Statement1  Statement2  Statement3}

The first one we saw was:

for (i = 0; i < 10; i = i + 1)  printf("i is %dn", i);

(Here we see that the for loop has three control expressions. As always, the statement can be a brace-enclosed block.)

Do while Loop

This is very similar to the while loop except that the test occurs at the end of the loop body. This guarantees that the loop is executed at least once before continuing. Such a setup is frequently used where data is to be read. The test then verifies the data, and loops back to read again if it was unacceptable.

do{  printf("Enter 1 for yes, 0 for no :");  scanf("%d", &input_value);} while (input_value != 1 && input_value != 0);

The break Statement

We have already met break in the discussion of the switch statement. It is used to exit from a loop or a switch, control passing to the first statement beyond the loop or a switch.

With loops, break can be used to force an early exit from the loop, or to implement a loop with a test to exit in the middle of the loop body. A break within a loop should always be protected within an if statement which provides the test to control the exit condition.

The continue Statement

This is similar to break but is encountered less frequently. It only works within loops where its effect is to force an immediate jump to the loop control statement.

  • In a while loop, jump to the test statement.
  • In a do while loop, jump to the test statement.
  • In a for loop, jump to the test, and perform the iteration.

Like a break, continue should be protected by an if statement. You are unlikely to use it very often.

Take the following example:

int i;for (i=0; i<10; i++){  if (i == 5)    continue;  printf("%d", i);  if (i == 8)    break;}

This code will print 1 to 8 except 5.

Continue means, whatever code that follows the continue statement WITHIN the loop code block will not be executed and the program will go to the next iteration. In this case, when the program reaches i=5 it checks the condition in the if statement and executes ‘continue’, everything after continue, which are the printf statement, the next if statement, will not be executed.

Break statement will just stop execution of the loop and go to the next statement after the loop if any. In this case when i=8 the program will jump out of the loop. Meaning, it won’t continue till i=9, 10.

Comment:

  • The compiler is “line oriented”, and parses your program in a line-by-line fashion.
  • There are two kinds of comments: single-line and multi-line comments.
  • The single-line comment is indicated by “//”. This means everything after the first occurrence of “//”, UP TO THE END OF CURRENT LINE, is ignored.
  • The multi-line comment is indicated by the pair “/*” and “*/”. This means that everything between these two sequences will be ignored. This may ignore any number of lines.

Here is a variant of our first program:

/* This is a variant of my first program. * It is not much, I admit. */int main() {  printf("Hello World!n"); // that is all?  return(0);}

UNIT – 4

ARRAY AND STRING

Arrays are widely used data type in C language. It is a collection of elements of similar data type. These similar elements could be all integers, all floats or all characters. An array of characters is called a string whereas an array of integers or floats is simply called an array. So array may be defined as a group of elements that share a common name and that are defined by position or index. The elements of an array are stored in sequential order in memory.

There are mainly two types of arrays used:

  • One dimensional Array
  • Multidimensional Array

One dimensional Array

So far, we’ve been declaring simple variables: the declaration

int i;

declares a single variable, named i, of type int. It is also possible to declare an array of several elements. The declaration

int a[10];

declares an array, named a, consisting of ten elements, each of type int. Simply speaking, an array is a variable that can hold more than one value. You specify which of the several values you’re referring to at any given time by using a numeric subscript. (Arrays in programming are similar to vectors or matrices in mathematics.) We can represent the array a above with a picture like this:

UyIyzq0KuaFW6N0T SXtJTREUHrll2X8xUItPv2eN5QWtt8krvVNVkOs2w3yA2zl1M2tp7aoVc MqA412tk66PnNlwRPl0pCuLUGPjKQMK6 LB3RQk5TJUuU5V6Sgs4dyNz2diQ

In C, arrays are zero-based: the ten elements of a 10-element array are numbered from 0 to 9. The subscript which specifies a single element of an array is simply an integer expression in square brackets. The first element of the array is a[0], the second element is a[1], etc. You can use these “array subscript expressions” anywhere you can use the name of a simple variable, for example:

a[0] = 10;a[1] = 20;a[2] = a[0] + a[1];

Notice that the subscripted array references (i.e. expressions such as a[0] and a[1]) can appear on either side of the assignment operator. It is possible to initialize some or all elements of an array when the array is defined. The syntax looks like this:

int a[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

The list of values, enclosed in braces {}, separated by commas, provides the initial values for successive elements of the array.

The subscript does not have to be a constant like 0 or 1; it can be any integral expression. For example, it’s common to loop over all elements of an array:

int i;for (i = 0; i < 10; i = i + 1)  a[i] = 0;

This loop sets all ten elements of the array a to 0.

Arrays are a real convenience for many problems, but there is not a lot that C will do with them for you automatically. In particular, you can neither set all elements of an array at once nor assign one array to another; both of the assignments:

a = 0; /* WRONG */int b[10];b = a; /* WRONG */

are illegal.

To set all of the elements of an array to some value, you must do so one by one, as in the loop example above. To copy the contents of one array to another, you must again do so one by one:

int b[10];for (i = 0; i < 10; i = i + 1)  b[i] = a[i];

Remember that for an array declared:

int a[10];

there is no element a[10]; the topmost element is a[9]. This is one reason that zero-based loops are also common in C. Note that the for loop:

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

does just what you want in this case: it starts at 0, the number 10 suggests (correctly) that it goes through 10 iterations, but the less-than comparison means that the last trip through the loop has i set to 9. (The comparison i <= 9 would also work, but it would be less clear and therefore poorer style.)

Multidimensional Array

The declaration of an array of arrays looks like this:

int a2[5][7];

You have to read complicated declarations like these “inside out.” What this one says is that a2 is an array of 5 something’s, and that each of the something’s is an array of 7 ints. More briefly, “a2 is an array of 5 arrays of 7 ints,” or, “a2 is an array of array of ints.” In the declaration of a2, the brackets closest to the identifier a2 tell you what a2 first and foremost is. That’s how you know it’s an array of 5 arrays of size 7, not the other way around. You can think of a2 as having 5 “rows” and 7 “columns,” although this interpretation is not mandatory. (You could also treat the “first” or inner subscript as “x” and the second as “y.” Unless you’re doing something fancy, all you have to worry about is that the subscripts when you access the array match those that you used when you declared it, as in the examples below.)

To illustrate the use of multidimensional arrays, we might fill in the elements of the above array a2 using this piece of code:

int i, j;for (i = 0; i < 5; i = i + 1){  for (j = 0; j < 7; j = j + 1)    a2[i][j] = 10 * i + j;}

This pair of nested loops sets a2[1][2] to 12, a2[4][1] to 41, etc. Since the first dimension of a2 is 5, the first subscript index variable, i, runs from 0 to 4. Similarly, the second subscript varies from 0 to 6.

We could print a2 out (in a two-dimensional way, suggesting its structure) with a similar pair of nested loops:

for (i = 0; i < 5; i = i + 1){  for (j = 0; j < 7; j = j + 1)    printf("%dt", a2[i][j]);  printf("n");}

(The character t in the printf string is the tab character.)

Just to see more clearly what’s going on, we could make the “row” and “column” subscripts explicit by printing them, too:

for (j = 0; j < 7; j = j + 1)  printf("t%d:", j);printf("n");for (i = 0; i < 5; i = i + 1){  printf("%d:", i);  for (j = 0; j < 7; j = j + 1)    printf("t%d", a2[i][j]);  printf("n");}

This last fragment would print:

0: 1: 2: 3: 4: 5: 6:
0: 0 1 2 3 4 5 6
1: 10 11 12 13 14 15 16
2: 20 21 22 23 24 25 26
3: 30 31 32 33 34 35 36
4: 40 41 42 43 44 45 46

STRING

Strings are the combination of a number of characters; these are used to store any word in any variable or constant. A string is an array of characters. It is internally represented in system by using ASCII value. Every single character can have its own ASCII value in the system. A character string is stored in one array of character type.

e.g. “Ram” contains ASCII value per location. When we are using strings, these strings are always terminated by character ‘’. We use conversion specifier %s to set any string. We can have any string as follows:

char NM[25];

When we store any value in NM variable then it can hold only 24 characters because at the end of the string one character is consumed automatically by ‘’.

#include

There are some common inbuilt functions to manipulate strings in string.h file. These are as follows:

  1. strlen – string length
  2. strcpy – string copy
  3. strcmp – string compare
  4. strupr – string upper
  5. strlwr – string lower
  6. strcat – string concatenate

UNIT- 5

Function

A function is a “black box” that we’ve locked part of our program into. The idea behind a function is that it compartmentalizes part of the program, and in particular, that the code within the function has some useful properties:

  1. It performs some well-defined task, which will be useful to other parts of the program.
  2. It might be useful to other programs as well; that is, we might be able to reuse it (and without having to rewrite it).
  3. The rest of the program doesn’t have to know the details of how the function is implemented. This can make the rest of the program easier to think about.
  4. The function performs its task well. It may be written to do a little more than is required by the first program that calls it, with the anticipation that the calling program (or some other program) may later need the extra functionality or improved performance. (It’s important that a finished function do its job well, otherwise there might be a reluctance to call it, and it therefore might not achieve the goal of re-usability.)
  5. By placing the code to perform the useful task into a function, and simply calling the function in the other parts of the program where the task must be performed, the rest of the program becomes clearer: rather than having some large, complicated, difficult-to-understand piece of code repeated wherever the task is being performed, we have a single simple function call, and the name of the function reminds us which task is being performed.
  6. Since the rest of the program doesn’t have to know the details of how the function is implemented, the rest of the program doesn’t care if the function is reimplemented later, in some different way (as long as it continues to perform its same task, of course!). This means that one part of the program can be rewritten, to improve performance or add a new feature (or simply to fix a bug), without having to rewrite the rest of the program.

Functions are probably the most important weapon in our battle against software complexity. You’ll want to learn when it’s appropriate to break processing out into functions (and also when it’s not), and how to set up function interfaces to best achieve the qualities mentioned above: re-usability, information hiding, clarity, and maintainability.

So what defines a function? It has a name that you call it by, and a list of zero or more arguments or parameters that you hand to it for it to act on or to direct its work; it has a body containing the actual instructions (statements) for carrying out the task the function is supposed to perform; and it may give you back a return value, of a particular type.

Here is a very simple function, which accepts one argument, multiplies it by 2, and hands that value back:

int multbytwo(int x){  int retrieval;  retrieval = x * 2;  return retrieval;}

On the first line we see the return type of the function (int), the name of the function (multbytwo), and a list of the function’s arguments, enclosed in parentheses. Each argument has both a name and a type; multbytwo accepts one argument, of type int, named x. The name x is arbitrary, and is used only within the definition of multbytwo. The caller of this function only needs to know that a single argument of type int is expected; the caller does not need to know what name the function will use internally to refer to that argument. (In particular, the caller does not have to pass the value of a variable named x.)

Next we see, surrounded by the familiar braces, the body of the function itself. This function consists of one declaration (of a local variable retrieval) and two statements. The first statement is a conventional expression statement, which computes and assigns a value to retrieval, and the second statement is a return statement, which causes the function to return to its caller, and also specifies the value which the function returns to its caller.

The return statement can return the value of any expression, so we don’t really need the local retrieval variable; the function could be collapsed to:

int multbytwo(int x){  return x * 2;}

How do we call a function? We’ve been doing so informally since day one, but now we have a chance to call one that we’ve written, in full detail. Here is a tiny skeletal program to call multbytwo:

#include extern int multbytwo(int);int main(){  int i, j;  i = 3;  j = multbytwo(i);  printf("%dn", j);  return 0;}

This looks much like our other test programs, with the exception of the new line:

extern int multbytwo(int);

This is an external function prototype declaration. It is an external declaration, in that it declares something which is defined somewhere else. (We’ve already seen the defining instance of the function multbytwo, but maybe the compiler hasn’t seen it yet.) The function prototype declaration contains the three pieces of information about the function that a caller needs to know: the function’s name, return type, and argument type(s). Since we don’t care what name the multbytwo function will use to refer to its first argument, we don’t need to mention it. (On the other hand, if a function takes several arguments, giving them names in the prototype may make it easier to remember which is which, so names may optionally be used in function prototype declarations.) Finally, to remind us that this is an external declaration and not a defining instance, the prototype is preceded by the keyword extern.

The presence of the function prototype declaration lets the compiler know that we intend to call this function, multbytwo. The information in the prototype lets the compiler generate the correct code for calling the function, and also enables the compiler to check up on our code (by making sure, for example, that we pass the correct number of arguments to each function we call).

Down in the body of main, the action of the function call should be obvious: the line

j = multbytwo(i);

calls multbytwo, passing it the value of i as its argument. When multbytwo returns, the return value is assigned to the variable j. (Notice that the value of main‘s local variable i will become the value of multbytwo‘s parameter x; this is absolutely not a problem, and is a normal sort of affair.)

This example is written out in “longhand,” to make each step equivalent. The variable i isn’t really needed, since we could just as well call

j = multbytwo(3);

And the variable j isn’t really needed, either, since we could just as well call

printf("%dn", multbytwo(3));

Here, the call to multbytwo is a subexpression which serves as the second argument to printf. The value returned by multbytwo is passed immediately to printf. (Here, as in general, we see the flexibility and generality of expressions in C. An argument passed to a function may be an arbitrarily complex subexpression, and a function call is itself an expression which may be embedded as a subexpression within arbitrarily complicated surrounding expressions.)

We should say a little more about the mechanism by which an argument is passed down from a caller into a function. Formally, C is call by value, which means that a function receives copies of the values of its arguments. We can illustrate this with an example. Suppose, in our implementation of multbytwo, we had gotten rid of the unnecessary retrieval variable like this:

int multbytwo(int x){  x = x * 2;  return x;}

Recursive Functions

A recursive function is one which calls itself. This is another complicated idea which you are unlikely to meet frequently. We shall provide some examples to illustrate recursive functions.

Recursive functions are useful in evaluating certain types of mathematical functions. You may also encounter certain dynamic data structures such as linked lists or binary trees. Recursion is a very useful way of creating and accessing these structures.

Here is a recursive version of the Fibonacci function. We saw a non-recursive version of this earlier.

int fib(int num)/* Fibonacci value of a number */{  switch(num) {    case 0:      return(0);      break;    case 1:      return(1);      break;    default: /* Including recursive calls */      return(fib(num - 1) + fib(num - 2));      break;  }}

We met another function earlier called power. Here is an alternative recursive version.

double power(double val, unsigned pow){  if (pow == 0) /* pow(x, 0) returns 1 */    return(1.0);  else    return(power(val, pow - 1) * val);}

Notice that each of these definitions incorporate a test. Where an input value gives a trivial result, it is returned directly; otherwise the function calls itself, passing a changed version of the input values. Care must be taken to define functions which will not call themselves indefinitely, otherwise your program will never finish.

The definition of fib is interesting, because it calls itself twice when recursion is used. Consider the effect on program performance of such a function calculating the Fibonacci function of a moderate size number.

O3k9Ncnr9U3RgcQPigTUoaDVs OtabgLbqpT3 Nk3dWlkvu16lJEupdl22CQRzJoFeXZvrzKrz3wFYEvO LS1nTNp2WYvUoLv2YSP6zDfBLGxnB6EW2jfudnyOhr9s TpMEyyuE

If such a function is to be called many times, it is likely to have an adverse effect on program performance.

Don’t be frightened by the apparent complexity of recursion. Recursive functions are sometimes the simplest answer to a calculation. However there is always an alternative non-recursive solution available too. This will normally involve the use of a loop, and may lack the elegance of the recursive solution.

UNIT – 6

Pointer

A pointer is a variable that points to or references a memory location in which data is stored. In the computer, each memory cell has an address that can be used to access that location so a pointer variable points to a memory location. We can access and change the contents of this memory location via the pointer.

Pointer declaration:

A pointer is a variable that contains the memory location of another variable in which data is stored. Using pointer, you start by specifying the type of data stored in the location. The asterisk helps to tell the compiler that you are creating a pointer variable. Finally you have to give the name of the variable. The syntax is as shown below.

type *variable_name

The following example illustrates the declaration of pointer variable:

int *ptr;float *string;        

Address operator:

Once we declare a pointer variable then we must point it to something. We can do this by assigning to the pointer the address of the variable you want to point as in the following example:

ptr = &num;

The above code tells that the address where num is stored is assigned into the variable ptr. The variable ptr has the value 21260, if num is stored in memory at address 21260 then…

The following program illustrates the pointer declaration:

/* A program to illustrate pointer declaration */main(){  int *ptr;  int sum;  sum = 45;  ptr = ∑  printf("nSum is %dn", sum);  printf("nThe sum pointer is %d", ptr);}        

Pointer expressions & pointer arithmetic:

In expressions, like other variables pointer variables can be used. For example, if p1 and p2 are properly initialized and declared pointers, then the following statements are valid:

y = *p1 * *p2;sum = sum + *p1;z = 5 * - *p2 / p1;*p2 = *p2 + 10;        

C allows us to subtract integers to or add integers from pointers as well as to subtract one pointer from the other. We can also use shorthand operators with pointers like p1 += 1;, sum += *p2; etc. By using relational operators, we can also compare pointers like the expressions such as p1 > p2, p1 == p2 and p1 != p2 are allowed.

The following program illustrates the pointer expression and pointer arithmetic:

/* Program to illustrate the pointer expression and pointer arithmetic */#include main(){  int *ptr1, *ptr2;  int a, b, x, y, z;  a = 30; b = 6;  ptr1 = &a;  ptr2 = &b;  x = *ptr1 + *ptr2 * 6;  y = 6 * - *ptr1 / *ptr2 + 30;  printf("nAddress of a = %u", ptr1);  printf("nAddress of b = %u", ptr2);  printf("na = %d, b = %d", a, b);  printf("nx = %d, y = %d", x, y);  ptr1 = ptr1 + 70;  ptr2 = ptr2;  printf("na = %d, b = %d", a, b);}        

Pointers and function:

In a function declaration, pointers are very much used. Sometimes, only with a pointer a complex function can be easily represented and successful. In a function definition, the usage of the pointers may be classified into two groups:

  1. Call by reference
  2. Call by value

Call by value:

We have seen that there will be a link established between the formal and actual parameters when a function is invoked. As soon as temporary storage is created where the value of actual parameters is stored, the formal parameters pick up its value from storage area. The mechanism of data transfer between formal and actual parameters is referred to as call by value. The corresponding formal parameter always represents a local variable in the called function. The current value of the corresponding actual parameter becomes the initial value of formal parameter. In the body of the subprogram, the value of formal parameter may be changed by assignment or input statements. This will not change the value of the actual parameters.

/* Include  */void main(){  int x, y;  x = 20;  y = 30;  printf("nValue of a and b before function call = %d %d", x, y);  fncn(x, y);  printf("nValue of a and b after function call = %d %d", x, y);}fncn(p, q)int p, q;{  p = p + p;  q = q + q;}        

Call by Reference:

The address should be pointers, when we pass address to a function the parameters receiving. By using pointers, the process of calling a function to pass the address of the variable is known as call by reference. The function which is called by reference can change the value of the variable used in the call.

/* example of call by reference */#include void main(){  int x, y;  x = 20;  y = 30;  printf("nValue of a and b before function call = %d %d", x, y);  fncn(&x, &y);  printf("nValue of a and b after function call = %d %d", x, y);}fncn(p, q)int *p, *q;{  *p = *p + *p;  *q = *q + *q;}        

Pointer to arrays:

An array is actually very much similar to a pointer. We can declare as int *a is an address, because a[0] the array’s first element as a[0] and *a is also an address. The form of declaration is also equivalent. The difference is pointer can appear on the left of the assignment operator and it is a variable that is value. The array name cannot appear as the left side of assignment operator and is constant.

/* A program to display the contents of array using pointer */main(){  int a[100];  int i, j, n;  printf("nEnter the elements of the arrayn");  scanf("%d", &n);  printf("Enter the array elements");  for (i = 0; i < n; i++)    scanf("%d", &a[i]);  printf("Array elements are");  for (ptr = a; ptr < (a + n); ptr++)    printf("Value of a[%d] = %d stored at address %u", j++, *ptr, ptr);}        

Pointers and structures:

We know the name of an array stands for address of its zero element; the same concept applies for names of arrays of structures. Suppose item is an array variable of the struct type. Consider the following declaration:

struct products{  char name[30];  int manufacture;  float net;} item[2], *ptr;        



');}
Bc0138c3d2dab0944d91d638547c2715

subscriber

1 Comment

  • 1426cff8a28730ed6cd318e019dcb0f3

    avenue17, September 13, 2023 @ 5:54 pmReply

    At me a similar situation. I invite to discussion.

Leave a Reply

Your email address will not be published. Required fields are marked *

Accept Our Privacy Terms.*