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
Basic Stack Operation : Data Structure
Primitive Basic Stack Operation in C
We know that Stack can be represented using an array. Stack is open at one end and operations can be performed on single end. We can have different primitive operations on Stack Data Structure.
Creating Stack Data Structure :
typedef struct stack { int data[MAX]; int top; }stack;
Basic Operations Performed on Stack :
- Create
- Push
- Pop
- Empty
A. Creating Stack :
- Stack can be created by declaring the structure with two members.
- One Member can store the actual data in the form of array.
- Another Member can store the position of the topmost element.
typedef struct stack { int data[MAX]; int top; }stack;
B. Push Operation on Stack :
We have declared data array in the above declaration. Whenever we add any element in the ‘data’ array then it will be called as “Pushing Data on the Stack”.
Suppose “top” is a pointer to the top element in a stack. After every push operation, the value of “top” is incremented by one.
C. Pop Operation on Stack :
Whenever we try to remove element from the stack then the operation is called as POP Operation on Stack.
Some basic Terms :
Concept | Definition |
---|---|
Stack Push | The procedure of inserting a new element to the top of the stack is known as Push Operation |
Stack Overflow | Any attempt to insert a new element in already full stack is results into Stack Overflow. |
Stack Pop | The procedure of removing element from the top of the stack is called Pop Operation. |
Stack Underflow | Any attempt to delete an element from already empty stack results into Stack Underflow. |
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
Function Pointer in C Programming : Complete Reference
Requirement | Declaration of Function Pointer | Initialization of Function Pointer | Calling Function using Pointer |
---|---|---|---|
Return Type : None Parameter : None | void *(*ptr)(); | ptr = &display; | (*ptr)(); |
Return Type : Integer Parameter : None | int *(*ptr)(); | ptr = &display; | int result; result = (*ptr)(); |
Return Type : Float Parameter : None | float *(*ptr)(); | ptr = &display; | float result; result = (*ptr)(); |
Return Type : Char Parameter : None | char *(*ptr)(); | ptr = &display; | char result; result = (*ptr)(); |
Example 1 : Function having two Pointer Parameters and return type as Pointer
#include<stdio.h> char * getName(int *,float *); int main() { char *name; int num = 100; float marks = 99.12; char *(*ptr)(int*,float *); ptr=&getName; name = (*ptr)(&num,&marks); printf("Name : %s",name); return 0; } //------------------------------------- char *getName(int *ivar,float *fvar) { char *str="www.c4learn.com"; str = str + (*ivar) + (int)(*fvar); return(str); }
Output :
.c4learn.com
Global Copy is Accessible in All the Functions : C Programming
Different Copies of Variables : Local Copy and Global Copy
#include<stdio.h> int num = 100 ; // Global void func(); // Prototype int main() { int num = 20; // Local to main { int num = 30 ; // Local to Inner Part printf("%d ",num); func(); } printf("%d ",num); return(0); } void func() { printf("%d ",num); }
Output :
30 100 20
Explanation : Scope of the Variable
We have 3 copies of the variable “num”. We have global copy,local copy of main function and local copy of inner block.
{ int num = 30 ; // Local to Inner Part printf("%d ",num); func(); }
in the above inner block, priority is given to the local variable i.e 30.
void func() { printf("%d ",num); }
after calling the above function from inner block we can have access to the global copy of variable since we don’t have local copy of variable.
printf("%d ",num); return(0);
after moving out from the inner block, we again have access to the local copy from main function.
Local copy of Block will get Higher Priority than Global Copy of Variable.
#include<stdio.h> void main() { int num = 20; { int x = 30 ; printf("%d ",num); } printf("%d ",num); return(0); }
Output :
30 20
Explanation :
Consider the following inner block -
{ int x = 30 ; printf("%d ",num); }
Inner variable x is local variable of inner block. Though the variable have global copy, first priority is given to the local copy of the block. As soon as the block ends the local copy will be destroyed.
printf("%d ",num); return(0);
Higher Priority is Given to Local Variables : Accessing Variable in C Programming
Higher Priority is Given to Local Variables
#include<stdio.h> int num = 50 ; void main() { int num = 20; printf("%d",num); }
Output :
20
Explanation :
Above program contain two different copies of the variable, One local copy and another global copy. Local and Global Copy have same name.
int num = 50 ; void main() { int num = 20; }
Rule :
In C Higher Priority is Given to Local Variables
Bit Manipulation Using Structure in C Programming Language
Bit Operations using Structure !!!
Suppose we want to store the gender of the person , then instead of wasting the complete byte we can manipulate single bit. We can consider Single bit as a flag. Gender of Person can be stored as [M/F] . By Setting the flag bit 1 we can set Gender as “Male” and “Female” by setting bit as 0
- To pack Several data objects in the single memory word , Bits are used.
- Flags can be used in order to store the Boolean values ( T / F ).
- A method to define a structure of packed information is known as bit fields.
Syntax : Bit Manipulation
struct databits { int b1 : 1; int b2 : 1; int b3 : 1; int b4 : 4; int b5 : 9; }data1;
Explanation :
- In the above example, we can say that we have allocated specific number of bits to each structure member.
- Integer can store 2 bytes (*) , so 2 bytes are manipulated in bits and 1 bit is reserved for b1. Similarly b2,b3 will get single bit.
- Similarly we can structure efficiently to store boolean values or smaller values that requires little membory.
How to access the Individual Bits ?
data1.b1 data1.b2 data1.b3 data1.b4 data1.b5
We can access the individual structure member by using dot operator. Each data member of structure can be accessed by using tag name followed by dot and structure member.
How to initialize Structure ?
struct databits { - - - - - - }data1 = { 1,1,0,10,234 };
Initialized Result -
data1.b1 = 1 data1.b2 = 1 data1.b3 = 0 data1.b4 = 10 data1.b5 = 234
Pictorial Representation :
How to calculate size of structure without using sizeof operator ?
Evaluate Size of Structure Without using Sizeof Operator.
Sizeof operator is used to evaluate the size of any data type or any variable in c programming. Using sizeof operator is straight forward way of calculating size but following program will explain you how to calculate size of structure without using sizeof operator.
#include<stdio.h> struct { int num1,num2; }a[2]; void main() { int start,last; start = &a[1].num1; last = &a[0].num1; printf("\nSize of Structure : %d Bytes",start-last); }
Steps to Calculate Size of Structure :
- Create Structure .
- Create an array of Structure , Here a[2].
- Individual Structure Element and Its Address -
Address of a[0].num1 = 2000 Address of a[0].num2 = 2002 Address of a[1].num1 = 2004 Address of a[1].num2 = 2005
- &a[1].num1 - 2004
- &a[0].num1 - 2000
- Difference Between Them = 2004 - 2000 = 4 Bytes (Size of Structure)
Another Live Example :
#include<stdio.h> struct { int num1,num2; char s1; int *ptr; int abc[5]; }a[2]; void main() { int start,last; start = &a[1].num1; last = &a[0].num1; printf("\nSize of Structure : %d Bytes",start-last); }
Output :
Size of Structure : 17 Bytes
Declaring Structure Variable in C Programming Language
Declaring Structure Variable in C
In C we can group some of the user defined or primitive data types together and form another compact way of storing complicated information is called as Structure. Let us see how to declare structure in c programming language -
Syntax Of Structure in C Programming :
struct tag { data_type1 member1; data_type2 member2; data_type3 member3; };
Structure Alternate Syntax :
struct <structure_name> { structure_Element1; structure_Element2; structure_Element3; ... ... };
Some Important Points Regarding Structure in C Programming :
- Struct keyword is used to declare structure.
- Members of structure are enclosed within opening and closing braces.
- Declaration of Structure reserves no space.
- It is nothing but the “ Template / Map / Shape ” of the structure .
- Memory is created , very first time when the variable is created / Instance is created.
Different Ways of Declaring Structure Variable :
Way 1 : Immediately after Structure Template
struct date { int date; char month[20]; int year; }today; // 'today' is name of Structure variable
Way 2 : Declare Variables using struct Keyword
struct date { int date; char month[20]; int year; }; struct date today;
where “date” is name of structure and “today” is name of variable.
Way 3 : Declaring Multiple Structure Variables
struct Book { int pages; char name[20]; int year; }book1,book2,book3;
We can declare multiple variables separated by comma directly after closing curly.
Introduction to Structure in C Programming Language
Introduction to Structure in C
- As we know that Array is collection of the elements of same type , but many time we have to store the elements of the different data types.
- Suppose Student record is to be stored , then for storing the record we have to group together all the information such as Roll,name,Percent which may be of different data types.
- Ideally Structure is collection of different variables under single name.
- Basically Structure is for storing the complicated data.
- A structure is a convenient way of grouping several pieces of related information together.
Definition of Structure in C:
Structure is composition of the different variables of different data types , grouped under same name.
typedef struct { char name[64]; char course[128]; int age; int year; } student;
Some Important Definitions of Structures :
- Each member declared in Structure is called member.
char name[64]; char course[128]; int age; int year;
are some examples of members.
- Name given to structure is called as tag
student
- Structure member may be of different data type including user defined data-type also
typedef struct { char name[64]; char course[128]; book b1; int year; } student;
Here book is user defined data type.
Advantages And Features Of Object Oriented Programming
Advantages Of Object Oriented Programming :
- OOP provides a clear modular structure for programs.
- It is good for defining abstract data types.
- Implementation details are hidden from other modules and other modules has a clearly defined interface.
- It is easy to maintain and modify existing code as new objects can be created with small differences to existing ones.
- objects, methods, instance, message passing, inheritance are some important properties provided by these particular languages
- encapsulation, polymorphism, abstraction are also counts in these fundamentals of programming language.
- It implements real life scenario.
- In OOP, programmer not only defines data types but also deals with operations applied for data structures.
Features Of Object Oriented Programming :
- More reliable software development is possible.
- Enhanced form of c programming language.
- The most important Feature is that it’s procedural and object oriented nature.
- Much suitable for large projects.
- Fairly efficient languages.
- It has the feature of memory management.
Binary File Format : Complex Formatting File Format in C Programming
What are Binary Files :
- Binary Files Contain Information Coded Mostly in Binary Format.
- Binary Files are difficult to read for human.
- Binary Files can be processed by certain applications or processors.
- Only Binary File Processors can understood Complex Formatting Information Stored in Binary Format.
- Humans can read binary files only after processing.
- All Executable Files are Binary Files.
Explanation :
As shown in fig. Binary file is stored in Binary Format (in 0/1). This Binary file is difficult to read for humans. So generally Binary file is given as input to the Binary file Processor. Processor will convert binary file into equivalent readable file.
Some Examples of the Binary files :
- Executable Files
- Database files
Text file Format in C Programming Language
Text file Format in C Programming :
- Text File is Also Called as “Flat File“.
- Text File Format is Basic File Format in C Programming.
- Text File is simple Sequence of ASCII Characters.
- Each Line is Characterized by EOL Character (End of Line).
Text File Formats :
- Text File have .txt Extension.
- Text File Format have Little contains very little formatting .
- The precise definition of the .txt format is not specified, but typically matches the format accepted by the system terminal or simple text editor.
- Files with the .txt extension can easily be read or opened by any program that reads text and, for that reason, are considered universal (or platform independent).
- Text Format Contain Mostly English Characters
Printf MCQ 8 : Multiple Strings seperated by Comma
Printf Multiple Choice Questions : Multiple Strings Separated by Comma
Guess the output of Program -
#include<stdio.h> #include<conio.h> void main() { clrscr(); printf("Computer","Programming"); getch(); }
No | Options |
---|---|
1 | Computer |
2 | Programming |
3 | ComputerProgramming |
4 | Garbage |
Explanation of Program :
- Only First String before comma will be accepted.
- If number of Strings are Separated by “Comma” then it will accept only first String because printf looks for double quote immediately after Opening round bracket.
- Once corresponding closing double quote is detected, printf will ignore any string written after comma.
#include<stdio.h> #include<conio.h> void main() { clrscr(); printf("Computer : %s","Programming"); getch(); }
In case of above program, Printf finds format string inside printf “%s”. As it is first format specifier printf will look first parameter after comma. So output of the above program will be -
Computer : Programming
Arithmetic Operator in C Programming Language
Arithmetic Operator in C Programming Language
- C Programming Supports 5 Arithmetic Operators.
- Arithmetic Operators are used for “Arithmetic Calculation“.
Supported Arithmetic Operators :
5 arithmetic operators are shown in the following table. Arithmetic operators are used to perform arithmetic operations in c programming.
Operator | Meaning | Example |
---|---|---|
+ | Addition Operator | 10 + 20 = 30 |
- | Subtraction Operator | 20 - 10 = 10 |
* | Multiplication Operator | 20 * 10 = 200 |
/ | Division Operator | 20 / 10 = 2 |
% | Modulo Operator | 20 % 6 = 2 |
Live Example : C Program to Verify Arithmetic Operator and Operation
#include <stdio.h> int main() { int num1,num2; int sum,sub,mult,div,mod; printf("\nEnter First Number :"); scanf("%d",&num1); printf("\nEnter Second Number :"); scanf("%d",&num2); sum = num1 + num2; printf("\nAddition is : %d",sum); sub = num1 - num2; printf("\nSubtraction is : %d",sub); mult = num1 * num2; printf("\nMultiplication is : %d",mult); div = num1 / num2; printf("\nDivision is : %d",div); mod = num1 % num2; printf("\nModulus is : %d",mod); return(0); }
Output :
Enter First Number : 10 Enter Second Number : 5 Addition is : 15 Subtraction is : 5 Multiplication is : 50 Division is : 2 Modulus is : 0
Precedence Power : Which Operator have Highest Priority ?
If we consider all the arithmetic operators then we can say that Multiplication and division operator have highest priority than addition and subtraction operator. Following table clearly explains the priority of all arithmetic operators in C programming -
Priority Rank | Operator Description | Operator | Associativity |
---|---|---|---|
1 | Multiplication | * | Left to Right |
1 | Division | / | Left to Right |
1 | Modulo | % | Left to Right |
2 | Addition | + | Left to Right |
2 | Subtraction | - | Left to Right |
Note :
Common C Programming Mistakes : Preprocessor Errors
Errors Or [ Mistakes/Misuse] of C Preprocessor in C :
Preprocessor processes given source code before giving it to the compiler.Preprocessor must be used with care. Some of the Common mistakes while using preprocessor are as below -
1 . Macro expansion should be enclosed within parenthesis
#include<stdio.h> #include<conio.h> #define SQU(x) x*x void main() { int num ; clrscr(); num = SQU(2)/SQU(2); printf("Answer : %d",num); getch(); }
Output :
Answer : 4
Explanation of Program :
Above expression will be expanded as -
SQU(x) / SQU(x) = [ x*x / x*x] = [ x*x/x*x ] = [ x*x ] = [ x^2 ]
In the program the macro #define substitutes SQU(2) by just 2*2 not by 4. thus -
SQU(2) / SQU(2) = [ 2*2 / 2*2] = [ 2*2/2*2 ] = [ 2*2 ] = [ 2^2 ] = [ 4 ]
How to avoid this problem ?
#define SQU(x)((x)*(x))
2 .Do not Leave blank between macro-template and its argument
#define SQU(x)((x)*(x))//Write like this
- Do not give space between SQU and (x) , as it becomes the part of macro expansion
- It results into Improper result OR Compile time Error
3 . Do not Give semicolon at the end of #define statement .
#define SQU(x)((x)*(x));//Do not give semicolon at the end
4 . Allot one line for each macro preprocessor
#include<stdio.h> #include<conio.h>// Write on separate line
Do not write like this
#include<stdio.h>#include<conio.h>
One’s Compliment Operator in C : Negation in C Language
One’s Compliment Operator in C
- It is denoted by ~
- Bit Pattern of the data can be Reversed using One’s Compliment
- It inverts each bit of operand .
- One’s Compliment is Unary Operand i.e Operates on 1 Argument
Original Number A | 0000 0000 0011 1100 |
One’sCompliment | 1111 1111 1100 0011 |
Zero’s Are Changed to | 1 |
One’s Are Changed to | 0 |
Syntax :
~Variable_Name
Live Example : Negation Operator in C Programming
#include<stdio.h> int main() { int a=10; printf("\nNegation of Number 1 : %d",~a); return(0); }
Output :
Negation of Number 1 : -11
Memory Representation of Multidimensional Array : C Programming
Memory Representation
- 2-D arrays are Stored in contiguous memory location row wise.
- 3 X 3 Array is shown below in the first Diagram.
- Consider 3×3 Array is stored in Contiguous memory location which starts from 4000 .
- Array element a[0][0] will be stored at address 4000 again a[0][1] will be stored to next memory location i.e Elements stored row-wise
- After Elements of First Row are stored in appropriate memory location , elements of next row get their corresponding mem. locations.
- This is integer array so each element requires 2 bytes of memory.
Basic Memory Address Calculation :
a[0][1] = a[0][0] + Size of Data Type
Element | Memory Location |
---|---|
a[0][0] | 4000 |
a[0][1] | 4002 |
a[0][2] | 4004 |
a[1][0] | 4006 |
a[1][1] | 4008 |
a[1][2] | 4010 |
a[2][0] | 4012 |
a[2][1] | 4014 |
a[2][2] | 4016 |
Assignment Operator in C Programming Language
Assignment Operator in C Programming Language :
- Assignment Operator is Used to Assign Value to a Variable.
- Assignment Operator is Denoted by Equal to Sign , “=“.
- Assignment Operator is Binary Operator i.e It Operates on Two Operands.
- Assignment Operator have Two Values - L-Value and R-Value.
- Assignment Operator Copies R-Value into L-Value.
- Assignment Operator have Lower Precedence than any Other Operand and Higher Precedence than “Comma Operator“. [View this Precedence Table ]
Different Ways of Using Assignment Operator :
Way 1 : Assignment Operator used to Assign Value
#include<stdio.h> int main() { int value; value = 55; return(0); }
Way 2 : Assignment Operator used To Type Cast.
Assignment Operator can Type Cast Higher Values to Lower Values or Lower Values to Higher Values
int value; value = 55.450; printf("%d",value);
Way 3 : Assignment Operator in If Statement
if(value = 10) printf("True"); else printf("False");
Haha… Above Program will always execute True Condition because Assignment Operator is Used inside If Statement not Comparison Operator.
Different Categories of Variables Depending on Number of Values it Can Store
Variable Can be categorized depending on Type of Data it stores inside -
- Variable Storing Integer Data Type is called as “Integer Variable“.
- Variable Storing Character Data Type is called as “Character Variable“.
- Variable Storing Float Data Type is called as “Float Variable“.
- Variable Storing Double Data Type is called as “Double Variable“.
Variables can be categorized depending on Number of Variables it can store -
- Variable storing single value at a time of any data type is called as “Normal or Ordinary” Variable.
- Variable Storing multiple values of same data type is called as ”Array“.
- Variable Storing multiple values of different data type is called as “Structure” [ User defined data type]
Token : Basic Building Block in C
C Tokens Chart
- In C Programming punctuation,individual words,characters etc are called tokens.
- Tokens are basic building blocks of C Programming
Example :
No | Token Type | Example 1 | Example 2 |
---|---|---|---|
1 | Keyword | do | while |
2 | Constants | number | sum |
3 | Identifier | -76 | 89 |
4 | String | HTF” | PRIT” |
5 | Special Symbol | * | @ |
6 | Operators | ++ | / |
Basic Building Blocks and Definition :
Token | Meaning |
---|---|
Keyword | A variable is a meaningful name of data storage location in computer memory. When using a variable you refer to memory address of computer |
Constant | Constants are expressions with a fixed value |
Identifier | The term identifier is usually used for variable names |
String | Sequence of characters |
Special Symbol | Symbols other than the Alphabets and Digits and white-spaces |
Operators | A symbol that represent a specific mathematical or non mathematical action |
Difference Between Single Line and Multi line Comment ?
Difference Between Single Line and Multi line Comment ?
Multi-line Comment | Single-line Comments |
---|---|
Starts with /* and ends with */ | Starts with // |
All Words and Statements written between /* and */ are ignored | Statements after the symbol // upto the end of line are ignored |
Comment ends when */ Occures | Comment Ends whenever ENTER is Pressed and New Line Starts |
e.g /* This is Multiline Comment */ | e.g // Single line Comment |
Comments in C :
Below are some of the examples where we can use different kinds of comments.Single line comment and multiple line comments can be
Hiding Code using Comments :
Single Line Comments are useful where you need to comment or hide two-three words however multiple line comments are useful where you want to hide multiple lines of code.
/* for(i=0;i<num;i++) { printf("\nEnter the Number : "); scanf("%d",&arr[i]); } */
i.e Suppose we want to hide multiple lines then instead of using single line comment before each line we can use multiple line comment.
for(i=0;i<num;i++) { printf("\nEnter the Number : "); scanf("%d",&arr[i]); // i++; }
Rules of Writing Comments in C Programming
Rules :
1 . Program Contain Any number of comments at any place
void main(/*Main Function*/) { int age; // Variable printf("Enter Your Age : "); scanf("%d",/*Type Age*/&age); printf("Age is %d : ",/*Your age here*/age); getch() }
2 . Nested Comments are not allowed i.e Comment within Comment
/* This is /*Print Hello */ */ printf("Hello");
3 . Comments can be split over more than one line.
printf("Hello"); /* This is Comment */
4 . Comments are not Case-Sensitive.
printf("Hello"); /* This is Comment */ /* THIS IS COMMENT */
5 . Single line Comments Starts with ‘//’
printf("Hello"); // This is Single Line Comment
Multi Line Comment in C Programming
Multi Line Comment
- Multi Line Comment Can be Placed Anywhere.
- Multi Line Comment Starts with ‘/*’ .
- Multi Line Comment Ends with ‘*/’ .
- Any Symbols written between ‘/*’ and ‘*/’ are ignored by Compiler.
- It can be split over multiple Lines
Example :
#include<stdio.h> void main() { printf("Hello"); /* Multi Line Comment */ printf("By"); }
Which Part is Ignored by Compiler ? [Shown by Dash]
#include<stdio.h> void main() { printf("Hello"); /*-------------------------------------------- ------------------Ignored by compiler------- -------------------------------------------- */ printf("By"); }
Different Ways of Using Multiple Line Comment :
Way 1 : Used for Program Title and Documentation
/**************************************** * Title : Program Name * * Author: Author Name * ***************************************/
Way 2 : Used for More detailed comment inside program
/* following line is used to get - 1.Count of the Customer 2.It is going to Return Integer */ int var = getCount(str);
OR
int var = getCount(str); /* Used to count Number of Persons Present */ pritnf("count : %d",var);
What is declaration in Programming Language ?
What is Declaration ?
- To Declare is nothing but to represent a variable.
- Only Variable name and its Data type is Represented in Declaration.
Facts about Declaration :
- Memory is neither allocated to Variable nor space is Reserved after declaration.
- Declaration is just used for Identification of Data Type.
- Re-Declaration of variable will cause compile Error.
int ivar; int ivar = 10;
It will cause compile error. We cannot re-declare variable.
- We cannot use variable inside program expression or in program statements without declaring.
- Declaring a variable just give rough idea to compiler that there is something which is of type “<Data Type Specified>” and will be used in the program.
Example Of Declaration :
int ivar;
float fvar;
char cvar;
String Constant in C Programming Language
String Constant in C Programming Language :
- String is “Sequence of Characters“.
- String Constant is written in Pair of Double Quotes.
- String is declared as Array of Characters.
- In C , String data type is not available.
- Single Character String Does not have Equivalent Integer Value i.e ASCII Value
Different Constant Values Contained inside String :
String with Single Character
"a"
String With Multiple Characters
"Ali"
String With Digits
"123"
String With Blanks
"How are You"
Note :
1] 'A' is not Equal to "A"
2] 'A' ==> Requires 1 byte Memory
3] "A" ==> Requires 2 byte Memory
Summary :
Example | Meaning |
---|---|
a” | String with Single Character |
Ali” | String With Multiple Characters |
123? | String With Digits |
How are You” | String With Blanks |