404

Page not found.

Kruskal’s algorithm : Reference

ImageDescription
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.

Features of C Programming Language

Features of C Programming Language :

C Programming is widely used in Computer Technology, We can say that C Programming is inspiration for development of other languages. We can use C Programming for different purposes. Below are some of the Features of C Programming language -

Features of C
Low Level Language SupportProgram Portability
Powerful and Feature RichBit Manipulation
High Level FeaturesModular Programming
Efficient Use of Pointers

1 . Low Level Features :

  1. C Programming provides low level features that are generally provided by the Lower level languages. C is Closely Related to Lower level Language such as “Assembly Language“.
  2. It is easier to write assembly language codes in C programming.

2 . Portability :

  1. C Programs are portable i.e they can be run on any Compiler with Little or no Modification
  2. Compiler and Preprocessor make it Possible for C Program to run it on Different PC

3 . Powerful

  1. Provides Wide verity of ‘Data Types
  2. Provides Wide verity of ‘Functions’
  3. Provides useful Control & Loop Control Statements

4 . Bit Manipulation

  1. C Programs can be manipulated using bits. We can perform different operations at bit level. We can manage memry representation at bit level. [Eg. We can use Structure to manage Memory at Bit Level]
  2. It provides wide verity of bit manipulation Operators. We have bitwise operators to manage Data at bit level.

5 . High Level Features :

  1. It is more User friendly as compare to Previous languages. Previous languages such as BCPL,Pascal and other programming languages never provide such great features to manage data.
  2. Previous languages have there pros and cons but C Programming collected all useful features of previous languages thus C become more effective language.

6 . Modular Programming

  1. Modular programming is a software design technique that increases the extent to which software is composed of separate parts, called modules
  2. C Program Consist of Different Modules that are integrated together to form complete program

7 . Efficient Use of Pointers

  1. Pointers has direct access to memory.
  2. C Supports efficient use of pointer .

8 . More Efficient

Application of C Programming

Application Of C Programming

C Programming is best known programming language. C Programming is near to machine as well as human so it is called as Middle level Programming Language. C Programming can be used to do verity of tasks such as networking related,OS related.

Application of C Programming are listed below -

  1. C language is used for creating computer applications
  2. Used in writing Embedded softwares
  3. Firmware for various electronics, industrial and communications products which use micro-controllers.
  4. It is also used in developing verification software, test code, simulators etc. for various applications and hardware products.
  5. For Creating Compiles of different Languages which can take input from other language and convert it into lower level machine dependent language.
  6. C is used to implement different Operating System Operations.
  7. UNIX kernel is completely developed in C Language.

List of Applications of C Programming

List of Application
Operating SystemsNetwork DriversPrint Spoolers
Language CompilersAssemblersText Editors
Modern ProgramsData BasesLanguage Interpreters
SimulatorsUtilitiesEmbedded System

What is Compiler ?

Definition of Compiler :

  1. A computer program which reads source code and outputs assembly code or executable code is called compiler.
  2. A program that translates software written in source code into instructions that a computer can understand Software used to translate the text that a programmer writes into a format the CPU can use.
  3. A piece of software that takes third-generation language code and translates it into a specific assembly code. Compilers can be quite complicated pieces of software.

Compiler Overview :

Consider process of Executing Simple C Language Code -

We have opened C Code editor and wrote simple C Program , Whenever we try to compile code and try to execute code our code is given to the compiler.

int main()
{
printf("Hello");
return(0);
}

Now our main intention is to convert program into lower level language which can be read by Machine. Compiler have different phases , and program undergoes through these 6 phases. After Passing through all the compilation Phases our code is converted into the machine level language code which can be read by machine.

Different Phases of Compiler

  1. Lexical Analysis Phase
  2. Syntax Analysis
  3. Semantic Analysis
  4. Intermediate Code Generation
  5. Code Optimizer
  6. Code Generation

Analysis Phase >> Lexical Analysis [ Phases of Compiler ]

Compiler :

Compiler takes high level human readable program as input and convert it into the lower level code.This conversion takes place using different phases.First phase of compiler is lexical analysis.

Must Read : [What is Compiler ?]

