Image | Description |
---|---|
AD and CE are the shortest arcs, with length 5, and AD has been arbitrarily chosen, so it is highlighted. | |
CE is now the shortest arc that does not form a cycle, with length 5, so it is highlighted as the second arc. | |
The next arc, DF with length 6, is highlighted using much the same method. | |
The next-shortest arcs are AB and BE, both with length 7. AB is chosen arbitrarily, and is highlighted. The arc BD has been highlighted in red, because there already exists a path (in green) between B and D, so it would form a cycle (ABD) if it were chosen. | |
The process continues to highlight the next-smallest arc, BE with length 7. Many more arcs are highlighted in red at this stage: BC because it would form the loop BCE, DE because it would form the loop DEBA, and FE because it would form FEBAD. | |
Finally, the process finishes with the arc EG of length 9, and the minimum spanning tree is found. |
404
Page not found.
Kruskal’s algorithm : Reference
Bitwise Left Shift (<<) Operator in C Programming
Bitwise Left Shift Operator in C
- It is denoted by <<
- Bit Pattern of the data can be shifted by specified number of Positions to Left
- When Data is Shifted Left , trailing zero’s are filled with zero.
- Left shift Operator is Binary Operator [Bi - two]
- Binary means , Operator that require two arguments
Quick Overview of Left Shift Operator
Original Number A | 0000 0000 0011 1100 |
Left Shift | 0000 0000 1111 0000 |
Trailing Zero’s | Replaced by 0 (Shown in RED) |
Direction of Movement of Data | <<<<<=======Left |
Syntax : Bitwise Left Shift Operator
[variable]<<[number of places]
Live Example : Bitwise Operator [Left Shift Operator]
#include<stdio.h> int main() { int a = 60; printf("\nNumber is Shifted By 1 Bit : %d",a << 1); printf("\nNumber is Shifted By 2 Bits : %d",a << 2); printf("\nNumber is Shifted By 3 Bits : %d",a << 3); return(0); }
Output :
Number is Shifted By 1 Bit : 120 Number is Shifted By 2 Bits : 240 Number is Shifted By 3 Bits : 480
Explanation of Left Shift Binary Operator :
We know the binary representation of the 60 is as below -
0000 0000 0011 1100
Now after shifting all the bits to left towards MSB we will get following bit pattern -
0000 0000 0011 1100 = 60 << 1 ------------------- 0000 0000 0111 1000 = 120
Observations and Conclusion :
Shfting Binary 1 to Left By ‘X’ Bits | Decimal Value | Converted Value |
---|---|---|
0 Bit | 2^0 | 1 |
1 Bit | 2^1 | 2 |
2 Bits | 2^2 | 4 |
3 Bits | 2^3 | 8 |
4 Bits | 2^4 | 16 |
5 Bits | 2^5 | 32 |
6 Bits | 2^6 | 64 |
7 Bits | 2^7 | 128 |
8 Bits | 2^8 | 256 |
What is meaning of (++*ptr) in Pointer ?
In the previous topic we have studied Precedence of Value at and Address Operator of Pointer. In this chapter we will be looking more advance form of pointer. We are looking one step forward to learn how (++*ptr) works ?
Meaning of (++*ptr) in C Programming :
Consider the Following Example :
int num = 20 , *ptr ; ptr = # printf("%d",++*ptr);
Explanation :
- ‘++’ and ‘*’ both have Equal Precedence
- Associativity is from Right to Left ( Expression evaluated from R->L)
- Both are Unary (Operates on single operand )
- So ‘ * ‘ is Performed First then ‘ ++ ‘
Re-Commanded Reference Article : Operator Precedence Table
Visual Understanding :
Calculation of Answer :
++*ptr = ++ ( *ptr ) = ++ ( *3058 ) = ++ ( 20 ) = 21
- Suppose ptr variable stores address 3058.
- * Operator will de-reference pointer to get value stored at that address. (i.e 20)
- Pre-increment on 20 will perform increment first then assignment
Live Example : Meaning of ++*ptr Pointer
#include<stdio.h> int main() { int n = 20 , *ptr ; ptr = &n; printf("%d",++*ptr); return(0); }
Output :
21
In the next chapter we will be learning the meaning of (*++ptr) Pointer.
What is the size of Pointer variable in C ?
In the previous chapter, we have learnt about the memory organization of the pointer variable. In this chapter we are learning to compute or find the size of pointer variable.
What is the size of Pointer variable in C ?
How to calculate size of Pointer ?
Consider the following memory map before declaring the variable.In the memory comprise of blocks of 1 byte.
Whenever we declare any variable then random block of memory is chosen and value will be stored at that memory location.
Similarly whenever we declare any pointer variable then random block of memory will be used as pointer variable which can hold the address of another variable.
Calculating Size of Pointer : Tips
- Pointer stores the address of the Variable.
- Size of Pointer Variable can be evaluated by using sizeof operator
- Address of variable is considered as integer value.
- For Borland C/C++ Compiler, for storing integer value 2 bytes are required.
- Thus Pointer variable requires 2 bytes of memory.
Size of Integer Pointer Variable in Different IDE :
Compiler | Size of Integer | Size of Integer Pointer |
---|---|---|
Borland C/C++ | 2 Bytes | 2 Bytes |
Turbo C/C++ | 2 Bytes | 2 Bytes |
Visual C++ | 4 Bytes | 4 bytes |
Size of the Pointer :
#include<stdio.h> int main() { int num = 15; int *ptr = NULL; ptr = # printf("Size of Pointer : %d Bytes",sizeof(ptr)); return 0; }
Output :
Size of Pointer : 2 Bytes
Some of the Useful Programs :
Application of Array in C Programming
Application Of Array :
Array is used for different verities of applications. Array is used to store the data or values of same data type. Below are the some of the applications of array -
A. Stores Elements of Same Data Type
Array is used to store the number of elements belonging to same data type.
int arr[30];
Above array is used to store the integer numbers in an array.
arr[0] = 10; arr[1] = 20; arr[2] = 30; arr[3] = 40; arr[4] = 50;
Similarly if we declare the character array then it can hold only character. So in short character array can store character variables while floating array stores only floating numbers.
B. Array Used for Maintaining multiple variable names using single name
Suppose we need to store 5 roll numbers of students then without declaration of array we need to declare following -
int roll1,roll2,roll3,roll4,roll5;
- Now in order to get roll number of first student we need to access roll1.
- Guess if we need to store roll numbers of 100 students then what will be the procedure.
- Maintaining all the variables and remembering all these things is very difficult.
Consider the Array :
int roll[5];
So we are using array which can store multiple values and we have to remember just single variable name.
C. Array Can be Used for Sorting Elements
We can store elements to be sorted in an array and then by using different sorting technique we can sort the elements.
Different Sorting Techniques are :
- Bubble Sort
- Insertion Sort
- Selection Sort
- Bucket Sort
D. Array Can Perform Matrix Operation
Matrix operations can be performed using the array.We can use 2-D array to store the matrix.
E. Array Can be Used in CPU Scheduling
CPU Scheduling is generally managed by Queue. Queue can be managed and implemented using the array. Array may be allocated dynamically i.e at run time. [Animation will Explain more about Round Robin Scheduling Algorithm | Video Animation]
F. Array Can be Used in Recursive Function
When the function calls another function or the same function again then the current values are stores onto the stack and those values will be retrieve when control comes back. This is similar operation like stack.
if-else-if Statement OR else if Ladder : Tutorial on If
if-else-if Statement OR else if Ladder :
Suppose we need to specify multiple conditions then we need to use multiple if statements like this -
void main ( ) { int num = 10 ; if ( num > 0 ) printf ("\n Number is Positive"); if ( num < 0 ) printf ("\n Number is Negative"); if ( num == 0 ) printf ("\n Number is Zero"); }
which is not a right or feasible way to write program. Instead of this above syntax we use if-else-if statement.
Consider the Following Program -
void main ( ) { int num = 10 ; if ( num > 0 ) printf ("\n Number is Positive"); else if ( num < 0 ) printf ("\n Number is Negative"); else printf ("\n Number is Zero"); }
Explanation :
In the above program firstly condition is tested i.e number is checked with zero. If it is greater than zero then only first if statement will be executed and after the execution of if statement control will be outside the complete if-else statement.
else if ( num < 0 ) printf ("\n Number is Negative");
Suppose in first if condition is false then the second condition will be tested i.e if number is not positive then and then only it is tested for the negative.
else printf ("\n Number is Zero");
and if number is neither positive nor negative then it will be considered as zero.
Which is faster and feasible way for Writing If ?
Point | Example 1 | Example 2 |
---|---|---|
No of If Statements | 3 | 2 |
No of times Condition Tested (Positive No.) | 3 | 1 |
No of times Condition Tested (Negative No.) | 3 | 2 |
No of times Condition Tested (Zero No.) | 3 | 2 |
Flowchart for If-Else Ladder :
Difference between Declaration and Definition in C Programming
Some Examples of Declaration :
Declaration of Function :
Whenever we write function after the main function, compiler will through the error since it does not have any idea about the function at the time of calling function. If we provide prototype declaration of function then we compiler will not look for the definition.
int sum(int,int); main() { int res = sum(10,20); } int sum(int n1,int n2) { return(n1+n2); }
In the above example , first line is called as function declaration.
int sum(int,int);
Declaring Variable
Whenever we write declaration statement then memory will not be allocated for the variable. Variable declaration will randomly specify the memory location.
int ivar; float fvar;
Variable Declaration Vs Definition Differentiation Parameters
A. Space Reservation :
- Whenever we declare a variable then space will not be reserved for the variable.
- Whenever we declare a variable then compiler will not look for other details such as definition of the variable.
- Declaration is handy way to write code in which actual memory is not allocated.
struct book { int pages; float price; char *bname; };
In the above declaration memory is not allocated. Whenever we define a variable then memory will be allocated for the variable.
struct book b1;
B. What it does ?
- Declaration will identify the data type of the identifier.
- Definition of the variable will assign some value to it.
C. Re-Declaration Vs Re-Definition
In Both the cases we will get compile error. Re-declaration and Re-definition is illegal in C programming language.
Re-Declaring the Variable in Same Scope :
main() { int num1; int num1; }
&
struct book { int pages; float price; char *bname; }; struct book { int pages; float price; char *bname; };
above statement will cause error.
Re-Defining the Variable :
int sum(int n1,int n2) { return(n1+n2); } int sum(int n1,int n2) { return(n1+n2); }
above definition will cause compile error.
Difference between Declaration and Definition
No | Declaration | Definition |
---|---|---|
1 | Space is Not Reserved | In Definition Space is Reserved |
2 | Identifies Data Type | Some Initial Value is Assigned |
3 | Re-Declaration is Error | Re-Definition is Error |
What is Data Type in C Programming ?
What is Data Type in C Programming ?
- A Data Type is a Type of Data.
- Data Type is a Data Storage Format that can contain a Specific Type or Range of Values.
- When computer programs store data in variables, each variable must be assigned a specific data type.
Some of the Data Types Supported by C :
Data Type | keyword | Description |
---|---|---|
Integer Data Type | int | Stores the Integer Value |
Float Data Type | float | Stores the Floating Point Value |
Character Data Type | char | Stores the Single Character Value |
Long Data Type | long | Stores the Long range Integer Value |
Double Data Type | double | Stores the long range Floating Value |
Explanation :
- Whenever we declare variable in Computer’s memory, Computer must know the type of the data to be stored inside the memory.
- If we need to store the single character then the size of memory occupied will be different than storing the single integer number.
- The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can manage in C.
- A byte can store a relatively small amount of data one single character or a small integer (generally an integer between 0 and 255).
Re-commanded Readings : Data Type
Size Required to Store Variable of Different Data Types
Data Type | Borland C/C++ Compiler | Visual C++ |
---|---|---|
Integer | 2 Bytes | 4 bytes |
Float | 4 Bytes | 4 Bytes |
Character | 1 Byte | 1 Byte |
Long | 4 Byte | 8 Byte |
1-D Array - Compile Time Initializing in C Programming
Different Methods of 1-D Array - Compile Time Initializing
Whenever we declare an array we can initialize array directly at compile time. Initialization of an array is called as compiler time initialization if and only if we assign certain set of values to array element before executing program. i.e at Compilation Time.
Different Ways Of Array Initialization :
- Size is Specified Directly
- Size is Specified Indirectly
A. Method 1 : Array Size Specified Directly
In this method , we try to specify the Array Size directly.
int num[5] = {2,8,7,6,0};
In the above example we have specified the size of array as 5 directly in the initialization statement.Compiler will assign the set of values to particular element of the array.
num[0] = 2 num[1] = 8 num[2] = 7 num[3] = 6 num[4] = 0
As at the time of compilation all the elements are at Specified Position So This Initialization Scheme is Called as “Compile Time Initialization“.
Graphical Representation :
B. Method 2 : Size Specified Indirectly
In this scheme of compile time Initialization, We does not provide size to an array but instead we provide set of values to the array.
int num[] = {2,8,7,6,0};
Explanation :
- Compiler Counts the Number Of Elements Written Inside Pair of Braces and Determines the Size of An Array.
- After counting the number of elements inside the braces, The size of array is considered as 5 during complete execution.
- This type of Initialization Scheme is also Called as “Compile Time Initialization“
Live Example :
#include <stdio.h> int main() { int num[] = {2,8,7,6,0}; int i; for(i=0;i<5;i++) { printf("\nArray Element num[%d] : %d",i+1,num[i]); } return 0; }
Output :
Array Element num[1] : 2 Array Element num[2] : 8 Array Element num[3] : 7 Array Element num[4] : 6 Array Element num[5] : 0
Logical Operator in C Programming
Logical Operator in C Programming
Whenever we use if statement then we can use relational operator which tells us the result of the comparison, so if we want to compare more than one conditions then we need to use logical operators. Suppose we need to execute certain block of code if and only if two conditions are satisfied then we can use Logical Operator in C Programming.
Operator | Name of the Operator |
---|---|
&& | And Operator |
|| | Or Operator |
! | Not Operator |
Let us look at all logical operators with example -
#include<stdio.h> int main() { int num1 = 30; int num2 = 40; if(num1>=40 || num2>=40) printf("Or If Block Gets Executed"); if(num1>=20 && num2>=20) printf("And If Block Gets Executed"); if( !(num1>=40)) printf("Not If Block Gets Executed"); return(0); }
Output :
Or If Block Gets Executed And If Block Gets Executed Not If Block Gets Executed
Explanation of the Program :
Suppose OR Operator is used inside if statement then if part will be executed if any of the condition evaluated to be true.
if(num1>=40 || num2>=40)
In the above if statement first condition is false and second condition is true , so if part will be executed.
if(num1>=20 && num2>=20)
In the above if statement both the conditions are true so if statement will be executed, AND Operator will look for truthness of first condition, If it founds the true condition then it will look for 2nd condition. If 2nd Condition founds to be true then it will look for next condition.
Logical Operator Chart :
Operator Applied Between | Condition 1 | Condition 2 | Final Output |
---|---|---|---|
AND | True | True | True |
True | False | False | |
False | True | False | |
False | False | False | |
OR | True | True | True |
True | False | True | |
False | True | True | |
False | False | False | |
NOT | True | - | False |
False | - | True |
Relational Operator in C Programming Language
Relational Operator in C
In C Programming we can compare the value stored between two variables and depending on the result we can follow different blocks using Relational Operator in C. In C we have different relational operators such as -
Operator | Meaning |
---|---|
> | Greater than |
>= | Greater than or equal to |
<= | Less than or equal to |
< | Less than |
Live Example of Relational Operator :
#include<stdio.h> int main() { int num1 = 30; int num2 = 40; printf("Value of %d > %d is %d",num1,num2,num1> num2); printf("Value of %d >=%d is %d",num1,num2,num1>=num2); printf("Value of %d <=%d is %d",num1,num2,num1<=num2); printf("Value of %d < %d is %d",num1,num2,num1< num2); return(0); }
Output :
Value of 30 > 40 is 0 Value of 30 >=40 is 0 Value of 30 <=40 is 1 Value of 30 < 40 is 1
We all know that C does not support boolean data type so in order to compare the equality we use comparison operator or equality operator in C Programming.
Operator | Meaning |
---|---|
== | Is equal to |
!= | Is not equal to |
Live Example Of Equality Operator in C
#include<stdio.h> int main() { int num1 = 30; int num2 = 40; printf("Value of %d ==%d is %d",num1,num2,num1==num2); printf("Value of %d !=%d is %d",num1,num2,num1!=num2); return(0); }
Output :
Value of 30 ==40 is 0 Value of 30 !=40 is 1
Variable in C Programming
What is Variable in C Programming
Variable in C Programming is also called as container to store the data. Variable name may have different data types to identify the type of value stored. Suppose we declare variable of type integer then it can store only integer values.Variable is considered as one of the building block of C Programming which is also called as identifier.
Consider real time example , suppose we need to store water then we can store water in glass if quantity of water is small and Bucket is the quantity of water is large. And big can to store water having quantity larger than bucket similarly Variable (i.e Value container) may have different size for storing different verities of values.
Must Read : Fundamental Attributes of Variable
What is Variable in C Programming?
- Initially 5 is Stored in memory location and name x is given to it
- After We are assigning the new value (3) to the same memory location
- This would Overwrite the earlier value 5 since memory location can hold only one value at a time
- Since the location ‘x’can hold Different values at different time so it is refered as ‘Variable‘
- In short Variable is name given to Specific memory location or Group.
Consider following Scenario -
Step 1 : Memory Before Variable Declaration
Initially before declaring variable ,We have Only memory.
Memory is block of bytes.
Each byte is filled with random or garbage data.
Step 2 : Declaring Variable in C Programming
- Now we have declared a variable. (in this case we have declared character variable)
- Compiler Checks data type . Depending on data type it will allocate appropriate bytes of memory. (in this case Compile will allocate 1 byte because we have declared Character data type)
- It’s only declaration so , garbage value inside that address remains the same.
Step 3 : Initialize Variable in C Programming
- We have Initialize character variable now.
- After initializing value inside that memory block gets overwritten.
Conclusion :
- Variable Name always holds a single Value.
- Variable Name is user defined name given to Memory Address.
- During Second Run , Address of Variable may change.
- During second Run , Value set inside variable during current will be considered as garbage..
Increment Operator in C Programming [Post Increment / Pre Increment]
In C Programming , Unary operators are having higher priority than the other operators. Unary Operators are executed before the execution of the other operators. Increment and Decrement are the examples of the Unary operator in C.
Increment Operator in C Programming :
- Increment operator is used to increment the current value of variable by adding integer 1.
- Increment operator can be applied to only variables.
- Increment operator is denoted by ++.
Different Types of Increment Operation :
In C Programming we have two types of increment operator i.e Pre-Increment and Post-Increment Operator.
A. Pre Increment Operator in C Programming :
Pre-increment operator is used to increment the value of variable before using in the expression. In the Pre-Increment value is first incremented and then used inside the expression.
b = ++y;
In this example suppose the value of variable ‘y’ is 5 then value of variable ‘b’ will be 6 because the value of ‘y’ gets modified before using it in a expression.
B. Post Increment Operator in C Programming :
Post-increment operator is used to increment the value of variable as soon as after executing expression completely in which post increment is used. In the Post-Increment value is first used in a expression and then incremented.
b = x++;
In this example suppose the value of variable ‘x’ is 5 then value of variable ‘b’ will be 5 because old value of ‘x’ is used.
Live Program : C Program to Perform Increment Operation in C Programming
#include<stdio.h> void main() { int a,b,x=10,y=10; a = x++; b = ++y; printf("Value of a : %d",a); printf("Value of b : %d",b); }
Output :
Value of a : 10 Value of b : 11
Tip #1 : Increment Operator should not be used on Constants
We cannot use increment operator on the constant values because increment operator operates on only variables. It increments the value of the variable by 1 and stores the incremented value back to the variable,
b = ++5;
Or
b = 5++;
Summary : Expression Solving using Pre/Post Increment
Decrement Operator in C Programming [Post Decrement / Pre Decrement]
We have seen increment operator in C Programming which increments the value of the variable by 1. Similarly C Supports one more unary operator i.e decrement operator which behaves like increment operator but only difference is that it decreases the value of variable by 1.
Decrement Operator in C Programming :
- Decrement operator is used to decrease the current value of variable by subtracting integer 1.
- Like Increment operator, decrement operator can be applied to only variables.
- Decrement operator is denoted by -.
Different Types of Decrement Operation :
When decrement operator used in C Programming then it can be used as pre-decrement or post-decrement operator.
A. Pre Decrement Operator in C Programming :
Pre-decrement operator is used to decrement the value of variable before using in the expression. In the Pre-decrement value is first decremented and then used inside the expression.
b = --var;
Suppose the value of variable var is 10 then we can say that value of variable ‘var’ is firstly decremented then updated value will be used in the expression.
B. Post Decrement Operator in C Programming :
Post-decrement operator is used to decrement the value of variable immediatly after executing expression completely in which post decrement is used. In the Post-decrement old value is first used in a expression and then old value will be decrement by 1.
b = var--;
Value of variable ‘var’ is 5. Same value will be used in expression and after execution of expression new value will be 4.
Live Program : C Program to Perform Decrement Operation in C Programming
#include<stdio.h> void main() { int a,b,x=10,y=10; a = x--; b = --y; printf("Value of a : %d",a); printf("Value of b : %d",b); }
Output :
Value of a : 10 Value of b : 9
Tip #1 : Decrement Operator should not be used on Constants
We cannot use decrement operator in the following case -
b = --5;
Or
b = 5--;
Summary : Expression Solving using Pre/Post Increment
Rules for Constructing Integer Number Constant
Rules for constructing Integer constant
No | Rule | Integer |
---|---|---|
1 | Decimal | Point Not Allowed |
2 | Sign | Positive or Negative |
3 | Default Sign | Positive |
4 | No of Digits | At least 1 |
5 | Min Value | -32768 |
6 | Max Value | +32767 |
Some important Tips :
- The range of the integer constant depends on the compiler. The above mentioned range is for 16-bit compiler.
- Integer Value does not have decimal point.
- Integer Value may be positive or negative. even 0 is also considered as Integer.
- Integer Constant Value is assigned to integer variable.
- Arithmetic Operations can be performed on Integer Value such as addition,subtraction,multiplication and division.
- 2 bytes in memory is allocated for Integer Value
Examples of integer constants :
- Whole Numbers
- Real Numbers i.e 10,-10,0
What is Constant in C Programming ?
What is Constant ?
Constant in C means the content whose value does not change at the time of execution of a program.
Definition :
Explanation :
- Initially 5 is Stored in memory location and name x is given to it
- After We are assigning the new value (3) to the same memory location
- This would Overwrite the earlier value 5 since memory location can hold only one value at a time
- The value of ’3′,’5′ do not change ,so they are constants
- In Short the ‘Values of Constant Does not Change‘.
Different Types of C Constants :
Constant | Type of Value Stored |
---|---|
Integer Constant | Constant which stores integer value |
Floating Constant | Constant which stores float value |
Character Constant | Constant which stores character value |
String Constant | Constant which stores string value |
How to Declare Constant in C :
We can declare constant using const variable. Suppose we need to declare constant of type integer then we can have following two ways to declare it -
const int a = 1; int const a = 1;
above declaration is bit confusing but no need to worry, We can start reading these variables from right to left. i.e
Declaration | Explanation |
---|---|
const int a = 1; | read as “a is an integer which is constant” |
int const a = 1; | read as “a is a constant integer” |
What does Storage Class of Variable Determines ?
Storage class of variable Determines following things -
- Where the variable is stored
- Scope of Variable
- Default initial value
- Lifetime of variable
A. Where the variable is stored :
Storage Class determines the location of variable , Where it is declared. Variables declared with auto storage classes are declared inside main memory whereas variables declared with keyword register are stored inside the CPU Register.
B. Scope of Variable
Scope of Variable tells compile about the visibility of Variable in the block. Variable may have Block Scope , Local Scope and External Scope. Wiki has defined variable scope as -
C. Default Initial Value of the Variable
Whenever we declare a Variable in C, garbage value is assigned to the variable. Garbage Value may be considered as initial value of the variable. C Programming have different storage classes which has different initial values such as Global Variable have Initial Value as 0 while the Local auto variable have default initial garbage value.
D. Lifetime of variable
Lifetime of the = Time Of - Time of Variable variable Declaration Destruction
Suppose we have declared variable inside main function then variable will be destroyed only when the control comes out of the main .i.e end of the program.
Register Storage Class in C Programming
Register Storage Class :
- Register is used to define Local Variable.
- Local Variable stored in Register instead of RAM.
- As Variable is stored in Register so Maximum size of variable = Maximum Size of Register
- Unary Operator [&] is not associated with it because Value is not stored in RAM instead it is stored in Register.
- This is generally used for faster access.
- Common use is “Counter“
Syntax :
{ register int count; }
Live Example : Register Storage Classes
#include<stdio.h> int main() { int num1,num2; register int sum; printf("\nEnter the Number 1 : "); scanf("%d",&num1); printf("\nEnter the Number 2 : "); scanf("%d",&num2); sum = num1 + num2; printf("\nSum of Numbers : %d",sum); return(0); }
Explanation of Above Code :
Refer below animation which depicts the register storage classes -
Reference : [cprogrammingexpert]
- In the above program we have declared two variables num1,num2. These two variables are stored in RAM.
- Another variable is declared which is stored in register variable.Register variables are stored in the register of the microprocessor.Thus memory access will be faster than other variables.
- If we try to declare more register variables then it can treat variables as Auto storage variables as memory of microprocessor is fixed and limited.
Summary of Register Storage Class in C :
Keyword | register |
---|---|
Storage Location | CPU Register |
Initial Value | Garbage |
Life | Local to the block in which variable is declared. |
Scope | Local to the block. |
Why we need Register Variable :
- Whenever we declare any variable inside C Program then memory will be randomly allocated at particular memory location.
- We have to keep track of that memory location. We need to access value at that memory location using ampersand operator/Address Operator i.e (&).
- If we store same variable in the register memory then we can access that memory location directly without using the Address operator.
- Register variable will be accessed faster than the normal variable thus increasing the operation and program execution. Generally we use register variable as Counter.
Limitations of Array in C Programming
Limitations of Array in C Programming :
We know What is an array in C Programming. Array is very useful which stores multiple data under single name with same data type. Following are some listed limitations of Array in C Programming.
A. Static Data
- Array is Static data Structure
- Memory Allocated during Compile time.
- Once Memory is allocated at Compile Time it Cannot be Changed during Run-time
B. Can hold data belonging to same Data types
- Elements belonging to different data types cannot be stored in array because array data structure can hold data belonging to same data type.
- Example : Character and Integer values can be stored inside separate array but cannot be stored in single array
C. Inserting data in Array is Difficult
- Inserting element is very difficult because before inserting element in an array we have to create empty space by shifting other elements one position ahead.
- This operation is faster if the array size is smaller, but same operation will be more and more time consuming and non-efficient in case of array with large size.
D. Deletion Operation is difficult
- Deletion is not easy because the elements are stored in contiguous memory location.
- Like insertion operation , we have to delete element from the array and after deletion empty space will be created and thus we need to fill the space by moving elements up in the array.
E. Bound Checking
- If we specify the size of array as ‘N’ then we can access elements upto ‘N-1′ but in C if we try to access elements after ‘N-1′ i.e Nth element or N+1th element then we does not get any error message.
- Process of Checking the extreme limit of array is called Bound Checking and C does not perform Bound Checking.
- If the array range exceeds then we will get garbage value as result.
F. Shortage of Memory
- Array is Static data structure. Memory can be allocated at compile time only Thus if after executing program we need more space for storing additional information then we cannot allocate additional space at run time.
- Shortage of Memory , if we don’t know the size of memory in advance
G. Wastage of Memory
- Wastage of Memory , if array of large size is defined
Here are more some recommended readings on limitations on array.
Scanf : Reading or Accepting String From User in C
Scanf : Reading or Accepting String From User in C
In C Programming we can use scanf function from stdio.h header file to read string. Scanf function is commonly used for accepting string.
Syntax for Accepting String :
scanf("%s",Name_Of_String_Variable);
Live Example :
#include<stdio.h> void main() { char name[20]; printf("\nEnter the Name : "); scanf("%s",name); }
Explanation : Scanf Program
In the above program we are accepting string from user using scnaf() function. We cannot use string ampersand address operator in the scanf() because string itself can be referred by address.
Some Rules and Facts :
- Format Specifier %s is used for Accepting String
- Scanf() function accepts only String before Space
#include<stdio.h> int main() { char name[20]; printf("\nEnter the Name : "); scanf("%s",name); printf("Name of the Company : %s",name); return(0); }
Output :
Enter the Name : Google Incl Name of the Company : Google
We can use scanf to Accept String With Spaces. Just Replace above scanf statement with this following statement -
scanf("%[\^n]", name );
Read more about Reading String with spaces using scanf.
Why We does not need Ampersand Operator :
- Scanf() needs a pointer to the variable that will store input.
- In the case of a string, you need a pointer to an array of characters in memory big enough to store whatever string is read in.
- When you declare something like char var[100], you make space for 100 chars with name[0] referring to the first char and name[99] referring to the 100th char.
- The array name by itself evaluates to exactly the same thing as &name[0], which is a pointer to the first character of the sequence, exactly what is needed by scanf.
- So all you need to do is -
scanf("%s", name);
Initializing Array of Structure in C Programming
Initializing Array of Structure in C Programming
- Array elements are stored in consecutive memory Location.
- Like Array , Array of Structure can be initialized at compile time.
Way1 : Initializing After Declaring Structure Array :
struct Book { char bname[20]; int pages; char author[20]; float price; }b1[3] = { {"Let us C",700,"YPK",300.00}, {"Wings of Fire",500,"APJ Abdul Kalam",350.00}, {"Complete C",1200,"Herbt Schildt",450.00} };
Explanation :
As soon as after declaration of structure we initialize structure with the pre-defined values. For each structure variable we specify set of values in curly braces. Suppose we have 3 Array Elements then we have to initialize each array element individually and all individual sets are combined to form single set.
{"Let us C",700,"YPK",300.00}
Above set of values are used to initialize first element of the array. Similarly -
{"Wings of Fire",500,"APJ Abdul Kalam",350.00}
is used to initialize second element of the array.
Way 2 : Initializing in Main
struct Book { char bname[20]; int pages; char author[20]; float price; }; void main() { struct Book b1[3] = { {"Let us C",700,"YPK",300.00}, {"Wings of Fire",500,"Abdul Kalam",350.00}, {"Complete C",1200,"Herbt Schildt",450.00} }; }
Some Observations and Important Points :
Tip #1 : All Structure Members need not be initialized
#include<stdio.h> struct Book { char bname[20]; int pages; char author[20]; float price; }b1[3] = { {"Book1",700,"YPK"}, {"Book2",500,"AAK",350.00}, {"Book3",120,"HST",450.00} }; void main() { printf("\nBook Name : %s",b1[0].bname); printf("\nBook Pages : %d",b1[0].pages); printf("\nBook Author : %s",b1[0].author); printf("\nBook Price : %f",b1[0].price); }
Output :
Book Name : Book1 Book Pages : 700 Book Author : YPK Book Price : 0.000000
Explanation :
In this example , While initializing first element of the array we have not specified the price of book 1.It is not mandatory to provide initialization for all the values. Suppose we have 5 structure elements and we provide initial values for first two element then we cannot provide initial values to remaining elements.
{"Book1",700,,90.00}
above initialization is illegal and can cause compile time error.
Tip #2 : Default Initial Value
struct Book { char bname[20]; int pages; char author[20]; float price; }b1[3] = { {}, {"Book2",500,"AAK",350.00}, {"Book3",120,"HST",450.00} };
Output :
Book Name : Book Pages : 0 Book Author : Book Price : 0.000000
It is clear from above output , Default values for different data types.
Data Type | Default Initialization Value |
---|---|
Integer | 0 |
Float | 0.0000 |
Character | Blank |
Pointer Within Structure in C Programming
Pointer Within Structure in C Programming :
- Structure may contain the Pointer variable as member.
- Pointers are used to store the address of memory location.
- They can be de-referenced by ‘*’ operator.
Example :
struct Sample { int *ptr; //Stores address of integer Variable char *name; //Stores address of Character String }s1;
- s1 is structure variable which is used to access the “structure members”.
s1.ptr = # s1.name = "Pritesh"
- Here num is any variable but it’s address is stored in the Structure member ptr (Pointer to Integer)
- Similarly Starting address of the String “Pritesh” is stored in structure variable name(Pointer to Character array)
- Whenever we need to print the content of variable num , we are dereferancing the pointer variable num.
printf("Content of Num : %d ",*s1.ptr); printf("Name : %s",s1.name);
Live Example : Pointer Within Structure
#include<stdio.h> struct Student { int *ptr; //Stores address of integer Variable char *name; //Stores address of Character String }s1; int main() { int roll = 20; s1.ptr = &roll; s1.name = "Pritesh"; printf("\nRoll Number of Student : %d",*s1.ptr); printf("\nName of Student : %s",s1.name); return(0); }
Output :
Roll Number of Student : 20 Name of Student : Pritesh
Some Important Observations :
printf("\nRoll Number of Student : %d",*s1.ptr);
We have stored the address of variable ‘roll’ in a pointer member of structure thus we can access value of pointer member directly using de-reference operator.
printf("\nName of Student : %s",s1.name);
Similarly we have stored the base address of string to pointer variable ‘name’. In order to de-reference a string we never use de-reference operator.
Ferror Macro : Test whether error has occurred on a stream or not
Ferror Macro :
- “ferror” is Macro.
- This tests if an error has occurred on a stream or not.
- Tests Give Stream for Read / Write Error.
Syntax :
int ferror(FILE *stream);
- Return Type : Integer.
- Parameter : File Stream
Live Example :
#include<stdio.h> int main(void) { FILE *fp; fp = fopen("myfile.txt","w"); if (ferror(fp)) { printf("Error has Occured"); clearerr(stream); } }
Return Value :
- If Error has Occurred : Returns [Non Zero Value]
- If Error has no Occurred : Returns [Zero]
Explanation of the Code :
We have opened file for writing purpose in write mode. Whenever we open file for writing then we have to check whether file is opened in writing mode or not. If not then Compiler will throw the error. ferror macro will check whether there is error while opening the stream or not.
if (ferror(fp)) { printf("Error has Occured"); clearerr(stream); }
If we found any error then we are executing the exception or error handler code.
Summary :
Type | It is Macro Not a function |
---|---|
Purpose | Tests if an error has occurred on a stream or not |
Return Value | Non Zero Value if True |
Zero Value if False |
Some Structure Declarations and Its Meaning
Some Structure Declarations and It’s Meaning :
struct { int length; char *name; }*ptr;
Suppose we initialize these two structure members with following values -
length = 30; *name = "programming";
Now Consider Following Declarations one by One -
Example 1 : Incrementing Member
++ptr->length
- “++” Operator is pre-increment operator.
- Above Statement will increase the value of “length“
Example 2 : Incrementing Member
(++ptr)->length
- Content of the length is fetched and then ptr is incremented.
Consider above Structure and Look at the Following Table :-
Expression | Meaning |
---|---|
++ptr->length | Increment the value of length |
(++ptr)->length | Increment ptr before accessing length |
(ptr++)->length | Increment ptr after accessing length |
*ptr->name | Fetch Content of name |
*ptr->name++ | Incrementing ptr after Fetching the value |
(*ptr->name)++ | Increments whatever str points to |
*ptr++->name | Incrementing ptr after accessing whatever str points to |
C Program to Print Value and Address of Variable of Pointer
Print Value and Address of Variable of Pointer :
#include<stdio.h> main( ) { int i = 3, *j, **k ; j = &i ; k = &j ; printf ( "\nAddress of i = %u", &i ) ; printf ( "\nAddress of i = %u", j ) ; printf ( "\nAddress of i = %u", *k ) ; printf ( "\nAddress of j = %u", &j ) ; printf ( "\nAddress of j = %u", k ) ; printf ( "\nAddress of k = %u", &k ) ; printf ( "\nValue of j = %u", j ) ; printf ( "\nValue of k = %u", k ) ; printf ( "\nValue of i = %d", i ) ; printf ( "\nValue of i = %d", * ( &i ) ) ; printf ( "\nValue of i = %d", *j ) ; printf ( "\nValue of i = %d", **k ) ; }
Output :
Address of i = 65524 Address of i = 65524 Address of i = 65524 Address of j = 65522 Address of j = 65522 Address of k = 65520 Value of j = 65524 Value of k = 65522 Value of i = 3 Value of i = 3 Value of i = 3 Value of i = 3