BCA IST SEM C PRRAMMING

                                                                                 UNIT 1


History of C Language

History of C language is interesting to know. Here we are going to discuss a brief history of the c language.

C programming language was developed in 1972 by Dennis Ritchie at bell laboratories of AT&T (American Telephone & Telegraph), located in the U.S.A.

Dennis Ritchie is known as the founder of the c language.

It was developed to overcome the problems of previous languages such as B, BCPL, etc.

Initially, C language was developed to be used in UNIX operating system. It inherits many features of previous languages such as B and BCPL.

Let's see the programming languages that were developed before C language.

Language

Year

Developed By

Algol

1960

International Group

BCPL

1967

Martin Richard

B

1970

Ken Thompson

Traditional C

1972

Dennis Ritchie

K & R C

1978

Kernighan & Dennis Ritchie

ANSI C

1989

ANSI Committee

ANSI/ISO C

1990

ISO Committee

C99

1999

Standardization Committee

 

 

Features of C Language

C is the widely used language. It provides many features that are given below.

1.     Simple

2.     Machine Independent or Portable

3.     Mid-level programming language

4.     structured programming language

5.     Rich Library

6.     Memory Management

7.     Fast Speed

8.     Pointers

9.     Recursion

10.  Extensible

 

 

 

 

First C Program

Before starting the abcd of C language, you need to learn how to write, compile and run the first c program.

To write the first c program, open the C console and write the following code:

1.     #include <stdio.h>    

2.     int main(){    

3.     printf("Hello C Language");    

4.     return 0;   

5.     }  

#include <stdio.h> includes the standard input output library functions. The printf() function is defined in stdio.h .

Variables in C

variable is a name of the memory location. It is used to store data. Its value can be changed, and it can be reused many times.

It is a way to represent memory location through symbol so that it can be easily identified.

Let's see the syntax to declare a variable:

1.     type variable_list;  

The example of declaring the variable is given below:

1.     int a;  

2.     float b;  

3.     char c;  

Here, a, b, c are variables. The int, float, char are the data types.

We can also provide values while declaring the variables as given below:

1.     int a=10,b=20;//declaring 2 variable of integer type  

2.     float f=20.8;  

3.     char c='A';  

Rules for defining variables

  • A variable can have alphabets, digits, and underscore.
  • A variable name can start with the alphabet, and underscore only. It can't start with a digit.
  • No whitespace is allowed within the variable name.
  • A variable name must not be any reserved word or keyword, e.g. int, float, etc.

 

Valid variable names:

1.     int a;  

2.     int _ab;  

3.     int a30;  

Invalid variable names:

1.     int 2;  

2.     int a b;  

3.     int long;  

Types of Variables in C

There are many types of variables in c:

1.     local variable

2.     global variable

3.     static variable

4.     automatic variable

5.     external variable

Local Variable

A variable that is declared inside the function or block is called a local variable.

It must be declared at the start of the block.

1.     void function1(){  

2.     int x=10;//local variable  

3.     }  

You must have to initialize the local variable before it is used.

Global Variable

A variable that is declared outside the function or block is called a global variable. Any function can change the value of the global variable. It is available to all the functions.

It must be declared at the start of the block.

1.     int value=20;//global variable  

2.     void function1(){  

3.     int x=10;//local variable  

4.     }  

Static Variable

A variable that is declared with the static keyword is called static variable.

It retains its value between multiple function calls.

1.     void function1(){  

2.     int x=10;//local variable  

3.     static int y=10;//static variable  

4.     x=x+1;  

5.     y=y+1;  

6.     printf("%d,%d",x,y);  

7.     }  

If you call this function many times, the local variable will print the same value for each function call, e.g, 11,11,11 and so on. But the static variable will print the incremented value in each function call, e.g. 11, 12, 13 and so on.

Automatic Variable

All variables in C that are declared inside the block, are automatic variables by default. We can explicitly declare an automatic variable using auto keyword.

1.     void main(){  

2.     int x=10;//local variable (also automatic)  

3.     auto int y=20;//automatic variable  

4.     }  

External Variable

We can share a variable in multiple C source files by using an external variable. To declare an external variable, you need to use extern keyword.

myfile.h

1.     extern int x=10;//external variable (also global)  

program1.c

1.     #include "myfile.h"  

2.     #include <stdio.h>  

3.     void printValue(){  

4.         printf("Global variable: %d", global_variable);  

5.     }  

 

 

Data Types in C

A data type specifies the type of data that a variable can store such as integer, floating, character, etc.

There are the following data types in C language.

Types

Data Types

Basic Data Type

int, char, float, double

Derived Data Type

array, pointer, structure, union

Enumeration Data Type

enum

Void Data Type

void

Basic Data Types

The basic data types are integer-based and floating-point based. C language supports both signed and unsigned literals.

The memory size of the basic data types may change according to 32 or 64-bit operating system.

Let's see the basic data types. Its size is given according to 32-bit architecture.

Data Types

Memory Size

Range

char

1 byte

−128 to 127

signed char

1 byte

−128 to 127

unsigned char

1 byte

0 to 255

short

2 byte

−32,768 to 32,767

signed short

2 byte

−32,768 to 32,767

unsigned short

2 byte

0 to 65,535

int

2 byte

−32,768 to 32,767

signed int

2 byte

−32,768 to 32,767

unsigned int

2 byte

0 to 65,535

short int

2 byte

−32,768 to 32,767

signed short int

2 byte

−32,768 to 32,767

unsigned short int

2 byte

0 to 65,535

long int

4 byte

-2,147,483,648 to 2,147,483,647

signed long int

4 byte

-2,147,483,648 to 2,147,483,647

unsigned long int

4 byte

0 to 4,294,967,295

float

4 byte

double

8 byte

long double

10 byte

Keywords in C

A keyword is a reserved word. You cannot use it as a variable name, constant name, etc. There are only 32 reserved words (keywords) in the C language.

A list of 32 keywords in the c language is given below:

auto

break

case

char

const

continue

default

do

double

else

enum

extern

float

for

goto

if

int

long

register

return

short

signed

sizeof

static

struct

switch

typedef

union

unsigned

void

volatile

while

We will learn about all the C language keywords later.

C Identifiers

C identifiers represent the name in the C program, for example, variables, functions, arrays, structures, unions, labels, etc. An identifier can be composed of letters such as uppercase, lowercase letters, underscore, digits, but the starting letter should be either an alphabet or an underscore. If the identifier is not used in the external linkage, then it is called as an internal identifier. If the identifier is used in the external linkage, then it is called as an external identifier.

We can say that an identifier is a collection of alphanumeric characters that begins either with an alphabetical character or an underscore, which are used to represent various programming elements such as variables, functions, arrays, structures, unions, labels, etc. There are 52 alphabetical characters (uppercase and lowercase), underscore character, and ten numerical digits (0-9) that represent the identifiers. There is a total of 63 alphanumerical characters that represent the identifiers.

Rules for constructing C identifiers

  • The first character of an identifier should be either an alphabet or an underscore, and then it can be followed by any of the character, digit, or underscore.
  • It should not begin with any numerical digit.
  • In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that identifiers are case sensitive.
  • Commas or blank spaces cannot be specified within an identifier.
  • Keywords cannot be represented as an identifier.
  • The length of the identifiers should not be more than 31 characters.
  • Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Example of valid identifier

1.     total, sum, average, _m _, sum_1, etc.  

Example of invalid identifiers

1.     2sum (starts with a numerical digit)  

2.     int (reserved word)  

3.     char (reserved word)  

4.     m+n (special character, i.e., '+')  