Different phases of compilers :

  1. Analysis Phase
  2. Synthesis Phase

1.Analysis Phase :

Lexical Analysis Phase :

Task of Lexical Analysis is to read the input characters and produce as output a sequence of tokens that the parser uses for syntax analysis.

  1. Lexical Analyzer is First Phase Of Compiler.
  2. Input to Lexical Analyzer is “Source Code
  3. Lexical Analysis Identifies Different Lexical Units in a Source Code.
  4. Different Lexical Classes or Tokens or Lexemes
    • Identifiers
    • Constants
    • Keywords
    • Operators
  5. Example : sum = num1 + num2 ;


So Lexical Analyzer Will Produce following Symbol Table -

TokenType
sumIdentifier
=Operator
num1Identifier
+Operator
num2Identifier
;Seperator
  1. Lexical Analyzer is also called “Linear Phase” or “Linear Analysis” or “Scanning
  2. Individual Token is also Called Lexeme
  3. Lexical Analyzer’s Output is given to Syntax Analysis.

Analysis Phase >> Syntax Analysis [2nd Phase of Compiler]

Analysis Phase : 2nd Phase of Compiler (Syntax Analysis)

During the first Scanning phase i.e Lexical Analysis Phase of the compiler , symbol table is created by the compiler which contain the list of leximes or tokens.

Syntax Analysis :

  1. It is Second Phase Of Compiler after Lexical Analyzer
  2. It is also Called as Hierarchical Analysis or Parsing.
  3. It Groups Tokens of source Program into Grammatical Production
  4. In Short Syntax Analysis Generates Parse Tree

Parse Tree Generation :

sum = num1 + num2

Now Consider above C Programming statement. In this statement we Syntax Analyzer will create a parse tree from the tokens.

Syntax Analyzer will check only Syntax not the meaning of Statement

Explanation : Syntax Analysis

  • We know , Addition operator plus (‘+’) operates on two Operands
  • Syntax analyzer will just check whether plus operator has two operands or not . It does not checks the type of operands.
  • Suppose One of the Operand is String and other is Integer then it does not throw error as it only checks whether there are two operands associated with ‘+’ or not .
  • So this Phase is also called Hierarchical Analysis as it generates Parse Tree Representation of the Tokens generated by Lexical Analyzer

Analysis Phase >> Semantic analysis [3rd Phase of Compiler]

Syntax analyzer will just create parse tree. Semantic Analyzer will check actual meaning of the statement parsed in parse tree. Semantic analysis can compare information in one part of a parse tree to that in another part (e.g., compare reference to variable agrees with its declaration, or that parameters to a function call match the function definition).

Semantic Analysis is used for the following -

  1. Maintaining the Symbol Table for each block.
  2. Check Source Program for Semantic Errors.
  3. Collect Type Information for Code Generation.
  4. Reporting compile-time errors in the code (except syntactic errors, which are caught by syntactic analysis)
  5. Generating the object code (e.g., assembler or intermediate code)

Now In the Semantic Analysis Compiler Will Check -

  1. Data Type of First Operand
  2. Data Type of Second Operand
  3. Check Whether + is Binary or Unary.
  4. Check for Number of Operands Supplied to Operator Depending on Type of Operator (Unary | Binary | Ternary)

Various C compilers and Supported OS

Must Visit : What is Compiler ?


S.N.
Name of Compiler
Microprocessor
OS
1
Turbo c 3.0
8086
MS DOS
2
ANSIC C
80386
LINUX
3
Borland C 4.0
80386
WINDOW
4
Microsoft C
8086
MS DOS
5
Visual C++
80386
WINDOW

Note :
[arrowlist]

  • 8086 is 16 bit Processor
  • 80386 is 32 bit Processor
[/arrowlist] Download :Borland C/C++ Compiler

About Turbo C Compiler !!!

About Turbo C
[arrowlist]

  • Turbo C is an IDE for writting C Programs.
  • Turbo C IDE is created by Borland
  • Turbo C IDE (version 3.0) is based on MS-DOS Operating System
  • Turbo C uses 16 bit 8086 microprocessor
[/arrowlist] Some Points one should know about 8086 :
[arrowlist]
  • 8086 have 20 address buses.
  • 8086 have 16 data buses.
  • 8086 have word length = two byte.
