echo '' ;

Category Archives: Programming Language

C – Coding Standard

If you writing a code it should be understand by anyone also. Generally developers follows the codding standards. Different different company are following different different coding standers as per they need. You can follow some standard structure for all your usage.

Read more… →

C Library – string.h

The C Library string.h provides various functions for handling strings in C programming. It includes functions for string manipulation, comparison, copying, concatenation, and searching. Some commonly used functions in string.h include strlen() for determining the length of a string, strcpy() for copying strings, strcat() for concatenating strings, and strcmp() for comparing strings. Additionally, string.h provides functions for searching for substrings within a string, such as strchr() and strstr(). The library also offers functions for converting strings to other data types and vice versa, like atoi() and itoa(). Overall, string.h is a crucial part of the C standard library, providing developers with efficient and convenient tools for working with strings in C programs. Its functions are widely used in various applications, from basic string manipulation to complex text processing tasks.

Read more: C Library – string.h

String Understanding

  • String is a collection of characters in between the double quotation “.
  • In C language does not have a data type like string, so we can get this from array of characters.
  • Last character of sting should be null characters ‘/0’.
  • Generally compiler will add the null characters when read a string from computer.
  • Dose not appear null characters ‘/0’ when print the string in computer display.
  • Data length is number of characters in the string with null characters.
  • string handling functions strlen() , strcpy()  , strcat()  , strcmp()  , strrev()  , strupr()   , strlwr()  , strrev()  ,
Read more… →
C Programming Language

C – Preprocessor and Macros

Before learning the C macro, you should know about C preprocessor directives in C language. In this post, you can clearly understand the following

  • what preprocess commands are available in C?
  • How do you declare the preprocessor command.?
  • what is a macro?
  • What is the macro syntax?
  • how to declare the macro?
  • how to assign the macro value?
  • how can use the macro function in c.

Here your answer, if you have any doubts please post in doubts about C Preprocessor and Macros.

Read more… →
C Programming Language

C – Operators

Arithmetic +, -, *, /, %
Assignment=
Augmented Assignment+=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
Bitwise Logic~, &, |, ^
Bitwise Shifts<<, >>
Boolean Logic!, &&, ||
Conditional Evaluation: ? :
Equality Testing==, !=
calling functions( ) (function) -Every function has a pair of parentheses ()

 
main() – main is a function. Every function has a pair of parentheses (). Can a program be compiled without main() function?: Yes, it can be but cannot be executed, as the execution requires main() function definition.
increment and decrement++, —
member selection., ->
object sizesizeof
Order relations<, <=, >, >=
reference and dereference& (Address of Operator) – It cannot be used on constants. It cannot be used on a variable that is declared using the register storage class.

, *, [ ]
sequencing,
subexpression grouping( )
type conversion(typename)
Semicolon; (Semicolon) Any C statement always ends with a ;

Arithmetic OperatorsUnary Operators

Binary Operators
Unary Operators – Eg: +5 , -8 .

Binary Operators
X = 5+6; (Addition + Operator)
X = 20-10; (Subraction – Operator
X = 5*3; (Multiplication * Operator)
X = 5/3; (Division / Operator)
X = 5%3; (Modular % Operator) -remainder
Relational OperatorsA>B; (Greater than)
A<B; (lesser than)
A>=B; (Greater than equal to)
A<=B; (Lesser than equal to)
A==B; (equal to)
A!=B; (not equal to)
Logical OperatorA && B; (AND)
A || B; (OR)
!A=A; (NOT)
Increment and Decrements OperatorsIncrement Operator
++x; (pre increments)
x++; (post increments)

Decrements Operator
–x; (pre Decrements)
x–; (post Decrements)
S++; // ++, as it is single machine instruction (INC) internally.(recommended)
S = S+1; // ++, as it wil take two machine cycle internally.(not recommended)
Short hand assignment Operators
conditional operators (Ternary Operator)

C program structure model explanation

main() -functionmain() – main is a function. Every function has a pair of parentheses ()
Can a program be compiled without main() function?
Yes, it can be but cannot be executed, as the execution requires main() function definition.
{} scope or block
A local block is any portion of a C program that is enclosed by the left brace { and the right brace } .
anything between the two braces is contained in a local block.
() function() – function -Every function has a pair of parentheses ()
semicolon : ; Any C statement always ends with a ;
, Comma OperatorComma Operator – can be used to separate two or more expressions
Eg: printf(“hi”) , printf(“Hello”);
& Address of Operator Address of Operator – It cannot be used on constants. It cannot be used on a variable that is declared using the register storage class.

Incremental and Decremental Operators

  • S++; // ++, as it is single machine instruction (INC) internally.(recommended)
  • S = S+1; // ++, as it wil take two machine cycle internally.(not recommended)
Increment OperatorDecrements Operator
++x (pre increments)–x (pre Decrements)
x++ (post increments)x– (post Decrements)

Example:

Code:

#include<stdio.h>
int main()
{
	int a=5, b=6;
	printf("A : %d \n", a);
	printf("B : %d \n\n", b);
	int c = a++ + ++b;
	printf("A : %d \n", a);
	printf("B : %d \n\n", b);

	printf("C : %d \n", c);
	printf("A : %d \n", a);
	printf("C : %d \n", c);
	return 0;
}

Output:

A : 5
B : 6
A : 6
B : 7
C : 12
A : 6
B : 7


Relational Operator

Code-1:

#include <stdio.h>

int main()
{
	int y;
	int x = y ==10; //int x = y == y; or int x = y ;  
	printf("%d",x);
	
	return 0;
}


//Output : 0

Code-2:

#include<stdlib.h>
 
int main()
{
	int x =10;
	x ==10;
	printf("%d",x);
      return 0;
}
//Output : 1

Boolean Operator

  • == Equal
  • != Not equal
  • > Greater than
  • >= Greater than or equal
  • < Less than
  • <= Less than or equal
  • && Logical AND
  • || Logical OR
  • ! Logical NOT

Conditional operators (Ternary Operator)

syntax : expression 1 ? expression 2 : expression 3;

  • Rule
    • if expression 1 is true then expression 2 is executed
    • else expression 1 is false then expression 3 is executed
  • Advantage : Using ?: reduce the number of line codes and improve the performance of application.
  • Example Invalid:In this below example this is an error in this line i>45? return(*P): return (*q); We cannot use return keyword in the terenary operators.
    #include<stdio.h>
    int check (int, int);
    
    int main()
    {
        int c;
        c = check(10, 20);
        printf("c=%d\n", c);
        return 0;
    }
    int check(int i, int j)
    {
        int *p, *q;
        p=&i;
        q=&j;
        i>=45 ? return(*p): return(*q);
    }

  • Example Valid : In this below example a is lesser than b . so the b value
    a= 5;
    b=7;
    a>b?a:b;
  • More examples :
    • Find largest number among 3 numbers using ternary operator

Associativity

Associativity is only needed when the operators in an expression have the same precedence. Usually + and – have the same precedence.

Consider the expression 7 – 4 + 2. The result could be either (7 – 4) + 2 = 5 or 7 – (4 + 2) = 1. The former result corresponds to the case when + and – are left-associative, the latter to when + and – are right-associative.

Usually, the addition, subtraction, multiplication, and division operators are left-associative, while the exponentiation, assignment, and conditional operators are right-associative. To prevent cases where operands would be associated with two operators or no operator at all, operators with the same precedence must have the same associativity.

BIT Operations

Bit OperationsOperator usageExample
Set bitUse the bitwise OR operator (|)aew_value = aew_value | 1<< set_bit
Clear BitUse the bitwise AND operator (&) and NOT operator (~).aew_value = aew_value & (~(1<< set_bit)
Toggle BitUse the XOR operator (^)Use the bitwise AND operator (&) and NOT operator (~).

How do find the status of a particular bit is SET or NOT?

#include <stdio.h>

int main(void)
{
  //How to find the status of a particular bit is SET or NOT?
    int value = 5;
    int n = 2;
    if (value & (1 << (n - 1)))
        printf("SET");
    else
        printf("NOT SET");

    return 0;
}

Print the Multiplication of the given N number?

#include <stdio.h>
#define N 4
int main()
{
    
    printf("Method-1: 1*%d = %d\n",N,(N));
    printf("Method-1: 2*%d = %d\n",N,(N<<1));
    printf("Method-1: 3*%d = %d\n",N,(N<<1)+N);
    printf("Method-2: 3*%d = %d\n",N,(N<<2)-N);
    printf("Method-1: 4*%d = %d\n",N,(N<<2));
    printf("Method-1: 5*%d = %d\n",N,(N<<2)+N);
    printf("Method-1: 8*%d = %d\n",N,(N<<3));
    printf("Method-1: 9*%d = %d\n",N,(N<<3)+N);
    printf("Method-1: 10*%d = %d\n",N,(N<<3)+(N<<1));
    printf("Method-1: 15*%d = %d\n",N,(N<<4)-N);
    printf("Method-1: 16*%d = %d\n",N,(N<<4));
    printf("Method-1: 40*%d = %d\n",N,(N<<5)+(N<<3));
    return 0;
}

OutPut

Method-1: 1*4 = 4
Method-1: 2*4 = 8
Method-1: 3*4 = 12
Method-2: 3*4 = 12
Method-1: 4*4 = 16
Method-1: 5*4 = 20
Method-1: 8*4 = 32
Method-1: 9*4 = 36
Method-1: 10*4 = 40
Method-1: 15*4 = 60
Method-1: 16*4 = 64
Method-1: 40*4 = 160


...Program finished with exit code 0
Press ENTER to exit console.

NEXT

C - Basic
C - Operator
C - Decision making, Branching, Looping
C - Functions
C - Storage Class
C - Extern
C - Array
C - Pointer
C - Memory Allocation
C - Structure
C - Union
C - Structure and Union
C - Macros
C – Preprocessor and Macros
C - File Management
C - Coding Standard
C - Compilers
C - Compiling Process
C File Management
C Library
C Example

C Programming Language

C – Decision Making Branching Looping

This article will discuss “Decision Making Branching Looping in C program”.

Decision Making: This involves using conditions to make choices in code. For example, using an “if” statement to check if a certain condition is true or false, and then executing different blocks of code accordingly.

Branching: Branching is an extension of decision making. It involves creating multiple paths or branches in your code based on different conditions. This often includes using “else if” statements.

Looping: Looping allows you to repeat a certain block of code multiple times. There are different types of loops, but two common ones are “for” and “while” loops.

Read more… →

C Examples – Bitwise Operators

C Bitwise Operators (Can only be used on integrals, no floats, and doubles)

C BitWise Logic Operator

  • & AND
  • | OR
  • ^ XOR
  • ~ ONE’S COMPLEMENT (Unary Operator)
  •  

& AND

x = 193;            /*1100 0001*/
y = x & 0xf0;        /*1111 0000*/
y = 192;            /*1100 0000*/

| OR

x = 193;            /*1100 0001*/
y = x | 0xf0;        /*1111 0000*/
y = 241;            /*1111 0001*/

^ XOR

x = 193;            /*1100 0001*/
y = x ^ 0xf0;        /*1111 0000*/
y = 62;                /*0011 0001*/

~ ONE’S COMPLEMENT (Unary Operator)

x = 193;            /*1100 0001*/
y = ~x;                /*0011 1110*/
y = 62;                /*0011 1110*

Bit-wise Shift

  • << LEFT SHIFT
    x = 193; /*1100 0001*/
    y = x << 2;
    y = 4; /*0000 0100*/
  • >> RIGHT SHIFT
    x = 193;            /*1100 0001*/
    y = x >> 2;
    y = 48;                /*0011 0000*/
  • Example : A = 0101 1000 >>1 Output : 000010000 .
  • Reference Videos:
    1. https://www.youtube.com/watch?v=d0AwjSpNXR
  1. Special Operators


Exercise in C bitwise operators

1) Which is not a bit-wise operator?

  1. &
  2. |
  3. <<
  4. &&

Ans : 4


2) Predict the output of following program.