Types of identifiers

  • Internal identifier
  • External identifier

Internal Identifier

If the identifier is not used in the external linkage, then it is known as an internal identifier. The internal identifiers can be local variables.

External Identifier

If the identifier is used in the external linkage, then it is known as an external identifier. The external identifiers can be function names, global variables.

Differences between Keyword and Identifier

Keyword

Identifier

Keyword is a pre-defined word.

The identifier is a user-defined word

It must be written in a lowercase letter.

It can be written in both lowercase and uppercase letters.

Its meaning is pre-defined in the c compiler.

Its meaning is not defined in the c compiler.

It is a combination of alphabetical characters.

It is a combination of alphanumeric characters.

It does not contain the underscore character.

It can contain the underscore character.

Let's understand through an example.

1.     int main()  

2.     {  

3.         int a=10;  

4.         int A=20;  

5.         printf("Value of a is : %d",a);  

6.         printf("\nValue of A is :%d",A);  

7.         return 0;  

8.     }  

Output

Value of a is : 10
Value of A is :20

The above output shows that the values of both the variables, 'a' and 'A' are different. Therefore, we conclude that the identifiers are case sensitive.

C Operators

An operator is simply a symbol that is used to perform operations. There can be many types of operations like arithmetic, logical, bitwise, etc.

There are following types of operators to perform different types of operations in C language.

  • Arithmetic Operators
  • Relational Operators
  • Shift Operators
  • Logical Operators
  • Bitwise Operators
  • Ternary or Conditional Operators
  • Assignment Operator
  • Misc Operator

Precedence of Operators in C

The precedence of operator species that which operator will be evaluated first and next. The associativity specifies the operator direction to be evaluated; it may be left to right or right to left

Let's understand the precedence by the example given below:

1.     int value=10+20*10;  

The value variable will contain 210 because * (multiplicative operator) is evaluated before + (additive operator).

The precedence and associativity of C operators is given below:

Category

Operator

Associativity

Postfix

() [] -> . ++ - -

Left to right

Unary

+ - ! ~ ++ - - (type)* &sizeof

Right to left

Multiplicative

* / %

Left to right

Additive

+ -

Left to right

Shift

<<>> 

Left to right

Relational

<<= >>=

Left to right

Equality

== !=

Left to right

Bitwise AND

&

Left to right

Bitwise XOR

^

Left to right

Bitwise OR

|

Left to right

Logical AND

&&

Left to right

Logical OR

||

Left to right

Conditional

?:

Right to left

Assignment

= += -= *= /= %=>>= <<= &= ^= |=

Right to left

Comma

,

Left to right


Next Topi

Constants in C

A constant is a value or variable that can't be changed in the program, for example: 10, 20, 'a', 3.4, "c programming" etc.

There are different types of constants in C programming.

List of Constants in C

Constant

Example

Decimal Constant

10, 20, 450 etc.

Real or Floating-point Constant

10.3, 20.2, 450.6 etc.

Octal Constant

021, 033, 046 etc.

Hexadecimal Constant

0x2a, 0x7b, 0xaa etc.

Character Constant

'a', 'b', 'x' etc.

String Constant

"c", "c program", "c in javatpoint" etc.

2 ways to define constant in C

There are two ways to define constant in C programming.

1.     const keyword

2.     #define preprocessor

1) C const keyword

The const keyword is used to define constant in C programming.

1.     const float PI=3.14;  

Now, the value of PI variable can't be changed.

1.     #include<stdio.h>    

2.     int main(){    

3.         const float PI=3.14;    

4.         printf("The value of PI is: %f",PI);    

5.         return 0;  

6.     }     

Output:

The value of PI is: 3.140000

If you try to change the the value of PI, it will render compile time error.

1.     #include<stdio.h>    

2.     int main(){    

3.     const float PI=3.14;     

4.     PI=4.5;    

5.     printf("The value of PI is: %f",PI);    

6.         return 0;  

7.     }     

Output:

Compile Time Error: Cannot modify a const object

2) C #define preprocessor

The #define preprocessor is also used to define constant. We will learn about #define preprocessor directive later.

Conditional Operator in C

The conditional operator is also known as a ternary operator. The conditional statements are the decision-making statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'.

As conditional operator works on three operands, so it is also known as the ternary operator.

The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is also a decision-making statement.

next →← prev

Conditional Operator in C

The conditional operator is also known as a ternary operator. The conditional statements are the decision-making statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'.

As conditional operator works on three operands, so it is also known as the ternary operator.

The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is also a decision-making statement.

Syntax of a conditional operator

1.     Expression1? expression2: expression3;  

The pictorial representation of the above syntax is shown below:

Meaning of the above syntax.

o    In the above syntax, the expression1 is a Boolean condition that can be either true or false value.

o    If the expression1 results into a true value, then the expression2 will execute.

o    The expression2 is said to be true only when it returns a non-zero value.

o    If the expression1 returns false value then the expression3 will execute.

o    The expression3 is said to be false only when it returns zero value.

Let's understand the ternary or conditional operator through an example.

1.     #include <stdio.h>  

2.     int main()  