[/arrowlist] Size of data types in Turbo C 3.0 :

Data type
Size
short int
2
int
2
long int
4
char
1
float
4
double
8
long double
10

Specification of Borland C/C++ 3.0 :

Byte ordering          : Little Endianness
Default pointer        : Near
Default memory model   : Small
To compile a c program : Alt + F9
To run a c program     : Ctrl + F9

Bitwise Left Shift (<<) Operator in C Programming

Bitwise Left Shift Operator in C

  1. It is denoted by <<
  2. Bit Pattern of the data can be shifted by specified number of Positions to Left
  3. When Data is Shifted Left , trailing zero’s are filled with zero.
  4. Left shift Operator is Binary Operator [Bi - two]
  5. 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’ BitsDecimal ValueConverted Value
0 Bit2^01
1 Bit2^12
2 Bits2^24
3 Bits2^38
4 Bits2^416
5 Bits2^532
6 Bits2^664
7 Bits2^7128
8 Bits2^8256

What is Interpreter in Programming Language?

What is Interpreter ?

  1. Interpreter Takes Single instruction as input .
  2. No Intermediate Object Code is Generated
  3. Conditional Control Statements are Executes slower
  4. Memory Requirement is Less
  5. Every time higher level program is converted into lower level program
  6. Errors are displayed for every instruction interpreted (if any)
  7. The interpreter can immediately execute high-level programs, thus interpreters are sometimes used during the development of a program, when a programmer wants to add small sections at a time and test them quickly.
  8. In addition, interpreters are often used in education because they allow students to program interactively.

Examples of Programming Languages Using Interpreter :

Lisp