#include <stdio.h>
int main()
{
    int a=10;
    int b=2;
    int c;
    
    c=(a & b);
    printf("c= %d",c);
    return 0;
}
  1. c= 12   
  2. c= 10
  3. c= 2
  4. c= 0

Correct answer: 3
c= 2

Bitwise AND (&) operator copies bit(s), if they are exist both of the operands. Here, binary of a is “1010” and binary of b is “0010”. Thus, result of expression (a & b) is “0010” which is equivalent to 2 in Decimal.


3) Predict the output of following program.

#include <stdio.h>

#define MOBILE  0x01
#define LAPPY   0x02

int main()
{
    unsigned char  item=0x00;

    item |=MOBILE;
    item |=LAPPY;

    printf("I have purchased ...:");
    if(item & MOBILE){
        printf("Mobile, ");
    }
    if(item & LAPPY){
        printf("Lappy");
    }

    return 1;
}
  1. I have purchased …:
  2. I have purchased …:Mobile, Lappy
  3. I have purchased …:Mobile,
  4. I have purchased …:Lappy

Correct answer: 2
I have purchased …:Mobile, Lappy

Bitwise OR (|) operator copies bit(s), if they are exist either side of the operands (that means if any bit is exist in any operand). Here, binary of Macro MOBILE (0x01) is “0001” and binary of Macro LAPPY (0x02) is “0010”, then result of the expression item |=MOBILE; will be “0001” and second expression item |=LAPPY; will return “0011”. Thus, both conditions (item & MOBILE) and (item & LAPPY) will be true.


4) Predict the output of following program.

#include <stdio.h>

int main()
{
    char var=0x04;

    var = var | 0x04;
    printf("%d,",var);
    var |= 0x01;
    printf("%d",var);
    
    return 0;
}
  1. 8,9
  2. 4,5   
  3. 8,8
  4. 4,4

Correct answer: 2
4,5

Value of var is 0x04 (0100), Consider the expression var = var | 0x04 The OR (|) of 0100, 0100 is 0100, hence value will remain 0100. After the expression var |=0x01, value will be 0101 that is 0x05.


5) Predict the output of following program.

#include <stdio.h>

int main()
{
    char flag=0x0f;

    flag &= ~0x02;
    printf("%d",flag);

    return 0;
}
  1. 13
  2. d
  3. 22
  4. 10

Correct answer: 1
13

Consider the expression flag &= ~0x02 => flag = flag & (~0x02) => flag = 0x0f & (~0x02) => flag = D => flag =13.


6) Consider the given statement:

int x = 10 ^ 2What will be the value of x?

  1. 5
  2. 6
  3. 7
  4. 8

Correct answer: 4
8

XOR operator (^) copies bit(s), if one operand has 1 and other has 0, consider the given truth table:

a       b       (a^b)
_______________________

0       0       0
0       1       1
1       0       1
1       1       0

Here, binary of 10 is “1010” and binary of 2 is “0010”, then the result of statement (10 ^ 2) will be “1000”, which is equivalent to 8 in decimal.


7) Predict the output of following program.

#include <stdio.h>

int main()
{
    int x=10;
    
    x &= ~2;
    printf("x= %d",x);
    
    return 0;
}
  1. x= 10
  2. x= 8
  3. x= 12
  4. x= 0

Correct answer: 2
x= 8

The statement x &= ~2; will clear second bit from the value of 10, binary of x is “1010” and the binary of 2 is “0010”, thus this statement will clear second bit and returns “1000” that is equivalent to 8 in Decimal.


8) Which Bitwise Operator can be used to check whether a number is EVEN or ODD quickly?

  1. Bitwise AND (&)   
  2. Bitwise OR (|)
  3. Bitwise XOR (^)
  4. Bitwise NOT (~)

Correct answer: 1
Bitwise AND (&)

Bitwise AND (&) Operator can be used to check whether a number if EVEN or ODD, consider the statement (num & 1), this statement will return 1 if first bit of the number is High (1) else it will return 0. All ODD numbers have their firs bit 1 and ODD numbers have 0.

Consider the following program:

#include <stdio.h>

int main()
{
    int count;
    
    for(count=1; count<=10; count+=1)
        if(count & 1)
            printf("%2d is ODD number\n",count);
        else
            printf("%2d is EVEN number\n",count);
    
    return 0;
}