3.     {  

4.         int age;  // variable declaration  

5.         printf("Enter your age");  

6.         scanf("%d",&age);   // taking user input for age variable  

7.         (age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting"));  // conditional operator  

8.         return 0;  

9.     }  

In the above code, we are taking input as the 'age' of the user. After taking input, we have applied the condition by using a conditional operator. In this condition, we are checking the age of the user. If the age of the user is greater than or equal to 18, then the statement1 will execute, i.e., (printf("eligible for voting")) otherwise, statement2 will execute, i.e., (printf("not eligible for voting")).

Let's observe the output of the above program.

If we provide the age of user below 18, then the output would be:

If we provide the age of user above 18, then the output would be:

As we can observe from the above two outputs that if the condition is true, then the statement1 is executed; otherwise, statement2 will be executed.

Till now, we have observed that how conditional operator checks the condition and based on condition, it executes the statements. Now, we will see how a conditional operator is used to assign the value to a variable.

Let's understand this scenario through an example.

1.     #include <stdio.h>  

2.     int main()  

3.     {  

4.        int a=5,b;  // variable declaration  

5.        b=((a==5)?(3):(2)); // conditional operator  

6.        printf("The value of 'b' variable is : %d",b);  

7.         return 0;  

8.     }  

In the above code, we have declared two variables, i.e., 'a' and 'b', and assign 5 value to the 'a' variable. After the declaration, we are assigning value to the 'b' variable by using the conditional operator. If the value of 'a' is equal to 5 then 'b' is assigned with a 3 value otherwise 2.

Output

The above output shows that the value of 'b' variable is 3 because the value of 'a' variable is equal to 5.

As we know that the behavior of conditional operator and 'if-else' is similar but they have some differences. Let's look at their differences.

o    A conditional operator is a single programming statement, while the 'if-else' statement is a programming block in which statements come under the parenthesis.

o    A conditional operator can also be used for assigning a value to the variable, whereas the 'if-else' statement cannot be used for the assignment purpose.

o    It is not useful for executing the statements when the statements are multiple, whereas the 'if-else' statement proves more suitable when executing multiple statements.

o    The nested ternary operator is more complex and cannot be easily debugged, while the nested 'if-else' statement is easy to read and maintain.

o    Bitwise Operator in C

o    The bitwise operators are the operators used to perform the operations on the data at the bit-level. When we perform the bitwise operations, then it is also known as bit-level programming. It consists of two digits, either 0 or 1. It is mainly used in numerical computations to make the calculations faster.

o    We have different types of bitwise operators in the C programming language. The following is the list of the bitwise operators:

Operator

Meaning of operator

&

Bitwise AND operator

|

Bitwise OR operator

^

Bitwise exclusive OR operator

~

One's complement operator (unary operator)

<< 

Left shift operator

>> 

Right shift operator

o    Let's look at the truth table of the bitwise operators.

X

Y

X&Y

X|Y

X^Y

0

0

0

0

0

0

1

0

1

1

1

0

0

1

1

1

1

1

1

1

Bitwise AND operator

Bitwise AND operator is denoted by the single ampersand sign (&). Two integer operands are written on both sides of the (&) operator. If the corresponding bits of both the operands are 1, then the output of the bitwise AND operation is 1; otherwise, the output would be 0.

For example,

1.     We have two variables a and b.  

2.     a =6;  

3.     b=4;  

4.     The binary representation of the above two variables are given below:  

5.     a = 0110  

6.     b = 0100  

7.     When we apply the bitwise AND operation in the above two variables, i.e., a&b, the output would be:  

8.     Result = 0100  

As we can observe from the above result that bits of both the variables are compared one by one. If the bit of both the variables is 1 then the output would be 1, otherwise 0.

Let's understand the bitwise AND operator through the program.

1.     #include <stdio.h>  

2.     int main()  

3.     {  

4.        int a=6, b=14;  // variable declarations  

5.        printf("The output of the Bitwise AND operator a&b is %d",a&b);  

6.        return 0;  

7.     }  

In the above code, we have created two variables, i.e., 'a' and 'b'. The values of 'a' and 'b' are 6 and 14 respectively. The binary value of 'a' and 'b' are 0110 and 1110, respectively. When we apply the AND operator between these two variables,

a AND b = 0110 && 1110 = 0110

Output

Bitwise OR operator

The bitwise OR operator is represented by a single vertical sign (|). Two integer operands are written on both sides of the (|) symbol. If the bit value of any of the operand is 1, then the output would be 1, otherwise 0.

For example,

1.     We consider two variables,  

2.     a = 23;  

3.     b = 10;  

4.     The binary representation of the above two variables would be:  

5.     a = 0001 0111  

6.     b = 0000 1010  

7.     When we apply the bitwise OR operator in the above two variables, i.e., a|b , then the output would be:  

8.     Result = 0001 1111  

As we can observe from the above result that the bits of both the operands are compared one by one; if the value of either bit is 1, then the output would be 1 otherwise 0.

Let's understand the bitwise OR operator through a program.

1.     #include <stdio.h>  

2.     int main()  

3.     {  

4.        int a=23,b=10;  // variable declarations  

5.        printf("The output of the Bitwise OR operator a|b is %d",a|b);  

6.        return 0;  

7.     }  

Output

Bitwise exclusive OR operator

Bitwise exclusive OR operator is denoted by (^) symbol. Two operands are written on both sides of the exclusive OR operator. If the corresponding bit of any of the operand is 1 then the output would be 1, otherwise 0.

For example,

1.     We consider two variables a and b,  

2.     a = 12;  

3.     b = 10;  

4.     The binary representation of the above two variables would be:  

5.     a = 0000 1100  

6.     b = 0000 1010  

7.     When we apply the bitwise exclusive OR operator in the above two variables (a^b), then the result would be:  

8.     Result = 0000 1110  

As we can observe from the above result that the bits of both the operands are compared one by one; if the corresponding bit value of any of the operand is 1, then the output would be 1 otherwise 0.

Let's understand the bitwise exclusive OR operator through a program.

1.     #include <stdio.h>  

2.     int main()  

3.     {  

4.        int a=12,b=10;  // variable declarations  

5.        printf("The output of the Bitwise exclusive OR operator a^b is %d",a^b);  

6.        return 0;  

7.     }  

Output

Bitwise complement operator

The bitwise complement operator is also known as one's complement operator. It is represented by the symbol tilde (~). It takes only one operand or variable and performs complement operation on an operand. When we apply the complement operation on any bits, then 0 becomes 1 and 1 becomes 0.

For example,

1.     If we have a variable named 'a',  

2.     a = 8;  

3.     The binary representation of the above variable is given below:  

4.     a = 1000  

5.     When we apply the bitwise complement operator to the operand, then the output would be:  

6.     Result = 0111  

As we can observe from the above result that if the bit is 1, then it gets changed to 0 else 1.

Let's understand the complement operator through a program.

1.     #include <stdio.h>  

2.     int main()  

3.     {  

4.        int a=8;  // variable declarations  

5.        printf("The output of the Bitwise complement operator ~a is %d",~a);  

6.        return 0;  

7.     }  

Output

Bitwise shift operators

Two types of bitwise shift operators exist in C programming. The bitwise shift operators will shift the bits either on the left-side or right-side. Therefore, we can say that the bitwise shift operator is divided into two categories:

  • Left-shift operator
  • Right-shift operator

Left-shift operator

It is an operator that shifts the number of bits to the left-side.

Syntax of the left-shift operator is given below:

1.     Operand << n  

Where,

Operand is an integer expression on which we apply the left-shift operation.

n is the number of bits to be shifted.

In the case of Left-shift operator, 'n' bits will be shifted on the left-side. The 'n' bits on the left side will be popped out, and 'n' bits on the right-side are filled with 0.

For example,

1.     Suppose we have a statement:  

2.     int a = 5;  

3.     The binary representation of 'a' is given below:  

4.     a = 0101  

5.     If we want to left-shift the above representation by 2, then the statement would be:   

6.     a << 2;  

7.     0101<<2 = 00010100  

Let's understand through a program.

1.     #include <stdio.h>  

2.     int main()  

3.     {  

4.         int a=5; // variable initialization  

5.         printf("The value of a<<2 is : %d ", a<<2);  

6.         return 0;  

7.     }  

Output

Right-shift operator

It is an operator that shifts the number of bits to the right side.

Syntax of the right-shift operator is given below:

1.     Operand >> n;  

Where,

Operand is an integer expression on which we apply the right-shift operation.

N is the number of bits to be shifted.

In the case of the right-shift operator, 'n' bits will be shifted on the right-side. The 'n' bits on the right-side will be popped out, and 'n' bits on the left-side are filled with 0.

For example,

1.     Suppose we have a statement,  

2.     int a = 7;  

3.     The binary representation of the above variable would be:  

4.     a = 0111  

5.     If we want to right-shift the above representation by 2, then the statement would be:  

6.     a>>2;  

7.     0000 0111 >> 2 = 0000 0001  

Let's understand through a program.

1.     #include <stdio.h>  

2.     int main()  

3.     {  

4.         int a=7; // variable initialization  

5.         printf("The value of a>>2 is : %d ", a>>2);  

6.         return 0;  

7.     }  

Output

Tokens in C

Tokens in C is the most important element to be used in creating a program in C. We can define the token as the smallest individual element in C. For `example, we cannot create a sentence without using words; similarly, we cannot create a program in C without using tokens in C. Therefore, we can say that tokens in C is the building block or the basic component for creating a program in C language.

Classification of tokens in C

Tokens in C language can be divided into the following categories:

  • Keywords in C
  • Identifiers in C
  • Strings in C
  • Operators in C
  • Constant in C
  • Special Characters in C

Let's understand each token one by one.

Keywords in C

Keywords in C can be defined as the pre-defined or the reserved words having its own importance, and each keyword has its own functionality. Since keywords are the pre-defined words used by the compiler, so they cannot be used as the variable names. If the keywords are used as the variable names, it means that we are assigning a different meaning to the keyword, which is not allowed. C language supports 32 keywords given below:

auto

double

int

struct

break

else

long

switch

case

enum

register

typedef

char

extern

return

union

const

float

short

unsigned

continue

for

signed

void

default

goto

sizeof

volatile

do

if

static

while

Identifiers in C

Identifiers in C are used for naming variables, functions, arrays, structures, etc. Identifiers in C are the user-defined words. It can be composed of uppercase letters, lowercase letters, underscore, or digits, but the starting letter should be either an underscore or an alphabet. Identifiers cannot be used as keywords. Rules for constructing identifiers in C are given below:

  • The first character of an identifier should be either an alphabet or an underscore, and then it can be followed by any of the character, digit, or underscore.
  • It should not begin with any numerical digit.
  • In identifiers, both uppercase and lowercase letters are distinct. Therefore, we can say that identifiers are case sensitive.
  • Commas or blank spaces cannot be specified within an identifier.
  • Keywords cannot be represented as an identifier.
  • The length of the identifiers should not be more than 31 characters.
  • Identifiers should be written in such a way that it is meaningful, short, and easy to read.

Strings in C

Strings in C are always represented as an array of characters having null character '\0' at the end of the string. This null character denotes the end of the string. Strings in C are enclosed within double quotes, while characters are enclosed within single characters. The size of a string is a number of characters that the string contains.

Now, we describe the strings in different ways:

char a[10] = "javatpoint"; // The compiler allocates the 10 bytes to the 'a' array.

char a[] = "javatpoint"; // The compiler allocates the memory at the run time.

char a[10] = {'j','a','v','a','t','p','o','i','n','t','\0'}; // String is represented in the form of characters.

Operators in C

Operators in C is a special symbol used to perform the functions. The data items on which the operators are applied are known as operands. Operators are applied between the operands. Depending on the number of operands, operators are classified as follows:

Unary Operator

A unary operator is an operator applied to the single operand. For example: increment operator (++), decrement operator (--), sizeof, (type)*.

Binary Operator

The binary operator is an operator applied between two operands. The following is the list of the binary operators:

  • Arithmetic Operators
  • Relational Operators
  • Shift Operators
  • Logical Operators
  • Bitwise Operators
  • Conditional Operators
  • Assignment Operator
  • Misc Operator

Constants in C

A constant is a value assigned to the variable which will remain the same throughout the program, i.e., the constant value cannot be changed.

There are two ways of declaring constant:

  • Using const keyword
  • Using #define pre-processor

Types of constants in C

Constant

Example

Integer constant

10, 11, 34, etc.

Floating-point constant

45.6, 67.8, 11.2, etc.

Octal constant

011, 088, 022, etc.

Hexadecimal constant

0x1a, 0x4b, 0x6b, etc.

Character constant

'a', 'b', 'c', etc.

String constant

"java", "c++", ".net", etc.

Special characters in C

Some special characters are used in C, and they have a special meaning which cannot be used for another purpose.

  • Square brackets [ ]: The opening and closing brackets represent the single and multidimensional subscripts.
  • Simple brackets ( ): It is used in function declaration and function calling. For example, printf() is a pre-defined function.
  • Curly braces { }: It is used in the opening and closing of the code. It is used in the opening and closing of the loops.
  • Comma (,): It is used for separating for more than one statement and for example, separating function parameters in a function call, separating the variable when printing the value of more than one variable using a single printf statement.
  • Hash/pre-processor (#): It is used for pre-processor directive. It basically denotes that we are using the header file.
  • Asterisk (*): This symbol is used to represent pointers and also used as an operator for multiplication.
  • Tilde (~): It is used as a destructor to free memory.
  • Period (.): It is used to access a member of a structure or a union.

C Expressions

An expression is a formula in which operands are linked to each other by the use of operators to compute a value. An operand can be a function reference, a variable, an array element or a constant.

Let's see an example:

1.     a-b;  

In the above expression, minus character (-) is an operator, and a, and b are the two operands.

There are four types of expressions exist in C:

  • Arithmetic expressions
  • Relational expressions
  • Logical expressions
  • Conditional expressions

Each type of expression takes certain types of operands and uses a specific set of operators. Evaluation of a particular expression produces a specific value.

For example:

1.     x = 9/2 + a-b;  

The entire above line is a statement, not an expression. The portion after the equal is an expression.

Arithmetic Expressions

An arithmetic expression is an expression that consists of operands and arithmetic operators. An arithmetic expression computes a value of type int, float or double.

When an expression contains only integral operands, then it is known as pure integer expression when it contains only real operands, it is known as pure real expression, and when it contains both integral and real operands, it is known as mixed mode expression.

Evaluation of Arithmetic Expressions

The expressions are evaluated by performing one operation at a time. The precedence and associativity of operators decide the order of the evaluation of individual operations.

When individual operations are performed, the following cases can be happened:

  • When both the operands are of type integer, then arithmetic will be performed, and the result of the operation would be an integer value. For example, 3/2 will yield 1 not 1.5 as the fractional part is ignored.
  • When both the operands are of type float, then arithmetic will be performed, and the result of the operation would be a real value. For example, 2.0/2.0 will yield 1.0, not 1.
  • If one operand is of type integer and another operand is of type real, then the mixed arithmetic will be performed. In this case, the first operand is converted into a real operand, and then arithmetic is performed to produce the real value. For example, 6/2.0 will yield 3.0 as the first value of 6 is converted into 6.0 and then arithmetic is performed to produce 3.0.

Let's understand through an example.

6*2/ (2+1 * 2/3 + 6) + 8 * (8/4)

Evaluation of expression

Description of each operation

6*2/( 2+1 * 2/3 +6) +8 * (8/4)

An expression is given.

6*2/(2+2/3 + 6) + 8 * (8/4)

2 is multiplied by 1, giving value 2.

6*2/(2+0+6) + 8 * (8/4)

2 is divided by 3, giving value 0.

6*2/ 8+ 8 * (8/4)

2 is added to 6, giving value 8.

6*2/8 + 8 * 2

8 is divided by 4, giving value 2.

12/8 +8 * 2

6 is multiplied by 2, giving value 12.

1 + 8 * 2

12 is divided by 8, giving value 1.

1 + 16

8 is multiplied by 2, giving value 16.

17

1 is added to 16, giving value 17.

Relational Expressions

  • A relational expression is an expression used to compare two operands.
  • It is a condition which is used to decide whether the action should be taken or not.
  • In relational expressions, a numeric value cannot be compared with the string value.
  • The result of the relational expression can be either zero or non-zero value. Here, the zero value is equivalent to a false and non-zero value is equivalent to true.

Relational Expression

Description

x%2 = = 0

This condition is used to check whether the x is an even number or not. The relational expression results in value 1 if x is an even number otherwise results in value 0.

a!=b

It is used to check whether a is not equal to b. This relational expression results in 1 if a is not equal to b otherwise 0.

a+b = = x+y

It is used to check whether the expression "a+b" is equal to the expression "x+y".

a>=9

It is used to check whether the value of a is greater than or equal to 9.

Let's see a simple example:

1.     #include <stdio.h>  

2.      int main()  

3.     {  

4.           

5.         int x=4;  

6.         if(x%2==0)  

7.         {  

8.             printf("The number x is even");  

9.         }  

10.      else  

11.      printf("The number x is not even");  

12.      return 0;  

13.  }  

Output

Logical Expressions

  • A logical expression is an expression that computes either a zero or non-zero value.
  • It is a complex test condition to take a decision.

Let's see some example of the logical expressions.

Logical Expressions

Description

( x > 4 ) && ( x < 6 )

It is a test condition to check whether the x is greater than 4 and x is less than 6. The result of the condition is true only when both the conditions are true.

x > 10 || y <11

It is a test condition used to check whether x is greater than 10 or y is less than 11. The result of the test condition is true if either of the conditions holds true value.

! ( x > 10 ) && ( y = = 2 )

It is a test condition used to check whether x is not greater than 10 and y is equal to 2. The result of the condition is true if both the conditions are true.

Let's see a simple program of "&&" operator.

1.     #include <stdio.h>  

2.     int main()  

3.     {  

4.         int x = 4;  

5.         int y = 10;  

6.         if ( (x <10) && (y>5))  

7.         {  

8.             printf("Condition is true");  

9.         }  

10.      else  

11.      printf("Condition is false");  

12.      return 0;  

13.  }  

Output

Let's see a simple example of "| |" operator

1.     #include <stdio.h>  

2.     int main()  

3.     {  

4.         int x = 4;  

5.         int y = 9;  

6.         if ( (x <6) || (y>10))  

7.         {  

8.             printf("Condition is true");  

9.         }  

10.      else  

11.      printf("Condition is false");  

12.      return 0;  

13.  }  

Output

Conditional Expressions

  • A conditional expression is an expression that returns 1 if the condition is true otherwise 0.
  • A conditional operator is also known as a ternary operator.

The Syntax of Conditional operator

Suppose exp1, exp2 and exp3 are three expressions.

exp1 ?exp2 : exp3

The above expression is a conditional expression which is evaluated on the basis of the value of the exp1 expression. If the condition of the expression exp1 holds true, then the final conditional expression is represented by exp2 otherwise represented by exp3.

Let's understand through a simple example.

1.     #include<stdio.h>  

2.     #include<string.h>  

3.     int main()  

4.     {  

5.         int age = 25;  

6.         char status;  

7.         status = (age>22) ? 'M''U';  

8.         if(status == 'M')  

9.         printf("Married");  

10.      else  

11.      printf("Unmarried");  

12.      return 0;  

13.  }  

Output

Compound Statement (C)

 

A compound statement (also called a "block") typically appears as the body of another statement, such as the if statement. Declarations and Types describes the form and meaning of the declarations that can appear at the head of a compound statement.

Syntax

compound-statement:
    { declaration-list
opt statement-listopt }

declaration-list:
    declaration
    declaration-list declaration

statement-list:
    statement
    statement-list statement

If there are declarations, they must come before any statements. The scope of each identifier declared at the beginning of a compound statement extends from its declaration point to the end of the block. It is visible throughout the block unless a declaration of the same identifier exists in an inner block.

Identifiers in a compound statement are presumed auto unless explicitly declared otherwise with registerstatic, or extern, except functions, which can only be extern. You can leave off the extern specifier in function declarations and the function will still be extern.

Storage is not allocated and initialization is not permitted if a variable or function is declared in a compound statement with storage class extern. The declaration refers to an external variable or function defined elsewhere.

Variables declared in a block with the auto or register keyword are reallocated and, if necessary, initialized each time the compound statement is entered. These variables are not defined after the compound statement is exited. If a variable declared inside a block has the static attribute, the variable is initialized when program execution begins and keeps its value throughout the program. See Storage Classes for information about static.

This example illustrates a compound statement:

CCopy

if ( i>0 )
{
line[i] = x;
x++;
i--;
}

In this example, if i is greater than 0, all statements inside the compound statement are executed in order.

Symbolic Constants in C – Symbolic Constant is a name that substitutes for a sequence of characters or a numeric constant, a character constant or a string constant.

When program is compiled each occurrence of a symbolic constant is replaced by its corresponding character sequence.

The syntax of Symbolic Constants in C

#define name text
where name implies symbolic name in caps.
text implies value or the text.

Also Learn - Types of Variables and Storage Classes

 

For example,

#define printf print
#define MAX 50
#define TRUE 1
#define FALSE 0
#define SIZE 15

The # character is used for preprocessor commands.

AIRTHMATIC OPERATOR

The following table shows all the arithmetic operators supported by the C language. Assume variable A holds 10 and variable B holds 20, then −

Operator

Description

Example

+

Adds two operands.

A + B = 30

Subtracts second operand from the first.

A − B = -10

*

Multiplies both operands.

A * B = 200

/

Divides numerator by de-numerator.

B / A = 2

%

Modulus Operator and remainder of after an integer division.

B % A = 0

++

Increment operator increases the integer value by one.

A++ = 11

--

Decrement operator decreases the integer value by one.

A-- = 9

Example

Try the following example to understand all the arithmetic operators available in C −

Live Demo

#include<stdio.h>
 
main(){
 
int a =21;
int b =10;
int c ;
 
   c = a + b;
printf("Line 1 - Value of c is %d\n", c );
        
   c = a - b;
printf("Line 2 - Value of c is %d\n", c );
        
   c = a * b;
printf("Line 3 - Value of c is %d\n", c );
        
   c = a / b;
printf("Line 4 - Value of c is %d\n", c );
        
   c = a % b;
printf("Line 5 - Value of c is %d\n", c );
        
   c = a++;
printf("Line 6 - Value of c is %d\n", c );
        
   c = a--;
printf("Line 7 - Value of c is %d\n", c );
}

When you compile and execute the above program, it produces the following result −

Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22

Unary operators in C/C++

Last Updated: 23-11-2020

Unary operator: are operators that act upon a single operand to produce a new value.

Types of unary operators:

1.       unary minus(-)

2.       increment(++)

3.       decrement(- -)

4.       NOT(!)

5.       Addressof operator(&)

6.       sizeof()

1.       unary minus
The minus operator changes the sign of its argument. A positive number becomes negative, and a negative number becomes positive.

2.  int a = 10;

3.  int b = -a;  // b = -10

unary minus is different from subtraction operator, as subtraction requires two operands.

4.       increment
It is used to increment the value of the variable by 1. The increment can be done in two ways:

1.       prefix increment
In this method, the operator preceeds the operand (e.g., ++a). The value of operand will be altered 
before it is used.



int a = 1;

int b = ++a;  // b = 2

2.       postfix increment
In this method, the operator follows the operand (e.g., a++). The value operand will be altered 
after it is used.

3.  int a = 1;

4.  int b = a++;   // b = 1

5.  int c = a;     // c = 2

5.       decrement
It is used to decrement the value of the variable by 1. The decrement can be done in two ways:

1.    prefix decrement
In this method, the operator preceeds the operand (e.g., – -a). The value of operand will be altered 
before it is used.

2.  int a = 1;

3.  int b = --a;  // b = 0

4.    posfix decrement
In this method, the operator follows the operand (e.g., a- -). The value of operand will be altered 
after it is used.

5.  int a = 1;

6.  int b = a--;   // b = 1

7.  int c = a;     // c = 0

6.    The following table shows all the relational operators supported by C language. Assume variable A holds 10 and variable B holds 20 then –

 

Assignment operator/relational operator-:

Operator

Description

Example

==

Checks if the values of two operands are equal or not. If yes, then the condition becomes true.

(A == B) is not true.

!=

Checks if the values of two operands are equal or not. If the values are not equal, then the condition becomes true.

(A != B) is true.

> 

Checks if the value of left operand is greater than the value of right operand. If yes, then the condition becomes true.

(A > B) is not true.

< 

Checks if the value of left operand is less than the value of right operand. If yes, then the condition becomes true.

(A < B) is true.

>=

Checks if the value of left operand is greater than or equal to the value of right operand. If yes, then the condition becomes true.

(A >= B) is not true.

<=

Checks if the value of left operand is less than or equal to the value of right operand. If yes, then the condition becomes true.

(A <= B) is true.

7.   Example

8.    Try the following example to understand all the relational operators available in C −

9.    Live Demo

10.#include<stdio.h>
11. 
12.main(){
13. 
14.int a =21;
15.int b =10;
16.int c ;
17. 
18.if( a == b ){
19.printf("Line 1 - a is equal to b\n");
20.}else{
21.printf("Line 1 - a is not equal to b\n");
22.}
23.  
24.if( a < b ){
25.printf("Line 2 - a is less than b\n");
26.}else{
27.printf("Line 2 - a is not less than b\n");
28.}
29.  
30.if( a > b ){
31.printf("Line 3 - a is greater than b\n");
32.}else{
33.printf("Line 3 - a is not greater than b\n");
34.}
35. 
36./* Lets change value of a and b */
37.   a =5;
38.   b =20;
39.  
40.if( a <= b ){
41.printf("Line 4 - a is either less than or equal to  b\n");
42.}
43.  
44.if( b >= a ){
45.printf("Line 5 - b is either greater than  or equal to b\n");
46.}
47.}

48.  When you compile and execute the above program, it produces the following result −

49.Line 1 - a is not equal to b
50.Line 2 - a is not less than b
51.Line 3 - a is greater than b
52.Line 4 - a is either less than or equal to  b
53.Line 5 - b is either greater than  or equal to b

 

UNIT 2

control structures-:

statement that is used to control the flow of execution in a program is called control structure. It combines instruction into logical unit. Logical unit has one entry point and one exit point.

Types of control structures

1. Sequence

2. Selection

3. Repetition

4. Function call

1. SequenceStatements are executed in a specified order. No statement is skipped and no statement is executed more than once.

Flow chart-:

For Example

#include<stdio.h>

void main()

int a;
{
int a=5;
printf(“Square of a = %d”,a);
}

2. Selection:

It selects a statement to execute on the basis of condition. Statement is executed when the condition is true and ignored when it is false e.g if, if else, switch structures.

Flow chart-:

For Example:

#include<stdio.h>

#include<conio.h>

void main ()

{

int y;

clrscr();

printf("Enter a year:");

scanf("%d",&y);

if (y % 4==0)

printf("%d is a leap year.",y);

elseprintf("%d is not a leap year.".y)

getch();

}

 

3. Repetition:

In this structure the statements are executed more than one time. It is also known as iteration or loop e.g while loop, for loop do-while loops etc.

Flow chart-:

For Example:

#include<stdio.h>

#include<conio.h>

void main()

{

int a=1;

clrscr();

while(a<=5)

{

printf(“I Love Pakistan\n”);

a++;

} //end of while

} //end of main

4. Function call:

It is used to invite or call a piece of code or statement. In this case control jumps from main program to that piece of code and then returns back to main program.

Flow chart-:

 

 

Address Calculation in single (one) Dimension Array:

Array of an element of an array say “A[ I ]” is calculated using the following formula:

Address of A [ I ] = B + W * ( I – LB )

Where,
B = Base address
W = Storage Size of one element stored in the array (in byte)
I = Subscript of element whose address is to be found

LB = Lower limit / Lower Bound of subscript, if not specified assume 0 (zero)

Example:

Given the base address of an array B[1300…..1900] as 1020 and size of each element is 2 bytes in the memory. Find the address of B[1700].

Solution:

The given values are: B = 1020, LB = 1300, W = 2, I = 1700

Address of A [ I ] = B + W * ( I – LB )

=1020+2*(1700-1300)

=1020+2*(400)

=1020+800

Address of A [ I ]=1820

Address Calculation in Double (Two) Dimensional Array:

While storing the elements of a 2-D array in memory, these are allocated contiguous memory locations. Therefore, a 2-D array must be linearized so as to enable their storage. There are two alternatives to achieve linearization: Row-Major and Column-Major.

Address of an element of any array say “A[ I ][ J ]” is calculated in two forms as given:
(1) Row Major System (2) Column Major System

Row Major System:

The address of a location in Row Major System is calculated using the following formula:

Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]

Column Major System:

The address of a location in Column Major System is calculated using the following formula:

Address of A [ I ][ J ] Column Major Wise = B + W * [( I – Lr ) + M * ( J – Lc )]

Where,
B = Base address
I = Row subscript of element whose address is to be found
J = Column subscript of element whose address is to be found
W = Storage Size of one element stored in the array (in byte)
Lr = Lower limit of row/start row index of matrix, if not given assume 0 (zero)
Lc = Lower limit of column/start column index of matrix, if not given assume 0 (zero)
M = Number of row of the given matrix
N = Number of column of the given matrix

Important : Usually number of rows and columns of a matrix are given ( like A[20][30] or A[40][60] ) but if it is given as A[Lr- – – – – Ur, Lc- – – – – Uc]. In this case number of rows and columns are calculated using the following methods:

Number of rows M(Ur–Lr)+1
Number of columns (N) = (Uc – Lc) + 1

And rest of the process will remain same as per requirement (Row Major Wise or Column Major Wise).

Examples:

Q 1. An array X [-15……….10, 15……………40] requires one byte of storage. If beginning location is 1500 determine the location of X [15][20].

Solution:

As you see here the number of rows and columns are not given in the question. So they are calculated as:

Number or rows say M = (Ur – Lr) + 1 = [10 – (- 15)] +1 = 26
Number or columns say N = (Uc – Lc) + 1 = [40 – 15)] +1 = 26

i) Column Major Wise Calculation of above equation

The given values are: B = 1500, W = 1 byte, I = 15, J = 20, Lr = -15, Lc = 15, M = 26

Address of A [ I ][ J ] = B + W * [ ( I – Lr ) + M * ( J – Lc ) ]

= 1500 + 1 * [(15 – (-15)) + 26 * (20 – 15)] = 1500 + 1 * [30 + 26 * 5] = 1500 + 1 * [160] = 1660 [Ans]

(ii) Row Major Wise Calculation of above equation

The given values are: B = 1500, W = 1 byte, I = 15, J = 20, Lr = -15, Lc = 15, N = 26

Address of A [ I ][ J ] = B + W * [ N * ( I – Lr ) + ( J – Lc ) ]

= 1500 + 1* [26 * (15 – (-15))) + (20 – 15)] = 1500 + 1 * [26 * 30 + 5] = 1500 + 1 * [780 + 5] = 1500 + 785
= 2285 [Ans]

 UNIT 3

Functions in C Programming with examples

 we will learn functions in C programming. A function is a block of statements that performs a specific task. Let’s say you are writing a C program and you need to perform a same task in that program more than once. In such case you have two options:

a) Use the same set of statements every time you want to perform the task
b) Create a function to perform that task, and just call it every time you need to perform that task.

Using option (b) is a good practice and a good programmer always uses functions while writing code in C.

Why we need functions in C

Functions are used because of following reasons –
a) To improve the readability of code.
b) Improves the reusability of the code, same function can be used in any program rather than writing the same code from scratch.
c) Debugging of the code would be easier if you use functions, as errors are easy to be traced.
d) Reduces the size of the code, duplicate set of statements are replaced by function calls.

Types of functions

1) Predefined standard library functions

Standard library functions are also known as built-in functions. Functions such as puts()gets()printf()scanf() etc are standard library functions. These functions are already defined in header files (files with .h extensions are called header files such as stdio.h), so we just call them whenever there is a need to use them.

For exampleprintf() function is defined in <stdio.h> header file so in order to use the printf() function, we need to include the <stdio.h> header file in our program using #include <stdio.h>.

2) User Defined functions

The functions that we create in a program are known as user defined functions or in other words you can say that a function created by user is known as user defined function.

Now we will learn how to create user defined functions and how to use them in C Programming

Function Declaration –

Intaddition(inta,int b);=addition(10,20);

A=&addition;

1. Return type –Int

2. Function name-addition

3. Parameters -(inta,int b)

 

Syntax of a function

return_type function_name (argument list)
{
Set of statements Block of code
}

return_type: Return type can be of any data type such as int, double, char, void, short etc. Don’t worry you will understand these terms better once you go through the examples below.

function_name: It can be anything, however it is advised to have a meaningful name for the functions so that it would be easy to understand the purpose of function just by seeing it’s name.

argument list: Argument list contains variables names along with their data types. These arguments are kind of inputs for the function. For example – A function which is used to add two integer variables, will be having two integer argument.

Block of code: Set of C statements, which will be executed whenever a call will be made to the function.

Function prototype

A function prototype is simply the declaration of a function that specifies function's name, parameters and return type. It doesn't contain function body.

A function prototype gives information to the compiler that the function may later be used in the program.

Syntax of function prototype

returnType functionName(type1 argument1, type2 argument2, ...);

In the above example, int addNumbers(int a, int b); is the function prototype which provides the following information to the compiler:

1.     name of the function is addNumbers()

2.     return type of the function is int

3.     two arguments of type int are passed to the function

The function prototype is not needed if the user-defined function is defined before the main() function.

Description of C programming function arguments


Here, as shown in the figure above arguments_value is used to send values to the called program.

Learn about user defined function in C programming.

Function arguments in c programming

Basically, there are two types of arguments:

  • Actual arguments
  • Formal arguments

The variables declared in the function prototype or definition are known as Formal arguments and the values that are passed to the called function from the main function are known as Actual arguments.

The actual arguments and formal arguments must match in number, type, and order.

Following are the two ways to pass arguments to the function:

  • Pass by value
  • Pass by reference

More Topics on Functions in C

1) Function – Call by value method – In the call by value method the actual arguments are copied to the formal arguments, hence any operation performed by function on arguments doesn’t affect actual parameters.

2) Function – Call by reference method – Unlike call by value, in this method, address of actual arguments (or parameters) is passed to the formal parameters, which means any operation performed on formal parameters affects the value of actual parameters.

Passing array to function in C programming with example

Just like variables, array can also be passed to a function as an argument . In this guide, we will learn how to pass the array to a function using call by value and call by reference methods.

To understand this guide, you should have the knowledge of following C Programming topics:

1.    C – Array

2.    Function call by value in C

3.    Function call by reference in C

Passing array to function using call by value method

As we already know in this type of function call, the actual parameter is copied to the formal parameters.

#include<stdio.h>
void disp(char ch)
{
   printf("%c ", ch);
}
int main()
{
char arr[]={'a','b','c','d','e','f','g','h','i','j'};
for(int x=0; x<10; x++)
{
/* I’m passing each element one by one using subscript*/
       disp (arr[x]);
}
 
return0;
}

Output:

a b c d e f g h i j

 

 

Passing array to function using call by reference

When we pass the address of an array while calling a function then this is called function call by reference. When we pass an address as an argument, the function declaration should have a pointer as a parameter to receive the passed address.

#include<stdio.h>
void disp(int*num)
{
    printf("%d ",*num);
}
 
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9,0};
for(int i=0; i<10; i++)
{
/* Passing addresses of array elements*/
         disp (&arr[i]);
}
 
return0;
}

Output:

1234567890

 

How to pass an entire array to a function as an argument?

In the above example, we have passed the address of each array element one by one using a for loop in C. However you can also pass an entire array to a function like this:

Note: The array name itself is the address of first element of that array. For example if array name is arr then you can say that arr is equivalent to the &arr[0].

#include<stdio.h>
void myfuncn(int*var1,int var2)
{
          /* The pointer var1 is pointing to the first element of
           * the array and the var2 is the size of the array. In the
           * loop we are incrementing pointer so that it points to
           * the next element of the array on each increment.
           *
           */
for(int x=0; x<var2; x++)
{
        printf("Value of var_arr[%d] is: %d \n", x,*var1);
/*increment pointer for next element fetch*/
        var1++;
}
}
 
int main()
{
int var_arr[]={11,22,33,44,55,66,77};
     myfuncn(var_arr,7);
return0;
}

Output:

Value of var_arr[0]is:11
Value of var_arr[1]is:22
Value of var_arr[2]is:33
Value of var_arr[3]is:44
Value of var_arr[4]is:55
Value of var_arr[5]is:66
Value of var_arr[6]is:77

 NEXT UNIT 

POINTERS
Presented by
Er. Jasleen Kaur
Assistant Professor
Applied Science(CSE)
Chandigarh University
Gharuan (Mohali).

Pointer
A variable that holds a memory address.
This address is the location of another object
in the memory.
Pointer as an address indicates where to find
an object.
Not all pointers actually contain an address
example NULL pointer.
Value of NULL pointer is 0.
10/19/2015
Pointer can have three kinds of content in it
1) The address of an object, which can be
dereferenced.
2) A NULL pointer.
3) Invalid content, which does not point to an
object.
(If p does not hold a valid value, it can crash the
program)
If p is a pointer to integer, then
Int *p
It is possible in some environments to have
multiple pointer values with different
representations that point to same location in
memory.
But make sure if the memory is deleted using
delete or if original variable goes out of scope.

Declaring pointer
Data-type *name;
* is a unary operator, also called as indirection
operator.
Data-type is the type of object which the
pointer is pointing.
Any type of pointer can point to anywhere in
the memory.
* is used to declare a pointer and also to
dereference a pointer.

When you write int *,
compiler assumes that any address that it
holds points to an integer type.
m= &count;
it means memory address of count variable is
stored into m.
& is unary operator that returns the memory
address.
i.e. & (orally called as ampersand) is returning
the address.
so it means m receives the address of count.
Suppose, count uses memory
Address 2000 to store its value 100.
so, m=&count means m has 2000
address.
q= *m
it returns the value at address m.
value at address 2000 is 100.
so, q will return value 100.
i.e. q receives the value at address m.
2000

count=100


Address-of operator(&)
It is used to reference the memory address of
a variable.
When we declare a variable, 3 things happen
Computer memory is set aside for variable
Variable name is linked to that location in memory
Value of variable is placed into the memory that
was set aside.

Int *ptr;
declaring variable ptr which holds the value
at address of int type
int val =1;
assigning int the literal value of 1
ptr=&val;
dereference and get value at address stored in
ptr
int deref =*ptr
printf(“%d\n”, deref);
Output will be 1

Pointer Conversions
One type of pointer can be converted to
another type of pointer.
int main() {
double x=100.1, y;
int *p;
p= (int *) &x; //explicit type conversion
y= *p;
}

Generic Pointer
void * pointer is called as generic pointer.
Can’t convert void *pointer to another pointer
and vice-versa.
void *pointer can be assigned to any other
type of pointer.
void * is used to specify a pointer whose base
type is unknown.
It is capable of receiving any type of pointer
argument without reporting any type of
mismatch.

Pointer Arithmetic
There are only two arithmetic operations that
can be used on pointers
Addition
Subtraction
To understand this concept, lets p1 be an
integer pointer with value 2000 address.
int is of 2 bytes
After expression p1++;
P1 contains address 2002 not 2001.
Each time p1 is incremented, it will point to
next integer.
The same is true for decrement.
for p1--;
Causes value of p1 to be 1998.
Each time a pointer is incremented, it points
to the memory location of the next element of
its base type.
If decremented, then it points to previous
element location.
P1=p1+12; makes p1 points to 12th element of
p1 type.

Arithmetic Rules
You cannot multiply or divide pointers.
You cannot add or subtract two pointers.
You cannot apply bitwise operators to them.
You cannot add or subtract type float or
double to or from pointers.

Pointer Comparison
You can compare two pointers in a relational
expression, example:
if(p<q)
printf(“p points to lower memory than q \n”);
Pointer comparison are useful only when two
pointers point to a common object such as an
array.

Benefits of pointer
Pointers are used in situations when passing actual values is
difficult or not desired.
To return more than one value from a function.
They increase the execution speed.
The pointer are more efficient in handling the data types .
Pointers reduce the length and complexity of a program.
The use of a pointer array to character string results in
saving of data.
To allocate memory and access it( Dynamic memory
Allocation).
Implementing linked lists, trees graphs and many other data
structure.

How to get address of a function
/*A program to get address of a function */
#include<stdio.h>
void main()
{
void show(); /* usual way of invoking a function */
printf(“ The address of show function is=%u”, show);
}
void show()
{
printf(“ \welcome to HPES!!”)
}

Uses of pointer to function
Pointers are certainly awkward and off-putting and thus
this feature of pointer is used for invoking a function
There are several possible uses :
(a) In writing memory
resident program.
(b) In writing viruses, or vaccines to
remove the viruses.
(c) In developing COM/DCOM component
(d) In VC++ programming to connect events to
function calls.

10/19/2015
10/19/2015
10/19/2015
10/19/2015
10/19/2015
10/19/2015
10/19/2015

NEXT UNIT

Structure & Union
Content
Introduction
Structure Definition
Accessing Structure Member
Array of Structure
Pointer to Structure
Function and Structure
Union
Introduction
User defined data type
Collection of heterogeneous data
Referred by a common name
A function can return a structure
Definition
Collection of logically related data with same
or different data-type, the logically related
data are grouped together in a common
name.
Structure Tag
Data Member or Fields
Syntax
struct tag_name
{
data-type Field1;
data-type Field2;
………
};

Example
struct book
{
char name[20];
char author[10];
int pages;
float price;
} ;

Declaration of Variable
struct student
{
int roll_no;
char name[20];
float marks;
}
s1,*s2;
Using Structure Tag
struct struct_tag variable-list;
struct student s1,*s2;
Variable can be declared inside(local) or
outside(global) of main function

Memory Allocation
struct student s1 = {1,”Rupesh”,67.67};
N=sizeof(s1);
N ????
s1.roll_no s1.name s1.marks

1 R u p e s h \
0
G V 67.67

6502 6504 6024 6025

#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
};

int main()
{
struct student s; // Structure Variable
printf("Enter information of students:\n\n");
printf("Enter name: "); scanf("%s",s.name);
printf("Enter roll number: "); scanf("%d",&s.roll);
printf("Enter marks: "); scanf("%f",&s.marks);

printf("\nDisplaying Information\n");
printf("Name: %s\n",s.name);
printf("Roll: %d\n",s.roll);
printf("Marks: %.2f\n",s.marks);
return 0;
}

typedef
It is used to give a new symbolic name (alias)
to the existing entity of program.
typedef existing name alias_name;
typedef int unit;
unit a,b;
typedef with structure
alias_name variable list;
typedef struct tag_name
{
data-type Field1;
data-type Field2;
………
} alias_name;

typedef with structure
typedef struct book
{
char name[20];
char author[10];
int pages;
float price;
} book_bank;
book_bank b1,b2;
Accessing Structure Member
Member Access Operator
Dot (.) operator
s1.name
Structure Pointer Operator
Arrow (->) Operator
s2->name
Nested Structure
struct date
{
int day, mon, year;
};
Struct emp
{
char name[20];
struct date birthday;
float salary;
};

Nested Structure
Struct emp
{
char name[20];
struct date
{
int day, mon, year;
} birthday;
float salary;
};

Nested Structure
struct emp e1 = {“Ratan”,{28,12,1937},68.4};
printf(“name =%s”,e1.name);
Output : Ratan
Printf(“Month of Birth=%d”,e1.birthday.mon);
Output ??
Nested Structure
struct emp e1 = {“Ratan”,{28,12,1937},68.4};
printf(“name =%s”,e1.name);
Output : Ratan
Printf(“Month of Birth=%d”,e1.birthday.mon);
Output : 12
Array of Structure
struct student
{
int roll_no;
char name[20];
float marks;
}
s[100];

#include <stdio.h>
struct employee
{
int emp_id;
char name[20];
float salary;
int dept_no;
int age;
};

Int main ( )
{
struct employee e[50];
int I,n;
printf(Enter No of Employee );
Scanf(“%d”,&n);

for (i=0; i<n; i++)
{
printf (“Enter employee id, name salary,
departement id and age of employee”);
scanf (“%d”,&e[i].emp_id);
scanf (“%s”,e[i].name);
scanf (“%f”,&e[i].salary);
scanf (“%d”,&e[i].dept_no);
scanf (“%d”,&e[i].age);
}

for (i=0; i<n; i++)
{
printf (“Employee id : %d”, e[i].emp_id);
printf (“Name : %s”,e[i].name);
printf (“Salary : %f”, e[i].salary);
printf (“Department ID: %d”, e[i].dept_no);
printf (“Age : %d”, e[i].age);
}
return 0;
}

Structure in Function
Parameter Passing
Return Value
Passing Parameter
#include <stdio.h>
struct employee
{
int emp_id;
char name[20];
float salary;
};

Int main ( )
{
struct employee e;
printf (“Enter the employee id of employee”);
scanf(“%d”,&e.emp_id);
printf (“Enter the name of employee”);
scanf(“%s”,e.name);
printf (“Enter the salary of employee”);
scanf(“%f”,&e.salary);
printdata (struct employee e); // f
n Call
return 0;
}

void printdata( struct employee emp)
{
printf (“\nThe employee id of employee is : %d”,emp.emp_id);
printf (“\nThe name of employee is : %s”, emp.name);
printf (“\nThe salary of employee is : %f”, emp.salary);
}
Return Value
#include <stdio.h>
struct employee
{
int emp_id;
char name[20];
float salary;
};

void main ( )
{
struct employee emp;
emp=getdata(); // fn Call
printf (“\nThe employee id is:%d”,emp.emp_id);
printf (“\nThe name is : %s”, emp.name);
printf (“\nThe salary is : %f”, emp.salary);
return 0;
}

struct employee getdata( )
{
struct employee e;
printf (“Enter the employee id of employee”);
scanf(“%d”,&e.emp_id);
printf (“Enter the name of employee”);
scanf(“%s”,e.name);
printf (“Enter the salary of employee”);
scanf(“%f”,&e.salary);
return(e);
}

Union
Definition – Same as structure
Syntax – Same as structure
Difference in structure and union
Keyword – union
Memory allocation
Variable Storage
Syntax
union tag_name
{
data-type Field1;
data-type Field2;
………
};

Memory Allocation
union student
{
int roll_no;
char name[20];
float marks;
}
s1,*s2;
sizeof(s1)= ????

Memory Allocation
union student
{
int roll_no;
char name[20];
float marks;
}
s1,*s2;
sizeof(s1)= 20 byte (Field with Max sixe: Name)



Comments

Popular posts from this blog

BCA 2ND SEM DBMS NOTES

BCA IST SEM FOC MCQ BATCH 2023-24