(defun convert ()
(format t "Enter Fahrenheit ")
  (LET (fahr)
    (SETQ fahr (read fahr))
    (APPEND '(celsisus is) (*(- fahr 32)(/ 5 9)) )
  )
)

BASIC

CLS
INPUT "Enter your name: ", Name$
IF Name$="Mike" THEN 
    PRINT "Go Away!"
ELSE
    PRINT "Hello, "; Name$; ".  How are you today?"
END IF


External Reference Links : Advantages and Disadvantages of Interpreter | Interpreter

Difference between Compiler and Interpreter

Difference between Compiler and Interpreter

NoCompilerInterpreter
1Compiler Takes Entire program as inputInterpreter Takes Single instruction as input .
2Intermediate Object Code is GeneratedNo Intermediate Object Code is Generated
3Conditional Control Statements are Executes fasterConditional Control Statements are Executes slower
4Memory Requirement : More (Since Object Code is Generated)Memory Requirement is Less
5Program need not be compiled every timeEvery time higher level program is converted into lower level program
6Errors are displayed after entire program is checkedErrors are displayed for every instruction interpreted (if any)
7Example : C CompilerExample : BASIC

Explanation : Compiler Vs Interpreter

Just understand the concept of the compiler and interpreter -

  1. We give complete program as input to the compiler. Our program is in the human readable format.
  2. Human readable format undergoes many passes and phases of compiler and finally it is converted into the machine readable format.
  3. However interpreter takes single line of code as input at a time and execute that line. It will terminate the execution of the code as soon as it finds the error.
  4. Memory requirement is less in Case of interpreter because no object code is created in case of interpreter.

Following video will say much more about compiler -

Video Explanation :

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 = &num;
printf("%d",++*ptr);

Explanation :

  1. ‘++’ and ‘*’ both have Equal Precedence
  2. Associativity is from Right to Left ( Expression evaluated from R->L)
  3. Both are Unary (Operates on single operand )
  4. So ‘ * ‘ is Performed First then ‘ ++ ‘

Re-Commanded Reference Article : Operator Precedence Table

Visual Understanding :

Calculation of Answer :

  ++*ptr     =  ++ ( *ptr )
             =  ++ ( *3058 )
             =  ++ ( 20 )
             =  21
  1. Suppose ptr variable stores address 3058.
  2. * Operator will de-reference pointer to get value stored at that address. (i.e 20)
  3. 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 Low Level Language ?

What is Low level Language in Computer Science ?

  • Machine understandable Language.
  • Assembly is Common High Level Language
  • Internal Machine Code dependent
  • Fast to Run But slow to write & Understand

What is machine Level Language ?

  1. Machine code is the only language a microprocessor can process directly without a previous transformation.
  2. Currently, Programmers never write programs directly in machine code, because it requires attention to numerous details which a high-level language would handle automatically.
  3. Low Level Language Requires memorizing or looking up numerical codes for every instruction that is used.
  4. For this reason, second generation programming languages provide one abstraction level on top of the machine code.

Example: A function in 32-bit x86 machine code to calculate the nth Fibonacci number :

8B542408 83FA0077 06B80000 0000C383
FA027706 B8010000 00C353BB 01000000
B9010000 008D0419 83FA0376 078BD98B
C84AEBF1 5BC3

Higher Level Languages and Middle Level languages are different than Low Level Language in many aspects.

Summary of Lower Level Languages :

Low level languages are Machine Understandable, difficult to write, requires more efforts to code and debug.

Why C is Middle Level Language ?

Middle Level Language ?

C Programming bridges gap between traditional Machine Understandable Machine Level language and more conventional High level languages. User can Use C Language to do system programming for writing operating system as well as application programming.

Middle Level Programming languages are closely related to Machine as well as Human Being.

Why C is Middle Level Language ?

  1. C Programming Supports Inline Assembly Language Programs .
  2. Using inline assembly language feature in C we can directly access system registers.
  3. C Programming is used to access memory directly using pointer.
  4. C Programming also Supports high Level Language Features.
  5. It is more User friendly as compare to Previous languages so C programming is Middle Level Language.

C Language is Middle Level Language

Tips : Middle Level Language

  1. Language is more Close to Machine
  2. Language is far from Human i,e human need to take more efforts to code
  3. We have to Write More Code to meet user requirement and It is Easy to create Machine Level Code using C Programming.

This Article may be useful for readers.

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 ?

Pointer is the variable that stores the address of another variable.

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

  1. Pointer stores the address of the Variable.
  2. Size of Pointer Variable can be evaluated by using sizeof operator
  3. Address of variable is considered as integer value.
  4. For Borland C/C++ Compiler, for storing integer value 2 bytes are required.
  5. Thus Pointer variable requires 2 bytes of memory.

Size of Integer Pointer Variable in Different IDE :

CompilerSize of IntegerSize of Integer Pointer
Borland C/C++2 Bytes2 Bytes
Turbo C/C++2 Bytes2 Bytes
Visual C++4 Bytes4 bytes

Size of the Pointer :

#include<stdio.h>
int main()
{
int num = 15;
int *ptr = NULL;
ptr = &num;
printf("Size of Pointer : %d Bytes",sizeof(ptr));
return 0;
}

Output :

Size of Pointer : 2 Bytes

Some of the Useful Programs :

NoProgram
1C Program to Calculate Size of Integer Pointer
2C Program to Calculate Size of character Pointer
3C Program to Calculate Size of float Pointer
4C Program to compute size of integer far pointer
5C Program to find Size of Pointer to Structure

What is high Level Language and its Execution Model ?

High level Language :

  1. First high-level programming languages were designed in the 1950s.
  2. High level Language is Human understandable Language.
  3. English is Common example of High Level Language.
  4. High level Language is Internal Machine Code Independent.
  5. High level Language is Program Oriented Language.
  6. High level Language is Developed for providing GUI Interface.

Explanation :

As you can see the above diagram, it clearly shows that HLL are more close to human and can be easily programmed as compare to lower level language.In HLL Language and Machine gap is more.

C Programming can be considered as High Level / Low Level -

  • In early 70′s , C Programming was considered as High Level language because it was capable of evaluating expressions,parenthesis recursive functions etc.
  • Nowadays C may be considered as “Low Level Language” by some programmer because it lacks a large runtime-system (no garbage collection, etc.)

Execution Models of HLL :

1. Interpreted :

  1. Interpreted languages are read and then executed directly, with no compilation stage.
  2. Program is read line by line and convert it into machine code, and executes it. [More Info : Interpreter]

2. Compiled :

Languages are transformed into an executable form before running There are two types of compilation:

2.1 Machine code generation

Some compilers compile source code directly into machine code. Machine code is generated by using compiler it is called as “truly compiled” languages.

2.2 Intermediate representations

Language is converted into middle level language and further optimized and reused.

3. Translated :

  1. A language may be translated into a lower-level programming language for which native code compilers are already widely available.
  2. The C programming language is a common target for such translators.

Some High Level Languages :

  1. Ada
  2. Algol
  3. LISP
  4. Pascal
  5. Prolog.
  6. Java
  7. C#

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;
  1. Now in order to get roll number of first student we need to access roll1.
  2. Guess if we need to store roll numbers of 100 students then what will be the procedure.
  3. 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 :

  1. Bubble Sort
  2. Insertion Sort
  3. Selection Sort
  4. 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.

Matrix can be multi-dimensional

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.

Step By Step Execution Of C Program

Step By Step Execution Of C Program

Step 1 : Edit

  1. This is First Step i.e Creating and Editing Program.
  2. First Write C Program using Text Editor , such as [ Borland C/C++ 3.0 , Notpad++,Notpad ]
  3. Save Program by using [.C] Extension.
  4. File Saved with [.C] extension is called “Source Program“.

Step 2 : Compiling

  1. Compiling C Program : C Source code with [.C] Extension is given as input to compiler and compiler convert it into Equivalent Machine Instruction.
  2. In Borland C/C++ 3.0 program can be compiled using key [Alt + F9 ].
  3. Compiler Checks for errors . If source code is error-free then Code is converted into Object File [.Obj ].

Step 3 : Checking Errors

  1. During Compilation Compiler will check for error, If compiler finds any error then it will report it.
  2. User have to re-edit the program.
  3. After re-editing program , Compiler again check for any error.
  4. If program is error-free then program is linked with appropriate libraries.

Step 4 : Linking Libraries

  1. Program is linked with included header files.
  2. Program is linked with other libraries.
  3. This process is executed by Linker.

Step 5 : Error Checking

  1. If run time error occurs then “Run-time” errors are reported to user.
  2. Again programmer have to review code and check for the solution.

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 ?

PointExample 1Example 2
No of If Statements32
No of times Condition Tested (Positive No.)31
No of times Condition Tested (Negative No.)32
No of times Condition Tested (Zero No.)32

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 :

  1. Whenever we declare a variable then space will not be reserved for the variable.
  2. Whenever we declare a variable then compiler will not look for other details such as definition of the variable.
  3. 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 ?

  1. Declaration will identify the data type of the identifier.
  2. 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

NoDeclarationDefinition
1Space is Not ReservedIn Definition Space is Reserved
2Identifies Data TypeSome Initial Value is Assigned
3Re-Declaration is ErrorRe-Definition is Error
Some Re-commanded Reading List : Link 1 | Link 2 | Link 3

What is Data Type in C Programming ?

What is Data Type in C Programming ?

  1. A Data Type is a Type of Data.
  2. Data Type is a Data Storage Format that can contain a Specific Type or Range of Values.
  3. 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 TypekeywordDescription
Integer Data TypeintStores the Integer Value
Float Data TypefloatStores the Floating Point Value
Character Data TypecharStores the Single Character Value
Long Data TypelongStores the Long range Integer Value
Double Data TypedoubleStores the long range Floating Value

Explanation :

  1. Whenever we declare variable in Computer’s memory, Computer must know the type of the data to be stored inside the memory.
  2. If we need to store the single character then the size of memory occupied will be different than storing the single integer number.
  3. The memory in our computers is organized in bytes. A byte is the minimum amount of memory that we can manage in C.
  4. 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 TypeBorland C/C++ CompilerVisual C++
Integer2 Bytes4 bytes
Float4 Bytes4 Bytes
Character1 Byte1 Byte
Long4 Byte8 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 :

  1. Size is Specified Directly
  2. 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 :

  1. Create
  2. Push
  3. Pop
  4. Empty

A. Creating Stack :

  1. Stack can be created by declaring the structure with two members.
  2. One Member can store the actual data in the form of array.
  3. 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 :

ConceptDefinition
Stack PushThe procedure of inserting a new element to the top of the stack is known as Push Operation
Stack OverflowAny attempt to insert a new element in already full stack is results into Stack Overflow.
Stack PopThe procedure of removing element from the top of the stack is called Pop Operation.
Stack UnderflowAny 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.

OperatorName 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 BetweenCondition 1Condition 2Final Output
ANDTrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
ORTrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse
NOTTrue-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 -

OperatorMeaning
>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.

OperatorMeaning
==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.

A Variable is a name given to the memory location where the actual data is stored.

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?

  1. Initially 5 is Stored in memory location and name x is given to it
  2. After We are assigning the new value (3) to the same memory location
  3. This would Overwrite the earlier value 5 since memory location can hold only one value at a time
  4. Since the location ‘x’can hold Different values at different time so it is refered as ‘Variable
  5. 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

  1. Now we have declared a variable. (in this case we have declared character variable)
  2. 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)
  3. It’s only declaration so , garbage value inside that address remains the same.