Output

 1 is ODD number
 2 is EVEN number
 3 is ODD number
 4 is EVEN number
 5 is ODD number
 6 is EVEN number
 7 is ODD number
 8 is EVEN number
 9 is ODD number
10 is EVEN number

9) Which statement is suitable to check 3rd (count from 0) bit is high (set) or not?

  1. (num & (1<<3))
  2. (num & 0x08)
  3. (num & 0x03)
  4. Both (1) and (2)

Correct answer: 4
Both (1) and (2)

The value of (1<<3) is 8 in Decimal and value of 0x08 is 8 in Decimal, both statements are suitable to check whether 3rd bit of num is High (set) or not.

Consider this program:

#include <stdio.h>

int main()
{
    int num;
    
    printf("Enter an integer number: ");
    scanf("%d",&num);
    
    if(num & (1<<3))
        printf("3rd bit is High (Set)\n");
    else
        printf("3rd bit is Low\n");
        
    return 0;
}

Output

First run:
Enter an integer number: 15 
3rd bit is High (Set) 

Second run:
Enter an integer number: 7
3rd bit is Low

Binary of 15 is: 1111 & Binary of 7 is: 0111, thus in first case 3rd bit is high and in second case 3rd bit is low. [Count from 0]


10) Left shift (<<) and Right shift (>>) operators are equivalent to _____________ by 2.

Choose the correct words…

  1. Multiplication and Division
  2. Division and Multiplication
  3. Multiplication and Remainder
  4. Remainder and Multiplication

Correct answer: 1
Multiplication and Division

Left shift by 1 return the multiplication by 2 and Right shift by 1 return the division by 2.

Consider this program:

#include <stdio.h>

int main()
{
    int num;
    
    printf("Enter an integer number: ");
    scanf("%d",&num);
    
    printf("Multiplication by 2 = %d\n", (num<<1));
    printf("Division by 2 = %d\n",(num>>1));
        
    return 0;
}

Output

Enter an integer number: 100
Multiplication by 2 = 200 
Division by 2 = 50


NEXT of C Bitwise Operators

C – Basic
C – Operator
C – Decision making, Branching, Looping
C – Functions
C – Storage Class
C – Extern
C – Array
C – Pointer
C – Memory Allocation
C – Structure
C – Union
C – Structure and Union
C – Macros
C – Preprocessor and Macros
C – File Management
C – Coding Standard
C – Compilers
C – Compiling Process
C File Management
C Library
C Example

C – Union

In this post, you can learn about what a C union is, its syntax, how to declare a union, and how to initialize union members. If you have any doubts, feel free to mention them in the comments section.

Introduction

union is a keyword, used to create a structure like struct keyword. When we declare a union, memory allocated for a union variable of the type is equal to the memory needed for the largest member of it, and all members share this same memory space

Read more: C – Union

Syntax

union union_name 
{
    data_type_1 member_1;
    data_type_2 member_2; 
};

Declaration :

union union_name 
{
    data_type_1 member_1;
    data_type_2 member_2;
}uv_1,uv_2;

Example-1: C Union Understanding

Predict the output of the above program. Assuming an integer size of 4 bytes and a character size of 1 byte, and no alignment needed.

union test
{
    int x;
    char arr[4];
    int y;
};
 
int main()
{
    union test t;
    t.x = 0;
    t.arr[1] = 'G';
    printf("%s", t.arr);
    return 0;
}

The answer is that “nothing is printed”.

Explanation:

StatementExplanation
union test t;Declares a union variable t of type test.
t.x = 0;Sets the value of x member of union t to 0.
t.arr[1] = 'G';Assigns the character ‘G’ to the second element of the arr member array.
printf("%s", t.arr);Prints the string stored in the arr member of union t.
return 0;Indicates successful termination of the program.

Uses of unions in C

Unions offer versatility and efficiency in memory usage and data representation in C programming.

Use CaseDescription
Memory ConservationUnions allow multiple members to share the same memory location, conserving memory when only one member is needed.
Type ConversionUnions facilitate type punning, enabling conversion between different data types or accessing the same memory location with different interpretations.
Handling Variant DataUnions are suitable for representing variant data structures where different members represent different data types, but only one member is valid at a time.
Bit ManipulationUnions can be used for bit manipulation and manipulation of individual bits within larger data types.
Implementing Tagged UnionsTagged unions combine a discriminant (a tag) with a union, allowing the representation of values from different types while keeping track of their type.
Optimizing Memory LayoutUnions can optimize memory layout in structures by grouping related data fields together, especially when only one field is needed at a time.

Advantages and disadvantages of unions in C

Unions offer flexibility and efficiency in certain scenarios but require careful usage to avoid pitfalls such as type-related bugs and undefined behavior.

AdvantageDisadvantage
Memory ConservationLimited Type Safety: Unions can lead to type-related bugs if not used carefully.
Type ConversionPotential for Misuse: Unions can be misused, leading to undefined behavior.
Handling Variant DataComplex Initialization: Initializing unions with complex types can be challenging.
Bit ManipulationLimited Readability: Code using unions for bit manipulation may be less readable.
Implementing Tagged UnionsAdditional Bookkeeping: Tagged unions may require additional code to manage tags.
Optimizing Memory LayoutPotential for Undefined Behavior: Accessing inactive union members may result in undefined behavior.

Interview questions

These questions cover various aspects of unions in C and can help assess a candidate’s understanding of this concept during an interview.

  1. What is a union in C?
  2. How is a union different from a structure?
  3. How do you declare a union in C?
  4. Can a union contain members of different data types?
  5. What is the size of a union in C?
  6. How do you access members of a union?
  7. What is type punning in the context of unions?
  8. What are the advantages of using unions?
  9. Can you explain the concept of memory conservation using unions?
  10. How do unions facilitate type conversion?
  11. What are the potential pitfalls of using unions?
  12. Can you provide an example of using unions in a real-world scenario?
  13. How does the compiler handle memory allocation for unions?
  14. Can a union have functions as members?
  15. What is the utility of tagged unions and how are they beneficial?

NEXT

C Programming Language

C – Structure

C Structure is the group of heterogeneous data structure which can store data of different data types or Structure is a collection of variables of different types under a single name. 

In the case of array, we can store the data of same data type but what if we have to save data of different data type in structure. Can use single structure name for  more type of data in structure and union. Storage area is not reserved by the compiler to structure definition.

  • Keyword struct  is used for creating a structure.
  • Structure is a user defined data structure.

C Structure Syntax

struct tag_filed_name 
{
    data_type_1 member_1;
    data_type_2 member_2
    .
    .
    .
    data_type_N member_N
}

How to create a structure?

‘struct keyword is used to create a structure. Following is an example.

struct address
{
   char name[50];
   char street[100];
   char city[50];
   char state[20];
   int pin;
};

Rules

  • Use declare semicolon };at end of structure. (Don’t forget the semicolon in  the ending line.)
  • Referencing structure members : struct_var-name . member_variable
  • A structure variable can be assigned to other using =, but cannot be compared with other using ==
  • In Structure bit cant set in float variable.
  • Bit-fields are only part of structs or unions because that’s what the C standard allows

static members can’t allowed in structure

  • In C, struct and union types, we cannot have static members.
  • In C++, struct types are allowed to have static members, but in union cannot have static members in C++ also.
  • The Below C program output is compilation error.
#include<stdio.h>
struct st
{
    int x;
    static int y;
};
 
int main()
{
    printf("%d", sizeof(struct st));
    return 0;
}

How to declare structure variables?

Way 1:

struct struct_name
{
    data_type member_1;
    data_type member_2;
}var_1, var_2;

Way 2 : struct struct_name var_1, var_2;

struct struct_name
 var_1, var_2;

How to initialize structure members?

Note: Structure elements cannot be initialized. When we declare a structure or union, we actually declare a new data type suitable for our purpose. By default, structure member init with a NULL value. It means Zero.

static struct structure_name var-name = 
{
        var_1, var_2,...var_n
};

So we cannot initialize values as it is not a variable declaration but a data type declaration. The below program output is Compilation error.