Step 3 : Initialize Variable in C Programming

  1. We have Initialize character variable now.
  2. After initializing value inside that memory block gets overwritten.

Conclusion :

  1. Variable Name always holds a single Value.
  2. Variable Name is user defined name given to Memory Address.
  3. During Second Run , Address of Variable may change.
  4. 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 :

  1. Increment operator is used to increment the current value of variable by adding integer 1.
  2. Increment operator can be applied to only variables.
  3. 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

When Postfix (++) is used with a variable in an Expression ,The Expression is evaluated first using the original value of variable and then variable is incremented by one

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 :

  1. Decrement operator is used to decrease the current value of variable by subtracting integer 1.
  2. Like Increment operator, decrement operator can be applied to only variables.
  3. 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

When Postfix (-) is used with a variable in an Expression ,The Expression is evaluated first using the original value of variable and then variable is decremented by one

Rules for Constructing Integer Number Constant

Rules for constructing Integer constant

NoRuleInteger
1DecimalPoint Not Allowed
2SignPositive or Negative
3Default SignPositive
4No of DigitsAt least 1
5Min Value-32768
6Max Value+32767

Some important Tips :

  1. The range of the integer constant depends on the compiler. The above mentioned range is for 16-bit compiler.
  2. Integer Value does not have decimal point.
  3. Integer Value may be positive or negative. even 0 is also considered as Integer.
  4. Integer Constant Value is assigned to integer variable.
  5. Arithmetic Operations can be performed on Integer Value such as addition,subtraction,multiplication and division.
  6. 2 bytes in memory is allocated for Integer Value