#include‹stdio.h›
int main()
{
    struct site
    {
        char name[] = "ArunEworld";
        int no_of_pages = 20;
    };
    struct site *ptr;
    printf("%d ", ptr->no_of_pages);
    printf("%s", ptr->name);
    getchar();
    return 0;
}

In a school, we need to store data like name, roll no, address and percentage. But we are able to store only one data type at a time. So, C programming provides a structure data type that can store data of different types such as integer, float, character, etc. In the case of the above school, we can initialize structure as (refer below example)

struct info
{
    char name [10];
    int roll_no;
    char address [10];
    float per;
};

Read/write in Structure variables

  • . (colon) is the member of a structure
  • -> (arrow) is the member of a POINTED TO structure
  • x -> y and (*x).y are both the same

When to user ->  (arrow) operator.?

  • When the structure/union variable is a pointer variable, we use the arrow operator to access structure/union elements.

What is a self-referential structure?

  • We call a structure containing the same structure pointer variable as its element a self-referential structure.

Nested structure [structure with structure]

  • We refer to a structure containing an element of another structure as its member.

Example : School Data Base

The below example explains many things about the structure

  • This below code is the best example for structure array.
/*********************************
Date: 2016-06-04
Authur: Arun
********************************/

#include <stdio.h>
#include <stdint.h>

//The structure used to store the school student details
typedef struct student_Details
{
    uint8_t     Roll_no; 
    const char* studnt_Name;
    uint8_t    Tamil;
    uint8_t    English;
    uint8_t    Maths;
    uint8_t    Science;
    uint8_t    SocialScience;
    
}student_Details;

// Already declared structure can initialize, throw here.
static student_Details Entry[]=
{
  {1, "Arun", 0, 0, 0, 0, 0},
  {2, "Jhon", 0, 0, 0, 0, 0},
  {3, "Raja", 0, 0, 0, 0, 0},
  {4, "Gaurav", 0, 0, 0, 0, 0},
  {5, "Smith", 0, 0, 0, 0, 0},
  {6, "Jothi", 0, 0, 0, 0, 0},
};


//Printing the structure array
void printStudentDetails()
{
    printf("\n\r Total No of stundets : %ld", sizeof(Entry)/sizeof(student_Details));
    
    uint8_t i=0, No_of_students = sizeof(Entry)/sizeof(student_Details);
    
    printf("\n _________________________________________________________");
    printf("\n | ID | Name \t | S1 \t | S2 \t| S3 \t| S4 \t| S5 \t |");
    printf("\n _________________________________________________________");
    while(No_of_students != i)
    {
        printf("\n\r | %d | %s \t | %d \t | %d \t | %d \t | %d \t | %d \t | ",
        Entry[i].Roll_no, 
        Entry[i].studnt_Name, 
        Entry[i].Tamil,
        Entry[i].English,
        Entry[i].Maths,
        Entry[i].Science,
        Entry[i].SocialScience);
        
        i++;
    }
    printf("\n _________________________________________________________");
}

void UpdateStudentRecord(int Rn,int Sb, int Mrk)
{
    if(Sb == 1)     Entry[Rn-1].Tamil= Mrk;
    else if(Sb == 2) Entry[Rn-1].English= Mrk;
    else if(Sb == 3) Entry[Rn-1].Maths= Mrk;
    else if(Sb == 4) Entry[Rn-1].Science= Mrk;
    else if(Sb == 5) Entry[Rn-1].SocialScience= Mrk;
}

void PrintHelperMenu()
{
    printf("\n helper Menu ");
    printf("\n 1 - Print Student record");
    printf("\n 2 - Update the Student Only One subject mark Mark");
}

void helperMenu()
{
    int scanValue;
    
    PrintHelperMenu();
    
    while(1)
    {
        printf("\n");
        
        scanf("%d",&scanValue);
        
        if(scanValue == 2 )
        {
            int Rn,Sb,Mrk;
            
            printf("\n 1 - Tamil, 2 - English, 3 - Maths, 4 - Science, 5 - Social Science.");
            
            printf("\n Enter the Roll No, Subject and Mark : ");
            
            scanf("%d%d%d",&Rn, &Sb, &Mrk);
            
            UpdateStudentRecord(Rn,Sb,Mrk);
            
            printStudentDetails();
            
            PrintHelperMenu();
        }
        else if( scanValue == 1)
        {
            printStudentDetails();
            
            PrintHelperMenu();
        }
    }
}

int main()
{
    helperMenu();
    return 0;
}

Structure Padding

During struct memory allocation, the system adds empty bytes based on the controller/processor type (8/16/32/64 bit), which can lead to memory issues when working with large arrays of data.

Structure Packing

Reduce the amount of memory that your application requires by packing data into structures. This is especially important if you need to store and access large arrays of data.

pack() function can be use to packing the structure memory.

  • Syntax: #pragma pack(parameters)
  • Parameters: 1 – Aligns structure members on 1-byte boundaries, or on their natural alignment boundary, whichever is less.
  • Parameters: 2 – Aligns structure members on 2-byte boundaries, or on their natural alignment boundary, whichever is less.
  • Parameters: 4 – Aligns structure members on 4-byte boundaries, or on their natural alignment boundary, whichever is less.
  • Parameters: 8 – Reserved for possible future use.
  • Parameters: 16 – Reserved for possible future use.

  • Pack() function : Reference Link
  • Reference Link


C Programming Language

C – Memory Allocation

Memory allocation in C refers to the process of reserving memory space during the execution of a program for storing variables or data structures. There are mainly two types of memory allocation in C: stack allocation and heap allocation.

Stack Allocation:

  • Stack allocation is the default method for allocating memory for local variables within functions.
  • Memory allocated on the stack is automatically managed by the compiler.
  • Variables allocated on the stack have a fixed size and are deallocated when they go out of scope, typically when the function exits.
  • Stack memory is limited and generally smaller than heap memory.

Heap Allocation:

  • Heap allocation involves dynamically allocating memory during runtime from the heap, which is a larger pool of memory managed by the operating system.
  • Memory allocated on the heap must be explicitly requested and released by the programmer using functions like malloc(), calloc(), realloc(), and free().
  • Heap memory allows for dynamic data structures like linked lists, trees, and dynamic arrays.
  • Improper use of heap memory can lead to memory leaks or memory fragmentation.

Common memory allocation functions in C:

  • malloc(size_t size): Allocates a block of memory of specified size in bytes and returns a pointer to the allocated memory.
  • calloc(size_t num, size_t size): Allocates an array of elements initialized to zero, with the total size equal to num * size bytes, and returns a pointer to the allocated memory.
  • realloc(void* ptr, size_t size): Resizes the previously allocated memory block pointed to by ptr to the new size specified by size. It may move the memory block to a new location, and the contents of the original block may be copied to the new block.
  • free(void* ptr): Releases the memory block previously allocated by malloc, calloc, or realloc.

Proper memory management is crucial in C programming to prevent memory leaks, segmentation faults, and other memory-related issues. It’s essential to allocate memory dynamically only when necessary and deallocate it when no longer needed to ensure efficient memory usage.

Static Memory allocation

In the case of static memory allocation, memory is allocated at compile time and memory can’t be increased while executing the program. It is used in the array

Dynamic memory allocation

In the case of dynamic memory allocation, memory is allocated at run time and memory can be increased while executing the program. It is used in the linked list.

The following functions are used in Dynamic memory allocation

  • malloc() – allocates a single block of requested memory. It has garbage value initially.
  • calloc()  – allocates multiple blocks of requested memory. It initially initializes all bytes to zero.
  • realloc() – reallocates the memory occupied by malloc()  or calloc()  functions.
  • free()      – free the dynamically allocated memory.


Stack grows upwards or downwards

Write a C code to check whether a stack grows upwards or downwards

void main()
{
	int i=2;
	int j=3;
	
	if(&i > &j)
	{
		printf("stack grown downwards");
	}
	else
	{
		printf("stack grows upwards");
	}
}


Memory Layout & Storage Type understanding

char *getString()
{
   char *str = "Nice test for strings";
   return str;
}
 
int main()
{
   printf("%s", getString());
   getchar();
   return 0;
}

Output: “Nice test for strings”
Explanations:

  • The above program works because string constants are stored in Data Section (not in Stack Section). So, when getString returns *str is not lost.
  • string constants are stored in Data Section (not in Stack Section)
  • static variable and is stored in Data Section,
  • array variables are stored in Stack Section

C – Pointers

A C pointers is a variable that holds the memory address of another variable. Pointer variables are declared using the * operator, and they can point to various data types, including integers, characters, arrays, structures, and even other pointers. Manipulating pointers requires careful handling to avoid issues like memory leaks, dangling pointers, and segmentation faults.

  • int a; // An integer
  • int *a; //A pointer to an integer
  • int **a; //A pointer to a pointer to an integer
  • int a[10]; //An array of 10 integers
  • int *a[10]; //An array of 10 pointers to integers
  • int (a)[10]; //A pointer to an array of 1 integers
  • int (a)(int); //A pointer to a function a that take an integer argument and return an integer
  • int (*a[10]){int); //An array of 10 pointers to functions that take an integer argument and return an integer

Pointer

A pointer is a variable capable of holding the address of another variable. Dereferencing, accomplished with the (*) operator, allows accessing the value of the variable.

  • Syntax : Datatype * variable name ;
  • Syntax example : int *p;
  • Rule : That two variables should be same data type.

Example

Int x=10;

Int *p=&x;

(Or)

Int *p;

p=&x;
  • To access the value of x : printf(“%d ”,p); —> value of x is 10 Or printf(“%d”,(&x)) —->value of x is 10
  • To access addres of x: printf(“%d”,p); —–> address of x is printed Or printf(“%d”,&x);——> address of x
Read more… →
C Programming Language

C – Array

It is very difficult to define more variables’ names when using more data.  So can create a array to solve this difficult(single variable name and more data). If the index of the array size is exceeded, the program will crash. But the modern compilers will take care of this kind of errors. We cannot initialize the size of array dynamically. Constant expression is required. This tutorial about “C Array”

Array Rules

  • only store the same data types in array structures
  • Arrays are always passed by reference
  • Array list should be end expression with semicolon  ; . Otherwise it will show the error.
  •  
  • What is Base address of array??  Eg : a[10] = {0,1,2,3,4,5,6,7,8,9};     // The starting address of the array is called as the base address of the array. Consider the address of the array starts from 101. Here the variable 0(Zero) address is the base address and the base address of the array is 101.
  • When we pass an array as a function argument, the base address of the array will be passed.
  • Array three types
    1. One Dimensional Array
    2. Two Dimensional Array and
    3.  Multi Dimensional Array

One Dimensional Array

When declare one index value is called One dimensional array

Syntax: 

data_type array_name [ size];

  • data_type  – What kind of array data type
  • array_name  – name of the array
  • size  – array size

Syntax Declaration:

  • int a[100];  //Data type- int (2Byte), array_name – ‘a’, size – 100, Memory Occupies- 200 byte (100×2).
  • float s [50];  //Data type- float(4byte), array_name – ‘s’, size – 50, Memory Occupies- 200 byte (50×4).
  • char name[15];  // Data type- char(1byte), array_name – “name”, size – 15, Memory Occupies- 15 byte (15×1).

Declaration : int a[100];

  • Reading : for(i=0; i<100; i++) scanf(“%d”, &a[i]);
  • Writing : for(i=0; i<100; i++) printf(“%d”, a[i]);
  • Memory Representation :

Array initialization Syntax :

Synatx:  data_type array_name [size] = {list_of_values}; 

Examples

  • static int age [3] = {10,20,30};  //its means – a[0]=10; a[1]=20; a[3]=30;
  • static float salary[] = {1000,2200,3300};  //salary[0]=1000; salary[2]=3300;
  • static char a[10] = “ArunEworld”;  //its means – a[0]=’A’; a[1]=’r’; like… a[9]=’d’;

Array initialization with Zero:

When an automatic array is partially initialized, the remaining elements are initialized to 0.

Example-1:

#include<stdio.h>
int main()
{
    int awe[2];
    printf("%d, %d, %d, %d, %d, %d, %d, %d\n", awe[0], awe[1], awe[2], awe[3], awe[4], awe[5], awe[6], awe[7]);
    return 0;
}

/* Output:     0, 0, 0, 0, -467742907, 32525, 0, 0 */

Example-2:

#include<stdio.h>
int main()
{
    int awe[3]={1,2,3};
    printf("%d, %d, %d, %d, %d, %d, %d, %d\n", awe[0], awe[1], awe[2], awe[3], awe[4], awe[5], awe[6], awe[7]);
    return 0;
}

/* Output:     1, 2, 3, 0, 0, -2036674747, 32587, 0 */

Accessing the Array Element

#include<stdio.h>

int main()
{
    int arr_aew[2]={10,2};
    printf("%d\n", 1[arr_aew]);
    return 0;
}

/* Output: 2 */

Other Example Programs

Check this below examples list in this Links

  • C program to Find Smallest & Largest Number of N numbers in Array.c
  • C program to Ascending Order of N numbers in Array.c
  • C program to Descending Order of N numbers in Array.c
  • C program to fine Largest Number and Position of N numbers in Array.c
  • C program to Find Mean and Standard Deviation in Array Element.c

Two Dimensional Array

  • When declare two index value is called two dimensional array
  • Two dimensional arrays can consider as a table. size_1 is row size and size_2 is column size.

Syntax: data_type array_name [ size_1] [size_2];

    • data_type  – What kind of array data type
    • array_name  – name of the array
    • size_1 , size_2 – two dimensional array size

Syntax Declaration:

    • int a[100] [20];  //Data type- int (2Byte), array_name – ‘a’, size_1(row) – 100,size_2(column)-20, Memory Occupies- 200 byte (100×2).

Declaration : int a[10][15];

Reading : for(i=0; i<10; i++) for(j=0; j<15; j++) scanf(“%d”, &a[i][j]); 

Writing : for(i=0; i<10; i++) for(j=0; j<15; j++) printf(“%d”, a[i][j]); 

  • Memory Representation :

Array initialization Syntax : data_type array_name [size_1] [size_2] = {v1, v2,…..vn}; 

Examples

  • static int mark[3][2] = {60,70,80, 35,90,18};  //its means – a[0][0]=60; a[0][1]=70; a[0][3]=30; a[1][0]=35; a[1][1]=90; a[1][2]=18;
  • static mark[3][2] = {{50},{0},{35};  //a[0][0]=50; a[0][1]=50; a[0][3]=0; a[1][0]=0; a[1][1]=35; a[1][2]=35;

Example Programs

  • Two_dimensional_array_read_row_column.c
  • Two_dimensional_array_print_row_column.c
  • Matrix_transpose_using_two_dimensional_array.c
  • Diagonal_elements_using_two_dimensional_array.c
  • Sum_of_diagonal_elements_using_two_dimensional_array.c
  • Sum_of_all_matrix_elements_using_two_dimensional_array.c
  • Add_a_given_matrix_elements_using_two_dimensional_array.c
  • Multiply_matrix_elements_using_two_dimensional_array.c
  • Largest_and_smallest_elements_using_two_dimensional_array.c

Multi Dimensional Array

  • In C, can use 3 or more dimension called as multi dimensional array
  • Multi Dimension limit is based on the compiler

Syntax: data_type array_name [size-1][size_2]….[size_n]; 

  • data_type  – What kind of array data type
  • array_name  – name of the array
  • size  – array size

Example : 

  •  int a[10][10][10];  //Data type- int (2Byte), array_name – ‘a’, size – 2000(10x10x10x2), Memory Occupies- 2000bytes

 

Array disadvantage:

  • One disadvantage of using arrays to store data is that arrays are static structures and therefore cannot be easily extended or reduced to fit the data set.
  • Arrays are also expensive to maintain new insertions and deletions


Exercise

C Program to Find the Number of Elements in an Array

Method 1:

if you know then data type of the array then easily can find out the array elements one if its initialized using sifeof(variable or array name) predefined function.

/* * C Program to Find the Number of Elements in an Array */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
    int array[] = {15, 50, 34, 20, 10, 79, 100};
    int n; 
    n = sizeof(array);
    printf("Size of the given array is %d\n", n/sizeof(int));
    return 0;
}