integer_graph1-blue-yellow

Examples of integer constants :

  1. Whole Numbers
  2. 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 :

Constant means “Whose value cannot be changed

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 :

ConstantType of Value Stored
Integer ConstantConstant which stores integer value
Floating ConstantConstant which stores float value
Character ConstantConstant which stores character value
String ConstantConstant 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

DeclarationExplanation
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 -

  1. Where the variable is stored
  2. Scope of Variable
  3. Default initial value
  4. 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 -

In computer programming, a scope is the context within a computer program in which a variable name or other identifier is valid and can be used, or within which a declaration has effect

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 :

  1. Register is used to define Local Variable.
  2. Local Variable stored in Register instead of RAM.
  3. As Variable is stored in Register so Maximum size of variable = Maximum Size of Register
  4. Unary Operator [&] is not associated with it because Value is not stored in RAM instead it is stored in Register.
  5. This is generally used for faster access.
  6. 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]

  1. In the above program we have declared two variables num1,num2. These two variables are stored in RAM.
  2. 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.
  3. 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 :

Keywordregister
Storage LocationCPU Register
Initial ValueGarbage
LifeLocal to the block in which variable is declared.
ScopeLocal to the block.

Why we need Register Variable :

  1. Whenever we declare any variable inside C Program then memory will be randomly allocated at particular memory location.
  2. 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 (&).
  3. If we store same variable in the register memory then we can access that memory location directly without using the Address operator.
  4. Register variable will be accessed faster than the normal variable thus increasing the operation and program execution. Generally we use register variable as Counter.