Method 2 :

if you don’t know then data type of the array then bit difficult to find out the array elements.


Find the size of array

#include <stdio.h>
int main()
{
  int size,i;
  printf("Enter the size of the array list");
 // scanf("%d",&size);
  int Arr[5]={88,97,65,43,77};
  size = 5;
   
  printf("\nBefore Array value\t:\t");
  for(i=0;i<size;i++)
    printf("%d\t",Arr[size]);
  /*
  for(i=0;i<size;i++)
  {
    if(Arr[size]>Arr[size+1])
      
  }
  */
  getchar();
  return 0;
}

Sum of the arrays 10 element

#include<stdio.h>
#include<conia.h>
int main()
{
	int num_array[10];
	int i,sum=0;
	int *ptr;
	printf("\n Enter 10 Elements")
	for(i=0; i<=10; i++)
		scanf("%d", num_array[i]);
	ptr = num_array;
	for(i=0; i<=10; i++)
	{
		sum = sum + *ptr;
		*ptr++;
	}
	printf("\n Sum of the arrays's 10 element : %d", sum);
	return 0;
}

NEXT

C – Basic
C – Operator
C – Decision making, Branching, Looping
C – Functions
C – Storage Class
C – Extern
C – Array
C – Pointer
C – Memory Allocation
C – Structure
C – Union
C – Structure and Union
C – Macros
C – Preprocessor and Macros
C – File Management
C – Coding Standard
C – Compilers
C – Compiling Process
C File Management
C Library
C Example

C Programming Language

C – Storage Class specifiers Extern

  • The extern keyword is used before a variable to inform the compiler that this variable is declared somewhere else.
  • The extern declaration does not allocate storage for variables.
  • Used to resolve the scope of global symbol
  • Eg : Example Using extern in same file
main()
{
    extern int x;  //Tells compiler that it is defined somewhere else
    printf("%d",x);   
}
int x=10;    //Global variable x

Extern Variable Initializer

Extern as global variable initializer

  • The extern keyword variable can be initialize when its global

 

Example : External variable always initialize (Zero) ‘0’

#include "stdio.h"
extern int a;
main(){
    printf("a=%d",a);
    return 0;
}
int a;

/* Output : a=0 */

 

Example : variable initialize in  global variable

#include "stdio.h"
extern int a;
main(){
    printf("a=%d",a);
    return 0;
}
int a =5;

/* Output : a=5 */

 

Example :

#include <stdio.h> 
extern int a;
int main()
{
    void fun();
    printf("\n a=%d",a);
    fun();
    return 0;
}
int a=7;
    
void fun()
{
    printf("\n in fun a=%d",a);
}

/* Output : 
 a=7
 in fun a=7
*/

 

 

Example : variable initialize in  global variable

#include <stdio.h> 
extern int a=5;
int main()
{   
    printf("%d",a);
    return 0;
}

/* Output : 5*/
/* Explanation pritf function print a value as 5. */

 

Example : variable initialize in  global variable

#include <stdio.h> 
extern int a=5;
int main()
{
    void fun();
    printf("\n a=%d",a);
    fun();
    return 0;
}
int a;
    
void fun()
{
    printf("\n in fun a=%d",a);
}

/* Output : 
 a=5
 in fun a=5
*/

 

 

Example : Error while running Linker

#include <stdio.h> 
extern int a;
int main()
{
    printf("\na=%d",a);
    return 0;
}

/* Output : // Error */

/*
  Error[e46]: Undefined external "a" referred in main 
  Error while running Linker 
*/

 

Extern as local variable initializer

  • The extern keyword variable can not be initialize when its local or inside the function. (an initializer is not allowed on a local declaration of an extern variable)

EXample : an initializer is not allowed on a local declaration of an extern variable

#include <stdio.h> 
int main()
{
  extern int a=5;
  printf("%d",a);
  return 0;
}

/* Output */
// Error[Pe2442]: an initializer is not allowed on a local declaration of an extern variable main.c 

 

C Programming Language

C – Basic

Starting with C programming offers great opportunities! Let’s kick things off with a brief overview of the basics to get you started:

Remember, mastering programming requires time and practice, so don’t get discouraged if you face difficulties along the way. Keep coding and experimenting, and you’ll improve over time!

Read more: C – Basic

Get start

  1. Setup your environment: You need a compiler to write and run C programs. Popular choices include GCC (GNU Compiler Collection), Clang, and Visual Studio for Windows. Install one based on your operating system.
  2. Choose a text editor or IDE: You can write C code in any text editor, but using an Integrated Development Environment (IDE) can make your life easier. Some popular options include Visual Studio Code, Atom, Sublime Text, and Eclipse.
  3. Learn the basics: Familiarize yourself with basic C syntax, such as variables, data types, operators, loops (like for and while loops), conditional statements (if-else), functions, arrays, and pointers. These are the building blocks of any C program.
  4. Compile and run: Save your program with a “.c” extension (e.g., hello.c). Open a terminal or command prompt, navigate to the directory containing your program, and compile it using the compiler you installed. For GCC, the command would be: gcc hello.c -o hello This command compiles your code into an executable named “hello”. Then, run the executable: ./hello You should see “Hello, World!” printed to the screen.
  5. Practice: Once you’ve got the basics down, practice writing more complex programs. Try solving small programming challenges or work on projects that interest you.
  6. Learn from resources: There are plenty of online resources, tutorials, and books available to help you learn C programming. Websites like GeeksforGeeks, Tutorialspoint, and the C programming subreddit can be valuable learning resources.
  7. Debugging: Learn how to debug your programs when something goes wrong. Understanding concepts like breakpoints, stepping through code, and reading error messages will be immensely helpful.
  8. Explore more advanced topics: Once you’re comfortable with the basics, you can delve into more advanced topics like memory management, file handling, data structures, and algorithms.

Write your first program

A classic first program is the “Hello, World!” program. It simply prints “Hello, World!” to the screen. Here’s how you can write it:

#include <stdio.h>

int main() {
    printf("Arun E, World!\n");
    return 0;
}

Join a community

Participating in online forums or joining a local programming group can provide support, encouragement, and opportunities to learn from others.

Constants

  • (Two types : Primary, Secondary)
  • When the program execution time constants should not change their value (A constant is an entity that doesn’t change)
Constant TypeConstant Sub TypeTypeTypeDescriptionExample
Primary ConstantNumeric Constant (Three Type)IntegerDecimalDecimal constants are 0 to 9 numbers86 , 94 , -133
Primary ConstantNumeric Constant (Three Type)IntegerOctalOctal constants are 0 to 7 numbers. First number should be ‘00137 , -0567 , 034
Primary ConstantNumeric Constant (Three Type)IntegerHexadecimalHexadecimal constants are 0 to 9 and A to F. First number should be start with ‘0x’ or ‘0X’0X73A , 0x89FA
Primary ConstantReal or floating point Constant (Two types)Fractional formFractional formdot points are consider as fractional forms-0.567 , .64 , 24.0
Primary ConstantReal or floating point Constant (Two types)

Exponential formExponential formRules: May use mantissa and exponent symbols
Should not use .dot point in exponent
Should have at-least one digit in exponent
0.2571e-5, mantissa – 0.2571, exponent – -5
Primary ConstantCharacter ConstantCharacter ConstantCharacter ConstantCharacter constant are come with two single quotes ()‘A’ – (ASCII-65)
‘O’ – (ASCII-48, EBCDIC-240)
‘a’ – (ASCII-97, EBCDIC-129)
‘z’ – (ASCII-122, EBCDIC-269)
% – (ASCII-37, EBCDIC-108)
Primary ConstantString constantString constantString constantString constant are come with two double quotes ()“ARUN” – Valid
“2020” – Valid
“A” – Valid
“ABC – Invalid
‘sum’ – Invalid
Secondary ConstantArray
Secondary ConstantPointer
Secondary Constantstructure
Secondary Constantunion
Secondary Constantenum

Floating Points

  • floating points may contain . dot point.
  • Rule-1: Should use 0 to 9 numbers.
  • Rule-2: Dot point may come front or back
  • Rule-3: In the case of float numbers, place sign symbols in front of them.
  • Example : 537.36, -158.77

How does the system store a negative integer?

  • Usually, all the negative integers are store in computers in the form of the two’s complement of the same positive integer.
  • Eg: 1011 (-5) Step-1 − One’s complement of 5: 1010, Step-2 − Add 1 to above, giving 1011, which is -5.

Character Set

Typecharacter set
Alphabets A, B, …. Y, Z a, b, …. y, z
Digits0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Special symbols~ `! @ # $ % ^ & * ( ) _ - + = | \ { } [ ] : ; ” ’ < > , . ? /
White spaceBlank space, Horizontal tab, Carriage return, New line , Form feed.

Reserved Keywords

C89 Reserved Keywords

According to C89 standards c has 32 reserved keywords

autodogotosignedunsigned
breakdoubleifsizeofvoid
caseelseintstaticvolatile
charenumlongstructwhile
constexternregisterswitch
continuefloatreturntypedef
defaultforshortunion

Enum:

  • Enumeration (or enum) represents a user-defined data type in C. It primarily assigns names to integral constants, making programs easier to read and maintain
  • --  or ++  are can’t be done on enum value.

C99 Reserved Keywords

According to C99, C has 5 more reserved keywords

  • _Bool
  • _Complex
  • _Imaginary
  • inline
  • restrict

C11 Reserved Keywords,

According to C11, C has 7 more reserved keywords

  • _Alignas
  • _Alignof
  • _Atomic
  • _Generic
  • _Noreturn
  • _Static_assert
  • _Thread_local

Identifiers

Rules

  • Should not use keyword as a identifier.
  • First letter should be English word.
  • May use Uppercase and Lowercase letters.
  • Can use _ underscore as a first letter of Identifier.
  • Identifiers are case sensitive(below both identifiers are not same)

Example

  • Valid Identifiers: Sum, basic_pay, a1, Ab, ab.
  • Invalid Identifiers: 8a – First letter should not be numbers, auto auto is a keyword

Variables

  • When the program execution time variable may be change their value.(A variable is an entity that does change),
  • Example: Sum , average , basic_pay , basic-pay , A0 etc (valid variables)
  • Generally variables are store in different storage class types : automatic , static , extern , register

Declaring a variable

Rules

  • should be declared data type of variable.
  • data types name should be declared data type’s
  • if declare multiple variables in a single data type, separate each by, operator
  • Every declaration should end with ; semicolon

Syntax

  • datatype variable_1, variable_2, …..variable_n ;
  • Example-1: int a, b , c; //here a,b, c are integer variables
  • Example-2: float salary; //here salary is a floating type variable.

Use of variable declaration

  • Compiler can allocate a memory when we declared data type variable

Variable Initializing

  • Syntax: datatype variable_name = initial value;
  • Example: int sum = 1;

Assigning Value to Variable

Assigning Operator = equal is used to assign value to variable in

  • Syntax for value : Variable_name = value; Ex: x = 20;
  • Syntax for another variable: variable_name = variable; Ex: y = x;
  • Syntax for expressions: variable_name = expression; Ex: z = x+y;

Exercise

Q : Which of the following is not a valid variable name in C?
A. 1 a @
B. a 1 2
C. a b 123
D. a b c 123

Answer: Option A (Explanation: First character must be alphabet).

You cannot print (automagically) the type of a variable in C. Variables and their types are only known at compile time.

At runtime, there is no variables (only locations & values) and almost no types:


Data types

  • Data types in any of the language means that what are the various type of data the variables can have in that particular language.
  • Whenever a variable is declared it becomes necessary to define data type that what will be the type of data that variable can hold.
  • basic datatype: char , int , float and double.
  • type modifier (Qualifier) : short , long , signed and unsigned
  • Rules : Every variable should have any one of the following data type

Typesbit SizeByte SizeRange
char (or)
signed char
81127 to 127
unsigned char810 to 255
int (or)
signed int
162-32,767 to 32,767
unsigned int1620 to 65,535
short int (or)
signed short int
81-127 to 127
unsigned short int810 to 255
long int (or)
signed long int
324-2,147,483,647 to 2,147,483,647
unsigned long int3240 to 4,294,967,295
float3243.4E-38 to 3.4E+38
double6481.7E-308 to 1.7E+308
long double80103.4E-4932 to 1.1E+4932
unsigned sort162

The various general types of data are:

General typeGeneral Sub typeData Type
Number type dataInteger Typeint
Number type dataFloat type (Three Types)Float
Number type dataFloat type (Three Types)double
Number type dataFloat type (Three Types)long double
Character type datachar
String type data
Boolean type databool

C Programming Structure

  • Pr-processor Commands
  • Type definition
  • Function prototype – Declare function type and variable passed to functions
  • Variable – We must have a main function in every c programs
//pre processor command
#include <stdio.h>

//variable type definition ("a" is a variable and integer type)
int a; 

//Function prototype ("Func" is a integer type function name with arguments "a", "b" is a variables integer type)
int Func(int b, int c); 

//main function integer type
int main()
{
	//"E" Local variable integer type
    int E;
	
    C statements;
}


Hello World C program

Code

#include<stdio.h>

void main()
{
 
   printf("ArunEworld");
}

Output : ArunEworld

Note : All the programs are run in gnu gcc of linux.


Escape sequence

Escape sequence is a character constant or string constants, its a non graphical character or printable.

Escape sequenceExample
\a  – alarm character 
\b  – back space 
\f  – form feed 
\n  – new line 
\r  – carriage return

Carriage return is known as cartridge return and often shortened to CR, <CR> or return.

It is a control character or mechanism used to reset a device position to the beginning of a line of text.

It is closed associate with the line feed and newline concepts.
 
\t  – horizontal tab 
\v  – vertical tab 
\\  – back slash 
\?  – question mark 
\’  – single quote 
\”  – double quote 
\000  – character representation

\xbh – character representation
 
\0  – nul character

Difference between ‘/0’  and ‘\0’  in C programming?‘\0’ – Null terminator in array.
 

Header files (Two types)

Predefined Header files

  • Syntax : #include<file_name> (Stored in Specified directories).
  • If a header file is included with in < > then the compiler searches for the particular header file only with in the built in include path.

User defined Header files

  • Syntax : #include “file_name” (Stored in Locally saved programs).
  • If a header file is included with in “ “ , then the compiler searches for the particular header file first in the current working directory, if not found then in the built in include path.

Command Statements

  • /* Commands */ – Commands in paragraph
  • // commands – command in single line

Format specifier

SpecifierDescription
%iCan be used to input integer in all the supported format.
%csingle character
%ddecimal character
%efloating point value
%ffloating point value
%gfloating point value
%hshort integer
%ldlong integer
%ooctal integer
%sstring
%uunsigned decimal integer
%xhexa decimal integer
%pprint the address of the variable
[...] string which may include white spaces

Little Endian & Big Endian

Next Topic

C – Basic
C – Operator
C – Decision making, Branching, Looping
C – Functions
C – Storage Class
C – Extern
C – Array
C – Pointer
C – Memory Allocation
C – Structure
C – Union
C – Structure and Union
C – Macros
C – Preprocessor and Macros
C – File Management
C – Coding Standard
C – Compilers
C – Compiling Process
C File Management
C Library
C Example
C Programming Language

C – File management

File management in the C programming language involves operations related to reading from and writing to files. Here are some key concepts and functions for file management in C:

File Pointers

  • C uses a file pointer to keep track of the current position in a file.
  • FILE is a structure in C that represents a file stream. You declare a pointer to this structure to work with files.
  • Syntax: FILE *filePointer;

File Functions in C

Table File Functions Summary

Opening a File: Fopen() Function

Syntax: fopen(“file_name”,"mode”);

File Modes: generic file handling

  • r – Open an existing file for Read purpose
  • wOpen an existing file for Write purpose
  • a – Open a file for writing in append mode. If file not exist, then create new file.
  • r+ – Open a file for both Read and Write
  • w+ – Opens a file for Read and Write. If a file is not existing it creates one, else if the file is existing it will be over written.
  • a+

File Modes: Binary file handling

  • rb – Read (Binary file)
  • wb – write (Binary file)
  • ab – append (Binary file)
  • rb+
  • wb+
  • ab+
  • r+b – reading (Binary file)
  • w+b – (Binary file)
  • a+b – (Binary file)

Closing a File: fclose() Function

  • After using a file, it’s important to close it using the fclose function.
  • Syntax: fclose(filePointer);

Reading from a File

  • For reading from a file, you use functions like fscanf, fgets, or fread.
  • Syntax: fscanf(filePointer, "%s", buffer); // Read a string

Writing to a File:

  • For writing to a file, you use functions like fprintf, fputs, or fwrite.
  • Syntax: fprintf(filePointer, "Hello, World!\n");

Error Handling:

  • It’s important to check if file operations are successful. The functions usually return NULL on failure.
  • Syntax: if (filePointer == NULL) { // Handle error }

File Positioning:

  • fseek and ftell functions can be used to set the file position indicator and get the current position.

Syntax:

fseek(filePointer, 0, SEEK_SET); // Move to the beginning of the file long position = ftell(filePointer); // Get the current position

Removing a File:

  • The remove function can be used to delete a file.
  • Syntax: remove("example.txt");

These are basic file management operations in C. Remember to always handle errors and close files after using them to avoid data corruption or loss.

NEXT

C – Basic
C – Operator
C – Decision making, Branching, Looping
C – Functions
C – Storage Class
C – Extern
C – Array
C – Pointer
C – Memory Allocation
C – Structure
C – Union
C – Structure and Union
C – Macros
C – Preprocessor and Macros
C – File Management
C – Coding Standard
C – Compilers
C – Compiling Process
C File Management
C Library
C Example
C Programming Language

C – Storage Classes

Storage classes in C determine a variable’s scope, visibility, lifetime, and storage location. They include auto, extern, static, and register. The default initial value varies based on the storage class. Scope defines variable visibility, while lifetime dictates its persistence in memory.

Read more: C – Storage Classes
  • Scope: The extent to which different parts of a program have access to the variable, determining its visibility.
  • Lifetime refers to the duration for which the variable persists in memory, encompassing the allocation and deallocation of its storage. The scope also influences a variable’s lifetime.
  • variable types(Global variable)
Variable TypeLifetimeScope
Global VariableOnly destroyed when the program terminatesOnly the program
Local VariableAllocated memory when entering the function, destroyed when leavingLimited to the function
  • syntax: storage_class_specifier data_type variable_name;
SpecifiersLifetimeScopeDefault Initialize
autoBlock (inside function)BlockUninitialized
registerBlock (stack or CPU register)BlockUninitialized
staticProgramBlock or compilation unitZero
externProgramBlock or compilation unitZero
(none)Dynamic (heap)nilUninitialized

Auto Keyword

A variable declared inside a function without any specified storage class is termed an auto variable.

  • Only usable within functions.
  • Created and destroyed automatically upon function call and exit, respectively.
  • Compiler assigns them garbage values by default.
  • The stack memory stores local variables.
  • By default, every local variable in a function is of auto storage class.

Example:

void f() {
    int i;    // auto variable
    auto int j;   // auto variable
}

Global variable

  • A variable declared outside any function is a global variable.
  • Any function in the program can change its value.
  • initializing
    • int – 0
    • char – \0
    • float – 0
    • double -0
    • pointer – null

Register Keyword

The “register” keyword specifies that local variables are stored in a register for rapid access, particularly for counters. These variables offer quicker access than normal ones, but only a limited number can be placed in registers. While the compiler sees “register” as a suggestion, it ultimately decides. Typically, compilers optimize and determine variable allocation.

Register Note 1:

Attempting to access the address of a register variable results in a compile error. For instance:

int main() {
    register int i = 10;
    int *a = &i; // Compile error
    printf("%d", *a);
    getchar();
    return 0;
}

Register Note 2:

You can use the register keyword with pointer variables. Below is a valid example:

int main() {
    int i = 10;
    register int *a = &i;
    printf("%d", *a); // Output: 10
    getchar();
    return 0;
}

Resistor Note 3:

Register is a storage class, and C prohibits multiple storage class specifiers for a variable. Therefore, you cannot use register with static.

int main() {
    int i = 10;
    register static int *a = &i; // Error
    printf("%d", *a);
    getchar();
    return 0;
}

Register Note 4:

There’s no limit to the number of register variables in a C program. However, the compiler may choose to allocate some variables to registers and others not.


static keyword

  • static means its take only single or same memory.
  • static is initialized only once and remains into existence till the end of program
  • static assigned 0 (zero) as default value by the compiler.
  • A static local variables retains its value between the function call and the default value is 0.
  • If a global variable is static then its visibility is limited to the same source code.
  • Static variables stored in Heap(Not in Stack memory)
  • The following function will print 1 2 3 if called thrice.
  • Example
    • void f() { static int i; ++i; printf(“%d “,i); }
  • In “static int a[20];”, variable “a” is declared as an integer type and static. When a variable is declared as static, it is automatically initialized to the value ‘0’ (zero).

What is a static function?

  • A function prefixed with the static keyword is called a static function.
  • You would make a function static if it should only be called within the same source code or be visible to other functions in the same file.
  • static has different meanings in in different contexts.
  • When specified on a function declaration, it makes the function local to the file.
  • When specified with a variable inside a function, it allows the vairable to retain its value between calls to the function

storage class specifier

  • typedef – typedef is the storage class specifier.
    • It does not reserve the storage.
    • It is used to alias the existing type. Also used to simplify the complex declaration of the type.
  • reference links

volatile

  • The compiler omits optimization for objects declared as volatile because code outside the current scope can change their values at any time.

Advantages and Disadvantages

Storage ClassAdvantageDisadvantage
autoAutomatically allocated and deallocated within functionsGarbage values if not explicitly initialized
registerFaster access due to storage in CPU registersLimited availability of register space; Compiler-dependent
staticPersistent value across function callsGlobal scope may lead to namespace pollution; May increase memory usage
externAllows sharing of variables across multiple filesGlobal scope may lead to namespace pollution

Interview Questions

What are storage classes in ‘C’ language?

  • automatic class
  • static class

How many storage class specifiers in “C” language?

  • auto,
  • register,
  • static
  • extern

How many variables scopes are there in “C” language?

  • Body.
  • Function.
  • Program.
  • File.

NEXT

C Programming Language

C – Functions

In C programming, functions are essential building blocks for organizing and reusing code.

  • Rule: In C, you cannot define a function inside another function.
  • Rule: But you can call a function inside another function.
  • Rule: Functions cannot return more than one value at a time because, after returning a value, control is passed back to the calling function.
  • Any function, including main(), can call itself recursively.
  • C has two kinds of functions User Defined Functions,  Pr-Defined Libarary Functions.
Read more… →
C Programming Language

C – Compilers

Compilers are playing important role in software development. compilers are converting human-written code into another runnable software in machines.

CompilersDescriptions
Microsoft – Visual StudioVisual Studio is a free source from Microsoft. You can download and install from the visual studio side.

Supports in windows (offline).
Bortland   –  Turbo C, Turbo C++Supports in windows(offline).

You can download the portable version from this link
Dev C++Dev C++ compiler not support void in main function, main function should be mention int type and return type.

Supports in windows(offline).

you can download the portable version by here

you can do the debug of program refer the video
Gcc compilerSupport in Linux(offline).
C Compliers
Read more… →
C Programming Language

C Quiz-1

Participating in a C quiz can offer several benefits for individuals looking to improve their programming skills and knowledge of the C programming language. Here are some potential advantages:

  1. Skill Enhancement: Quizzes often cover a range of topics within C programming, allowing participants to test and enhance their skills in areas such as syntax, data types, control structures, functions, and more.
  2. Knowledge Validation: Quizzes can help individuals gauge their understanding of key concepts in C programming. By answering questions, participants can identify areas where they need to focus on improving their knowledge.
Read more… →