Note : It is not applicable for arrays, structures or pointers.

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

  1. Array is Static data Structure
  2. Memory Allocated during Compile time.
  3. Once Memory is allocated at Compile Time it Cannot be Changed during Run-time

B. Can hold data belonging to same Data types

  1. Elements belonging to different data types cannot be stored in array because array data structure can hold data belonging to same data type.
  2. 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

  1. 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.
  2. 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

  1. Deletion is not easy because the elements are stored in contiguous memory location.
  2. 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

  1. 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.
  2. Process of Checking the extreme limit of array is called Bound Checking and C does not perform Bound Checking.
  3. If the array range exceeds then we will get garbage value as result.

F. Shortage of Memory

  1. 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.
  2. Shortage of Memory , if we don’t know the size of memory in advance

G. Wastage of Memory

  1. 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 :

  1. Format Specifier %s is used for Accepting String
  2. 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 :

  1. Scanf() needs a pointer to the variable that will store input.
  2. 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.
  3. 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.
  4. 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.
  5. So all you need to do is -
  6. scanf("%s", name);
    

Initializing Array of Structure in C Programming

Initializing Array of Structure in C Programming

  1. Array elements are stored in consecutive memory Location.
  2. 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 TypeDefault Initialization Value
Integer0
Float0.0000
CharacterBlank

Pointer Within Structure in C Programming

Pointer Within Structure in C Programming :

  1. Structure may contain the Pointer variable as member.
  2. Pointers are used to store the address of memory location.
  3. 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;
  1. s1 is structure variable which is used to access the “structure members”.
s1.ptr  = #  
s1.name = "Pritesh"
  1. Here num is any variable but it’s address is stored in the Structure member ptr (Pointer to Integer)
  2. Similarly Starting address of the String “Pritesh” is stored in structure variable name(Pointer to Character array)
  3. 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 :

  1. “ferror” is Macro.
  2. This tests if an error has occurred on a stream or not.
  3. 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 :

  1. If Error has Occurred : Returns [Non Zero Value]
  2. 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 :

TypeIt is Macro Not a function
PurposeTests if an error has occurred on a stream or not
Return ValueNon 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
  1. “++” Operator is pre-increment operator.
  2. Above Statement will increase the value of “length

Example 2 : Incrementing Member

(++ptr)->length
  1. Content of the length is fetched and then ptr is incremented.

Consider above Structure and Look at the Following Table :-

Expression Meaning
++ptr->lengthIncrement the value of length
(++ptr)->lengthIncrement ptr before accessing length
(ptr++)->lengthIncrement ptr after accessing length
*ptr->nameFetch Content of name
*ptr->name++Incrementing ptr after Fetching the value
(*ptr->name)++Increments whatever str points to
*ptr++->nameIncrementing 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

RequirementDeclaration of Function PointerInitialization of Function PointerCalling 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

  1. To pack Several data objects in the single memory word , Bits are used.
  2. Flags can be used in order to store the Boolean values ( T / F ).
  3. 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 :

  1. In the above example, we can say that we have allocated specific number of bits to each structure member.
  2. 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.
  3. 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 :

  1. Create Structure .
  2. Create an array of Structure , Here a[2].
  3. 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
  1. &a[1].num1 - 2004
  2. &a[0].num1 - 2000
  3. 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 :

  1. Struct keyword is used to declare structure.
  2. Members of structure are enclosed within opening and closing braces.
  3. Declaration of Structure reserves no space.
  4. It is nothing but the “ Template / Map / Shape ” of the structure .
  5. 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

  1. 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.
  2. 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.
  3. Ideally Structure is collection of different variables under single name.
  4. Basically Structure is for storing the complicated data.
  5. 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 :

  1. Each member declared in Structure is called member.
char name[64];
char course[128];
int age;
int year;

are some examples of members.

  1. Name given to structure is called as tag
student
  1. 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 :

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 :

  1. Binary Files Contain Information Coded Mostly in Binary Format.
  2. Binary Files are difficult to read for human.
  3. Binary Files can be processed by certain applications or processors.
  4. Only Binary File Processors can understood Complex Formatting Information Stored in Binary Format.
  5. Humans can read binary files only after processing.
  6. 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 :

  1. Executable Files
  2. Database files