C Programming Practical Leaning

C Progamming Language:-

C is a powerful programming language that is used to develop operating systems, databases and more.

Note:- int datatype keep positive and negative value and its size is 4 byte a per c programming language.
Example :-
WAP to take input from user and print it?

#include<stdio.h> //it's used to write(scanf()) and read(prtinf()) 

//#include<math.h> //this library is used to perform math operation such as squre rool and square

//#include<string.h> //This library is used to perform string function such as string copy, move etc.
/*Note :- Here stdio means Standard Input output*/

void main()

{

  int a,b;

  printf("enter value of a & b=> \n");

  scanf("%d\n%d",&a,&b);

  printf("a=> %d\nb=> %d",a,b);

}

 

/*Output:- 

enter value of a & b=> 

-965

+5.6

a=> -965

b=> 5

*/

 

//WAP to swap number without using third variable

#include<stdio.h>

void main()

{

  int a=5,b=10;

  printf("a=> %d\nb=> %d",a,b);

  printf("\nAfter Swaping:- \n");

  a=a+b; //5+10=15

  b=a-b; //5-10=-5 //Always take positive value due to datatype

  a=a-b; //15-5=10

  printf("a=> %d\nb=> %d",a,b);

}

 

/*Output:- 

a=> 5

b=> 10

After Swaping:-      

a=> 10

b=> 5

*/

 

--*******************Structure Beginig***********************************

  • Array and Strings => Similar data( int, float,char)
  • Structures can hold => dissimilar data 

  • Primitive :- Means define already

-> Definition :- It's a user define datatype which is constructed by the help of primitive and derived datatype.

-> It can store more than one value of different types of datatype of different-2 memory location.

-> Used the struct keyword here to define/declare structure.

-> The Size of structure is sum of it's all data member size.

Note :- 1) Always close the structure by using ;(semicolon).

2) The minimum size of structure is 1 byte.

3) The Structure is declared by the help of struct keyword.

  

^^^^^^^^^^^^Pointer with Structure :- 

Arrow operator :- Instead of writing *(ptr).code, we can use an arrow operator to access structure properties as follows

 (*ptr).code or ptr->code

Note:- 


Here -> is known as an arrow operator.


 #include<stdio.h>

//#include<math.h>
#include<string.h>
struct Employee  //define structure
{
  int id;        //4 byte
  char name[15]; //1 byte
  float salary;  // 4 byte
}; e; ///Must end with semicolon //We can declare variable here also
//Implementation of Database
//OR
//struct Employee e;//Global declaration of structure variable and we can initialize also like as below
//struct Employee e={1,'Ram',100000}; //Initialization of structure during the declaration

void main()
{
  struct Employee *ptr=&e; //Ptr contain the addrerss of e gloabal variable which contatain the address of all member of structure
  printf("Enter ID,Name & Salary:-\n");
  scanf("%d\n%s\n%f",&e.id,&e.name,&e.salary);
  //printf("%d\t%s\t%0.2f",e.id,e.name,e.salary);
   printf("%d\t%s\t%0.2f",(*ptr).id,ptr->name,(*ptr).salary);
}
/* Output:-
If we keep *ptr->id then It'll through error for *:-
Test.c: In function 'main':
Test.c:16:14: error: invalid type argument of unary '*' (have 'int')
   16 |   scanf("%d",*ptr->id);

Result :-

Enter ID,Name & Salary:-
45
Gopal
89000
45      Gopal   89000.00
*/

Date:- 14/03/2022

#include<stdio.h>

//Twenty integers are to be stored in memory. What will you prefer- Array or Structure?

void main()

{

  int array[20];

  printf("Enter twenty Integer:- \n");

  for(int i=0;i<20;i++)

  {

    scanf("%d\n",&array[i]);

  }

  printf("\nTwenty Integregs are:-\n");

  for(int i=0;i<20;i++)

  {

    if(i==9)

    {

      printf("%d\n",array[i]);

    }

    else

    {

       printf("%d\t",array[i]);

    }   

  }

}

/*

Result:- 

Enter twenty Integer:- 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18 

19

20

21


Twenty Integregs are:-

1       2       3       4       5       6       7       8       9       10

11      12      13      14      15      16      17      18      19      20

*/

#include<stdio.h>
#include<string.h>
//Write a program to illustrate the use of an arrow operator -> in C.
struct student
{
  int id;
  char name[50];
  float marks;
};
struct student s;
void main()
{
  struct student *ptr=&s;
  printf("Enter Student Infomation:- \n");
  scanf("%d\n%s\n%f",&s.id,&s.name,&s.marks);


  printf("\nStudent Deatils as below :- \nId:- \t%d\nName:- \t%s\nMarks:- %.2f\n",(*ptr).id,ptr->name,ptr->marks);
}
/*
Result:-
Enter Student Infomation:-
4
Mohan
60

Student Deatils as below :-
Id:-    4
Name:-  Mohan
Marks:- 60.00
*/


^^^^^^^^^^^^Array of Structures in C

Declaring an array of structure is same as declaring an array of fundamental types. Since an array is a collection of elements of the same type. In an array of structures, each element of an array is of the structure type.

Let's take an example:

struct Employee

{

  int id;        //4 byte

  char name[15]; //1 byte

  float salary;  // 4 byte

};

Here is how we can declare an array of structure Employee.

struct Employee e[0];//Here [0] means single row (id,name and salary can store and It's not a size of total member or element of strcture array

Visit for more information:- https://overiq.com/c-programming-101/array-of-structures-in-c/ 


-----------------print assign value and input value by using array of structure :- 

#include<stdio.h>

//#include<math.h>

#include<string.h>

struct Employee  //define structure

{

  int id;        //4 byte

  char name[15]; //1 byte

  float salary;  // 4 byte

}; ///Must end with semicolon

void main()

{

  struct Employee e[]={200,"Ram",5000}; //call structure

  printf("Maximin size of structure is %d byte\n",sizeof(e));

  printf("\n1st Employee Details:-");

  printf("\nID     :- %d\nName   :- %s\nSalary :- %.2f\n",e[0].id,e[0].name,e[0].salary);

  printf("\n*******Enter 2nd Employee Details :-");

  for(int i=0;i<1;i++) //here 1 is for 1 row 

  {

    printf("\nEnter ID:- ");

    scanf("%d",&e[i].id);

 

    printf("Enter Name:- ");

    scanf("%s",&e[i].name);

 

    printf("Enter Salary:- ");

    scanf("%f",&e[i].salary);

  }

  printf("\n*******2nd Employee Details :- ");

  for(int i=0;i<1;i++)

  {

    printf("\nID     :- %d\nName   :- %s\nSalary :- %.2f\n",e[i].id,e[i].name,e[i].salary);

  }

}

/* Output:- 

Maximin size of structure is 24 byte

 

1st Employee Details:-

ID     :- 200

Name   :- Ram

Salary :- 5000.00

 

*******Enter 2nd Employee Details :-

Enter ID:- 600

Enter Name:- Krishna

Enter Salary:- 10000

 

*******2nd Employee Details :- 

ID     :- 600

Name   :- Krishna

Salary :- 10000.00

*/

==================Table Implementation:- 

#include<stdio.h>

//#include<math.h>

#include<string.h>

struct Employee  //define structure

{

  int id;        //4 byte

  char name[15]; //1 byte

  float salary;  // 4 byte

}; ///Must end with semicolon

//Implementation of Database

void main()

{

  int i=0;

  struct Employee e[2]; 

  for(i=0;i<2;i++) //here 2 for 0 &1 (total 2 rows) Input will accept

  {

    printf("\nEnter %d Employee Information :-\n",i+1);

    printf("Enter ID:- ");

    scanf("%d",&e[i].id);

 

    printf("Enter Name:- ");

    scanf("%s",&e[i].name);

 

    printf("Enter Salary:- ");

    scanf("%f",&e[i].salary);

  }

  printf("\n\nEmployee Table\n");

  printf("SN\tID\tName\tSalary\n"); //Used \t for tab space apply 

  for(i=0;i<2;i++)

  {

    printf("%d\t%d\t%s\t%.2f\n",i+1,e[i].id,e[i].name,e[i].salary);

  }

}

/* Output:- 

Enter 1 Employee Information :-

Enter ID:- 100

Enter Name:- Ram

Enter Salary:- 85000

 

Enter 2 Employee Information :-

Enter ID:- 200

Enter Name:- Krunal

Enter Salary:- 90000

 

 

Employee Table

SN      ID      Name    Salary  

1       1       Ram     45000.00

2       2       Krishna 60000.00

 

Explaination:- 

e[0].id : refers to the id member of the 0th element of the array.

e[0].name : refers to the name member of the 0th element of the array.

e[0].salary : refers to the salary member of the 0th element of the array.

 

e[1].id : refers to the id member of the 1th element of the array.

e[1].name : refers to the name member of the 1th element of the array.

e[1].salary : refers to the salary member of the 1th element of the array.

*/

==================

-----------------

 

//Structure Begining :-Quick Quiz: Write a program to store the details of 3 employees from user-defined data. Use the structure declared above.

#include<stdio.h>

#include<math.h>

struct Employee  //define structure

{

  int id;        //4 byte

  char name[15]; //1 byte

  float salary;  // 4 byte

}; ///Must end with semicolon

void main()

{

  printf("\nStructure Begining:- \n");

  struct Employee e; //call structure

  printf("Maximin size of structure is %d byte\n",sizeof(e));

  printf("\nEnter Employee Details:-ID,Name and Salary\n");

    //scanf("%d\n%s\n%f",&e.id,&e.name,&e.salary);

  //OR

  e.id=101;

  strcpy(e.name,"Suraj");

  e.salary=75000;

  printf("ID     :- %d\nName   :- %s\nSalary :- %.2f",e.id,e.name,e.salary);

}

 

/*

Structure Begining:-

Maximin size of structure is 24 byte

 

Enter Employee Details:-ID,Name and Salary

9

XYZ

5689.385578 

ID     :- 9      

Name   :- XYZ    

Salary :- 5689.39

 

 

Structure Begining:-

Maximin size of structure is 24 byte

 

Enter Employee Details:-ID,Name and Salary

ID     :- 101

Name   :- Suraj   

Salary :- 75000.00

*/

 

-------

//Structure Begining

#include<stdio.h>

#include<math.h>

#include<string.h>

struct Employee  //define structure

{

  int id;        //4 byte

  char name[15]; //1 byte

  float salary;  // 4 byte

}; ///Must end with semicolon

void main()

{

  struct Employee e[2]={200,"Ram",5000}; //call structure

  printf("Maximin size of structure is %d byte\n",sizeof(e));

  printf("\nEnter Employee Details:-ID,Name and Salary\n");

  for(int i=0;i<1;i++)

  {

    printf("\nID     :- %d\nName   :- %s\nSalary :- %.2f",e[i].id,e[i].name,e[i].salary);

  }

}

 

/*Output:- 

Maximin size of structure is 48 byte

 

Enter Employee Details:-ID,Name and Salary

 

ID     :- 200

Name   :- Ram

Salary :- 5000.00

*/

 

--*******************************************************************************

Slice() using array calling by uinsg function 

#include<stdio.h>  

#include<string.h> //Declare hader file

void sliceArray(int a[]);

int main()

{

     int i=0,n,a[n],val[n]; 

     printf("Enter size of array: ");

     scanf("%d",&n);

     for(i=0;i<n;i++)

     {

        scanf("%d", &a[i]);

     }

     printf("\nElements in array are: ");

     for(i=0;i<n;i++)

     {

       if(i==n-1)

       {

           printf("%d.", a[i]);

       }

       else{

         printf("%d, ", a[i]);  

       }       

     }

    sliceArray(a);

    return 0;    

}

void sliceArray(int a[])

{

     int m,n;

     printf("\nEnter First & Last Index: ");

     scanf("%d %d",&m,&n);

     printf("Elements in array are: ");

     for(int i=m-1;i<=n-1;i++)

     {

       printf("%d  ", a[i]);

     }

 }

 

 

/* 

Output:- 

Enter size of array: 4

1

2

3

6

 

Elements in array are: 1, 2, 3, 6.

Enter First & Last Index: 2 3

Elements in array are: 2  3

*/

----

#include<stdio.h>

#include<string.h>

/*Write a function slice() to slice a string. 

It should change the original string such that it is now the sliced strings. 

Take m and n as the start and ending position for slice.

*/

void main()

{  

   char s[11],store[11];

   int n,m,i=0;

   printf("Enter string:- "); 

   gets(s);  

   for(int i=0;i<strlen(s);i++)

   {

       printf("s[%d]=>%c\n",i,s[i]);

   }

 

   printf("/nEnter start and End number:- ");

   scanf("%d\n%d",&n,&m);

 

   for(i=0;i<strlen(s);i++)

   {

       while(n<=m)

       {

           i=n-1;

           store[i]=s[i];

           printf("%c",store[i]);

           n++;

       }      

   }

 

}

 

 

/* 

Output:- 

Enter string:- Krishna

s[0]=>K

s[1]=>r

s[2]=>i

s[3]=>s

s[4]=>h

s[5]=>n

s[6]=>a

/nEnter start and End number:- 1

5

Krish

*/

---------------------------

#include<stdio.h>

#include<string.h>

//Write a program to searches for the character in a particular string then Fater found character it's appeart all the string after search..

//Write a program to check whether a given character is present in a string or not.

void main()

{  

 

    char str[]={};

    //char search[]="Sai";  

    printf("Enter a string:- ");

    gets(str);

    printf("Seach string[%c] is %s\n",'s',strchr(str,'s'));   

}

/*

Output:- 

Enter a string:- Jai sai ram Sainath

Seach string[s] is sai ram Sainath

*/

-

---------------------    

#include<stdio.h>

#include<string.h>

/*

Write a program to encrypt a string by adding 1 to the ASCII value of its characters.

Write a program to decrypt the string encrypted using the encrypt function in problem 6.

*/

void main()

{  

    char str[100];

    int n;

    printf("Enter a string:- ");

    gets(str);

    printf("Plain Text is %s",str);

    printf("\nEnter key to perform following options:-\n");

    printf("Enter 1 for Encryption\nEnter 2 for Decryption\n"); 

    scanf("%d",&n);

    printf("you choose number is %d",n);

    switch(n)

    {

        case 1:

        printf("\nEncrypted Text is ");

        for(int i=0;i<str[i];i++)

        {

            str[i]=str[i]+3;

            printf("%c",str[i]);

        }

        break;

 

        case 2:

        printf("\nDecrpted Text is ");

        for(int i=0;i<str[i];i++)

        {

            str[i]=str[i]-3;

            printf("%c",str[i]);

        }

        break;

    }

}

/*

Output:- 

Enter a string:- Suraj

Plain Text is Suraj

Enter key to perform following options:-

Enter 1 for Encryption

Enter 2 for Decryption

2

you choose number is 2

Decrpted Text is Pro^g

PS E:\C_Programming> .\a.exe

Enter a string:- Pro^g

Plain Text is Pro^g

Enter key to perform following options:-

Enter 1 for Encryption

Enter 2 for Decryption

1

you choose number is 1 

Encrypted Text is Suraj

*/

================================================  

  printf("The ASCII Value of Characte\n");

    for( int i = 0; i<str[i]; i++)

    {

        printf("str[%d]=> %c  = %d\n",i, str[i],str[i]);

    }

    printf("\nEnter String is ");

    for( int i = 0; i<str[i]; i++)

    {

        printf("%c",str[i]);

    }

    printf("\nEncryption is :- ");

    for( int i = 0; i<str[i]; i++)

    {

        printf("%c",str[i]+1);

    }

    Ouptut:-

    /*

    The ASCII Value of Characte

str[0]=> S  = 83

str[1]=> u  = 117

str[2]=> r  = 114

str[3]=> a  = 97

str[4]=> j  = 106

 

Enter String is Suraj      

Encryption is :- TRvts

    */ 

------------------

#include<stdio.h>

#include<string.h>

//Write a program to count the occurrence of a given character in a string.

void main()

{  

    char s1[10];

    int count=0;

    printf("Entere string here:- ");

    gets(s1);

    printf("length of enter string is %d\n",strlen(s1));  

    printf("\nString => ");

    for(int i=0;i<strlen(s1);i++)

    {

        if(s1[i]=='a')

        {

            count++;

        }

        printf("%c",s1[i]);        

    }  

 

    printf("\nCharacter a occarance count is %d",count);

}

/*

Output:- 

Entere string here:- Ram Ram

length of enter string is 7

 

String => Ram Ram

Character a occarance count is 2

*/

 

==================

#include<stdio.h>

#include<string.h>

//Write your own version of strcpy function from <string.h>

void copy();

void main()

{  

 copy();

}

void copy()

{

    char s1[]={};

    char s2[]={};

    printf("Enter s1:- ");

    gets(s1);

    printf("Values are:-\ns1 => %s\ns2=> %s",s1,s2);

    printf("\n\ncopy s1 value to s2 which is %s",strcpy(s2,s1));

    printf("\nValues are:- \ns1 => %s\ns2=> %s",s1,s2);

}


/*

Output:- 

Enter s1:- Jai Sai Ram

Values are:-     

s1 => Jai Sai Ram

s2=> Jai Sai Ram 

 

copy s1 value to s2 which is Jai Sai Ram

Values are:- 

s1 => Jai Sai Ram

s2=> Jai Sai Ram 

*/

---------------------------------------------

#include<stdio.h>

#include<string.h>

//Write your own version of strlen function from <string.h>

void len();

void main()

{  

 char s1[1];

 len();

}

void len()

{

    char s1[]={};

    printf("Enter String:- ");

    gets(s1);

    printf("Value of s1 is %s",s1);

    printf("\nLength of s1 is %d",strlen(s1));

}

/*

Output:- 

Enter String:- Jai Shree Krishna

Value of s1 is Jai Shree Krishna

Length of s1 is 17

*/

===============================

#include<stdio.h>

#include<string.h>

//Write a program to take a string as an input from the user using %c and %s. Confirm that the strings are equal.

void main()

{  

 char s1[1];

 char s2[2];

 printf("Enter s1:- ");

 gets(s1);

 printf("s1=> ");

 puts(s1);

 

 printf("\nEnter s2:- ");

 for(int i=0;i<1;i++)

 {

  //scanf("%c",&s2[i]); \\It's working with printf("%c",s2[i]);  need to keep loop 3 time to store 3character and s2[i]

  scanf("%s",&s2); //It's working with printf("%c",s2[i]); then Need to Keep loop 1 one

  //printf("%c",s2[i]);

 } 

 for(int i=0;i<1;i++)

 {

  //printf("%c",s2[i]);

  printf("%s",s2);//printoutput as per the take input in first loop

 } 

 printf("\nLength of S2 is %d",strlen(s2));

 printf("\nLenght of s1 is %d",strlen(s1));

}

/*

Output:- 

Case 1:- 

Enter s1:- JaiSaiRam

s1=> JaiSaiRam

 

Enter s2:- JaiSaiRam //If we enter allthree together than provide first output

Jai

Length of S2 is 4

Lenght of s1 is 0

 

Case 2:- If We enter three time input for s2 then It print last capture input as output:- 

Enter s1:- JaiSaiRam

s1=> JaiSaiRam

 

Enter s2:- Jai

Sai

Ram

Ram

Length of S2 is 4

Lenght of s1 is 0

 

Case 3:- 

Enter s1:- JaiSaiRam

s1=> JaiSaiRam

 

Enter s2:- Jai

Jai

Length of S2 is 4

Lenght of s1 is 0

*/

 

 

====================

#include<stdio.h>

#include<string.h>

void main()

{  

 char s1[]="5Ram";

 char s2[]="A";

 char s3[]="A"; 

 printf("s1=> %s\ns2=> %s\ns3=> %s",s1,s2,s3);

 printf("\nCompare s1 & s2:- %d",strcmp(s1,s2));

 printf("\ncompare s2 & s3:- %d",strcmp(s2,s3));

}

output:=

s1=> Ram

s2=> A

s3=> A

Compare s1 & s2:- 1

compare s2 & s3:- 0

//Create a three-dimensional array and print the address of its elements in increasing order.

#include<stdio.h>

void main()

{  

  int a[2][3]={1,2,3,4,5,6};

  printf("Value is :- \n");

  for(int i=0;i<2;i++)

  {

    for(int j=0;j<3;j++)

    {

      printf("%d \t%u",a[i][j],&a[i][j]);  

    }  

    printf("\n");               

  }

}

/*

Write a program containing a function that reverses the array passed to it.

*/

#include<stdio.h>

void main()

{

  int a[5];//={1,2,3,4,5};

  printf("Enter 5 number to get reverser order:- \n");

  for(int i=0;i<=4;i++)

  {

     scanf("%d\n",&a[i]);

  }

  for(int i=0;i<5;i++)

  {

    printf("a[%d]=> %d\n",i,a[i]);

  }

 

  printf("\nReverser Output:- \n");

  for(int i=4;i>=0;i--)

  {

    printf("a[%d]=> %d\n",i,a[i]);

  }

 

}

/*

Repeat problem 7 for a custom input given by the user.

*/

 

#include<stdio.h>

void main()

{  

  int a[2][10],k=1,m=1,n1,n2;

  printf("Enter n1 number for table:- \n"); 

  scanf("%d %d",&n1,&n2);

  printf("Table of %d, & %d are \n",n1, n2);

  for(int i=0;i<2;i++)

  {

    for(int j=0;j<10;j++)

    {

      if(i==1)

      {

        while(k<=10)

        {

          a[i][j]=n2*k;

          printf("%d  ",a[i][j]);        

          k++;

        } 

      }

      else

      {

        while(m<=10)

        {

          a[i][j]=n1*m;

          printf("%d  ",a[i][j]);        

          m++;

        } 

      }                  

    }

    printf("\n");

  }

}

 

Outpout:-

Enter n1 &n2 number for table:- 

5

6

Table of 5, & 6 are 

5  10  15  20  25  30  35  40  45  50  

6  12  18  24  30  36  42  48  54  60 

 

===

void main()

{  

  int a[10],n1=1,n2;

  printf("Enter first number for table:- \n"); 

  scanf("%d",&n1);

  printf("\nTable  is :- \n");

  for(int i=1;i<=10;i++)

  {

    a[i]=i*n1;

    printf("%d ",a[i]);

  }

}

==

 

 

/*

Create a three-dimensional array and print the address of its elements in increasing order.

A 3D array is a multi-dimensional array(array of arrays). A 3D array is a collection of 2D arrays. It is specified by using three subscripts:

array[Block size][row size][column size]

*/

#include<stdio.h>

 

void main()

{  

  int a[3][3][3]={

                    {

                        {7,4,1},

                        {2,5,8},

                        {9,6,3}

                    },

                    {

                        {1,2,3},

                        {4,5,6},

                        {7,8,9}

                    },

                    {

                        {5,4,6},

                        {8,7,9},

                        {2,3,1}

                    }

                  };

  for(int i=0;i<3;i++)

  {

    for(int j=0;j<3;j++)

    {

      for(int k=0;k<3;k++)

      {

        printf("%d |",a[i][j][k]);

      }  

       printf("\n");        

    }

     printf("--------------------\n");    

  }

}

 

 

 

 

 

 

 

 

/*

Repeat problem 7 for a custom input given by the user.

*/

#include<stdio.h>

 

void main()

{  

  int a[1][10],n,k=1;//={{2,4,6,8,10,12,14,16,18,20}};  --Incomplete

  printf("Enter n number for table:- \n"); 

  scanf("%d",&n);

  printf("\nTable is :-\n");

  for(int i=0;i<1;i++)

  {

    for(int j=0;j<10;j++)

    {

      while(k<=10)

      {

        if(k==10)

        {

          a[i][j]=n*k;

          printf("%d.",a[i][j]);

          break;

        }

        else

        {

         a[i][j]=n*k;

         printf("%d,  ",a[i][j]);

        }

        k++;

      }  

      break;              

    }

    printf("\n");

  }

}

 

Output:- 

Table is :-

7,  14,  21,  28,  35,  42,  49,  56,  63,  70.

/*

Create an array of size 3x10 containing multiplication tables of the numbers 2,7 and 9, respectively.

*/

#include<stdio.h>

 

void main()

{  

  int a[3][10]={

 {2,4,6,8,10,12,14,16,18,20},

 {7,14,21,28,35,42,49,56,63,70},

 {9,18,27,36,45,54,63,72,81,90}

  };

  for(int i=0;i<3;i++)

  {

    for(int j=0;j<10;j++)

    {

      if(a[i][j]==20 || a[i][j]==70 || a[i][j]==90)

      {

        printf("%d.",a[i][j]);

      }

      else

      {

        printf("%d, ",a[i][j]);

      }       

    }

    printf("\n");

  }

}

 

Output:-

2, 4, 6, 8, 10, 12, 14, 16, 18, 20.

7, 14, 21, 28, 35, 42, 49, 56, 63, 70.

9, 18, 27, 36, 45, 54, 63, 72, 81, 90.

 

 

 

 

 

/*

//Write a program containing functions that counts the number of positive integers in an array.

*/

#include<stdio.h>

 

void main()

{  

  int a[10]={-1,2,-3,4,-5,6,7,-8,9,-10}, count=0;

  for(int i=0;i<10;i++)

  {

    printf("a[%d] => %d\n",i,a[i]);

  }

 

  for(int i=0;i<10;i++)

  {

    if(a[i]>0)

    {

      count=count+1;

    }

  }

  printf("\nPositive Integer count is %d\n",count);

}

 

Output:- 

a[0] => -1

a[1] => 2

a[2] => -3

a[3] => 4

a[4] => -5

a[5] => 6

a[6] => 7

a[7] => -8

a[8] => 9

a[9] => -10

 

Positive Integer count is 5

 

 

 

 

 

 

 

/*

Repeat problem 3 for a general input provided by the user using scanf()

*/

#include<stdio.h>

void main()

{

  int S[10]={1,2,3,4,5,6,7,8,9,10}, n;

  printf("Enter number for table=> ");

  scanf("%d",&n);

  for(int i=0;i<10;i++)

  {

    printf("%d*%d=>  %d\n",S[i],n,S[i]*n);

  }

}

 

Ouput:- 

Enter number for table=> 12

1*12=>  12

2*12=>  24

3*12=>  36

4*12=>  48

5*12=>  60

6*12=>  72

7*12=>  84

8*12=>  96

9*12=>  108

10*12=>  120

 

 

/*

Write a program to create an array of 10 integers and store a multiplication table of 5 in it.

*/

#include<stdio.h>

void main()

{

  int S[10]={1,2,3,4,5,6,7,8,9,10};

  for(int i=0;i<10;i++)

  {

    printf("%d*5=>  %d\n",S[i],S[i]*5);

  }

}

Output:- 

1*5=>  5

2*5=>  10

3*5=>  15

4*5=>  20

5*5=>  25

6*5=>  30

7*5=>  35

8*5=>  40

9*5=>  45

10*5=>  50

 

 

 

/*

If S[3] is a 1-D array of integers, then *(S+3) refers to the third element:

True

False 

Depends

*/

#include<stdio.h>

void main()

{

  int S[3]={10,9,8};

  for(int i=0;i<3;i++)

  {

    printf("Index S[%d]=> %d & => %u\n",i,S[i], &S[i]);

  }

  printf("*(S+3) is %d",*(S+3)); 

}

 

Output:- 

Index S[0]=> 10 & => 467662496

Index S[1]=> 9 & => 467662500

Index S[2]=> 8 & => 467662504

*(S+3) is 3

 

Ans is false;

 

//Create an array of 10 numbers. Verify using pointer arithmetic that (ptr+2) 

//points to the third element where ptr is a pointer pointing to the first element 

//of the array.

 

#include<stdio.h>

void main()

{

  int a[10]={10,9,8,7,6,5,4,3,2,1}, *ptr;

  ptr=&a[0];

  for(int i=0;i<10;i++)

  {

    printf("Index a[%d]=> %d & => %u\n",i,a[i], &a[i]);

  }

  printf("Value of ptr=&a[0] is %u",ptr);

  printf("\nAddress of &ptr is %u",&ptr);

  printf("\nValue of ptr before ptr+2 is %d",*ptr);

  ptr=ptr+2;

  printf("\n\nValue of ptr after ptr+2 is %d",*ptr);

  printf("\n\nValue of ptr=&a[0] is %u",ptr);

  printf("\nAddress of &ptr is %u",&ptr);  

}

 

Output:-

Index a[0]=> 10 & => 2178939968

Index a[1]=> 9 & => 2178939972

Index a[2]=> 8 & => 2178939976

Index a[3]=> 7 & => 2178939980

Index a[4]=> 6 & => 2178939984

Index a[5]=> 5 & => 2178939988

Index a[6]=> 4 & => 2178939992

Index a[7]=> 3 & => 2178939996

Index a[8]=> 2 & => 2178940000

Index a[9]=> 1 & => 2178940004

Value of ptr=&a[0] is 2178939968

Address of &ptr is 2178939960

Value of ptr before ptr+2 is 10

 

Value of ptr after ptr+2 is 8

 

Value of ptr=&a[0] is 2178939976

Address of &ptr is 2178939960

 

==================

input:- 

//Multidimension array:-

#include<stdio.h>

void main()

{

  int a[2][3];

 printf("Enter a Value of Array for 2 rows and 3 column :- \n");

 for(int i=0;i<2;i++)  

 {

   for(int j=0;j<2;j++)

   {

     scanf("%d",&a[i][j]);

   }

   printf("\n");

 }

 

 printf("\nTow Dimension Array is :- \n");

 for(int i=0;i<2;i++)  

 {

   for(int j=0;j<2;j++)

   {

     printf("a[%d][%d] => %d   ",i,j,a[i][j]);

   }

   printf("\n");

 }

}

 

Output:- 

Enter a Value of Array for 2 rows and 3 column :- 

4 5

 

8 7

 

 

Tow Dimension Array is :-

a[0][0] => 4   a[0][1] => 5

a[1][0] => 8   a[1][1] => 7

  

 

//Multidimension array:-

#include<stdio.h>

void main()

{

  int a[2][3]={ 

                {5,6,7},

                {8,9,4} 

              };

 for(int i=0;i<2;i++)

 {

   for(int j=0;j<2;j++)

   {

     printf("a[%d][%d] => %d   ",i,j,a[i][j]);

   }

   printf("\n");

 }

}

 

Output:- 

a[0][0] => 5   a[0][1] => 6   

a[1][0] => 8   a[1][1] => 9   s

==========================

#include<stdio.h>

void main()

{

  int *ptr, arr[]={9,6,8}; 

  ptr=&arr[0];

  printf("Value of\narr[0] & arr[1] & arr[2] are :- \n");

  printf(" %d,  %d,  %d\n",arr[0],arr[1],arr[2]);

 

  printf("\nAddress of\narr[0] and arr[1] & arr[2] are :- ");

  printf("\n%u, %u, %u",&arr[0],&arr[1],&arr[2]);

 

  printf("\n\nvalue of ptr=&arr[0] is %u",ptr);

  printf("\nvalue of *ptr id %d",*ptr);

  printf("\nAddress of &ptr is %u",&ptr);

  ptr++;

  printf("\n\n**********After ptr ++*********\n");

  printf("\nAddress of &ptr is %u",&ptr);

  printf("\nValue of ptr++ is %u",ptr);

  printf("\nvalue of *ptr id %d",*ptr);

 

  ++ptr;

  printf("\n\n**********After ++ptr*********\n");

  printf("\nAddress of &ptr is %u",&ptr);

  printf("\nValue of ++ptr is %u",ptr);

  printf("\nvalue of *ptr id %d",*ptr);

 

 

}

 

output:- 

Value of

arr[0] & arr[1] & arr[2] are :- 

 9,  6,  8

 

Address of

arr[0] and arr[1] & arr[2] are :- 

2768240076, 2768240080, 2768240084

 

value of ptr=&arr[0] is 2768240076

value of *ptr id 9

Address of &ptr is 2768240088

 

**********After ptr ++*********

 

Address of &ptr is 2768240088

Value of ptr++ is 2768240080

value of *ptr id 6

 

**********After ++ptr*********

 

Address of &ptr is 2768240088

Value of ++ptr is 2768240084

value of *ptr id 8

 

 

-----------------------------------

#include<stdio.h>

void main()

{

  int *ptr, arr[]={9,6}; 

  ptr=&arr[0];

  printf("Valur of arr[0] is %d",arr[0]);

  printf("\nAddress of  of arr[0] is %u",&arr[0]);

  printf("\nvalue of ptr is %u",ptr);

  printf("\nvalue of *ptr id %d",*ptr);

  ptr++;

  printf("\n\nValur of arr[1] is %d",arr[1]);

  printf("\nAddress of  of arr[1] is %u",&arr[1]);

  printf("\nValue of ptr++ is %u",ptr);

  printf("\nvalue of *ptr id %d",*ptr);

}

 

output:- 

Valur of arr[0] is 9

Address of  of arr[0] is 4175427840

value of ptr is 4175427840

value of *ptr id 9

 

Valur of arr[1] is 6

 

 

-------------- *********************************************************** Note :- a[size]=Here size means how many number you have to store according to it you will have to give size

Address of  of arr[1] is 4175427844

Value of ptr++ is 4175427844       

value of *ptr id 6

 

================

#include<stdio.h>

#include<stdlib.h>

void main()

{

 int arr[]={1,2,3,4};

 //printf("arr[0] =%d\narr[1] =%d\narr[2] =%d\narr[3] =%d\narr[4]= %d\narr[5]= %d",arr[0],arr[1],arr[2],arr[3],arr[4],arr[5]);

 //printf("size of int=> %i\nfloat => %d\nchar=> %d\ndouble=> %d\n\n", sizeof(int),sizeof(float),sizeof(char),sizeof(double));

 int temp=0;

 for(int i=0;i<4;i++)

 {    

    printf("arr[%d] => %d and Address is %u\n",i,arr[i],&arr[i]);    

    temp=temp+1;    

 }

 printf("Size of array is %d",temp);

}

 

Output:- 

arr[0] => 1 and Address is 3363830688

arr[1] => 2 and Address is 3363830692

arr[2] => 3 and Address is 3363830696

arr[3] => 4 and Address is 3363830700

Size of array is 4

 

 

 

 

===

#include<stdio.h>

 

//Addition, comparision and substractin  of Number through pointer  

 

void main()

{

 int a=15,b=30, *i,*j,**k;

  i=&a;

  j=&b;

  printf("value of variable a and b are %d, & %d",a,b);

  printf("\nAddress of variable &a and &b are%u, & %u",&a,&b);

  printf("\nValue of pointer i and j are %u, & %u",i,j);

  printf("\nValue of pointer *i and *j are %d, %d",*i,*j);

  printf("\na+b =>  %d",*i+*j);

  printf("\na-b =>  %d\n\n",*i-*j);

  if(*i>*j)

  {

   printf("%d is greater than %d",*i,*j);

  }

  else

  {printf("%d is greater then %d",*j,*i);}

}

 

 

 

 

 

//Pointer increment checking

#include<stdio.h>

 

void main()

{

 int a=5, *i;

  i=&a;

  printf("value of variable a is %d",a);

  printf("\nAddress of variable &a=%u",&a);

  printf("\nValue of pointer i is %u",i);

  printf("\nAddress of pointer &i is %u",&i);

  printf("\nValue of pointer *i is %d",*i);

  printf("\n*(&i) is %d",*(&i));

  printf("\n\n******************After i++\n");

  i++;

 

  printf("\nValue of pointer i is %u",i);

  printf("\nAddress of pointer &i is %u",&i); 

  printf("\nValue of pointer *i is %d",*i);

  printf("\n *(&i) is %d",*(&i));

  

   i++;

  printf("\n\n&&&&&&&&&&&&&&&&&&&&&& After i++ ^^^^^^^^^^^^^^^^\n");

  printf("\nValue of pointer i is %u",i);

  printf("\nAddress of pointer &i is %u",&i); 

  printf("\nValue of pointer *i is %d",*i);

  printf("\n*(&i) is %d",*(&i));

 

}

 

Output:- 

value of variable a is 5

Address of variable &a=3477076108  

Value of pointer i is 3477076108   

Address of pointer &i is 3477076096

Value of pointer *i is 5

*(&i) is -817891188

 

******************After i++        

 

Value of pointer i is 3477076112   

Address of pointer &i is 3477076096

Value of pointer *i is 1

 *(&i) is -817891184

 

&&&&&&&&&&&&&&&&&&&&&& After i++ ^^^^^^^^^^^^^^^^

 

Value of pointer i is 3477076116

Address of pointer &i is 3477076096

Value of pointer *i is 0

*(&i) is -817891180  

 

 

 

 

 

Size of variable as per the type :- 

 

/*

//Write a program to accept marks of five students in an marks and print them to the screen

*/

#include<stdio.h>

 

void main()

{

   //It's mendatory to specify the size otherwise It's throw error to specify the size of array. 

   //OR 

   //Initialze the array during the declaration/ Initialization means value assign

 

   int k1;

   float k2; //4 byte

   char k3;

   int marks[]={1,2,3,4,5,6,7,8,9,10};//Array declaration

   printf("Size of int k is %d byte and address is %u",sizeof(k1),&k1);

   printf("\nSize of float k is %d byte and address is %u",sizeof(k2),&k2);

   printf("\nSize of char k is %d byte and address is %u",sizeof(k3),&k3);

}

 

//output:- 

Size of int k is 4 byte and address is 3602906012

Size of float k is 4 byte and address is 3602906008

Size of char k is 1 byte and address is 3602906007

 

Note :- Int arr[3]={1,2,3}      => 1 integer = 4 bytes

 

 

////////////////////////////////////////////Array==========================================================

//marks

/*

//Write a program to accept marks of five students in an marks and print them to the screen

*/

#include<stdio.h>

 

void main()

{

    

   int marks[5];//Array declaration and it's mendatory to specify the size otherwise It's throw error to specify the size of array.

   printf("Enter value into marks :- \n");

   for(int i=0;i<=5;i++)

   {

       scanf("%d",&marks[i]); // take input into array and configure the loop as per the size of array

   }

   for(int j=0;j<=4;j++)

   {

       printf("Value of marks[%d] is %d\n",j,marks[j]);

   }

 

}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`

//increment and decrement depend on the type of pointer.

 

#include<stdio.h>

 

void main()

{

  void* val = 0xffffffff;

 

    printf("d = %d\n", val);

    printf("u = %u\n", val);

    printf("p = %p\n", val);

}

 

/*

output:- 

%d will show a negative value for addresses with the most significant bit set (high addresses)

%u will always show the positive interpretation of the bits

%p is the best, since it's explicitly reserved for printing addresses.

=>

d = -1

u = 4294967295

p = 00000000ffffffff

*/

 

//////////////////////

#include<stdio.h>

 

void main()

{

  int a=5,*b;

  b=&a;

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

  printf("\naddress of a is %d",&a);

  printf("\naddress of a is %u",a);

  printf("\nValue of b pointer variable is %p",b);

  printf("\nValue of b pointer variable is %u",b); //%u is used to display the address but in %d also get the same number because both give the interger type value and address is number type

}

 

output:- 

Value of a is 5

address of a is 1629486612

address of a is 5

Value of b pointer variable is 000000ee611ffe14

Value of b pointer variable is 1629486612

[Done] exited with code=42 in 1.545 seconds

 

//Write a program to print the value of a variable i by using the "pointer to pointer" 

//type of variable.

#include <stdio.h>  

 

int main()  

{  

    int a=10,*b,**c; 

    b=&a;

    c=&b;  

    printf("Value of a=> %d",a);

    printf("\nAddress of &a=> %d",&a);

    printf("\nValue of b=> %d",b);

    printf("\nAddress of &b=> %d",&b);

    printf("\nValue of c is: %d",c); 

    printf("\nValue of *c=> %d",*c);

    printf("\nValue of **c=> %d",**c);

}  

 

/*Write a program using a function that calculates the sum and average of two numbers. 

Use pointers and print the values of sum and average in main().

*/

#include<stdio.h>

#include<math.h>

 

void cal(int a,int b);//Function declaration with two Parameters 

 

void main()  //Main Function 

{  

  int i=11,j=45; //Argument

  cal(i,j); //call by value :- pass value of argument to function

}

 

void cal(int i,int j) //Function Definition

  printf("Value of Variables is \ni=> %d, & j=>%d",i,j);

  printf("\n\nsum is %d",i+j);

  printf("\nAverage is %.2f \n\n",((float)i+(float)j)/2);

}

 

Note :- To display decimal number after point the use the "%.2f" in printf statements.

 

/*Write a program having a variable i. Print the address of i. Pass this variable to a 

function and print its address. Are these addresses same? Why?

*/

#include<stdio.h>

 

void fun(int a); //Parameter

 

void main()

{

  int i=9; //Argument

  printf("Address of Variable i=> %d",&i);

  fun(i); //call by value 

}

 

void fun(int i)

{

  printf("\nvalue of argument is %d",i);

  printf("\n\nAddress of i inside function) is  %d",&i);

}

#include<stdio.h>

void main()

{

  int *ptr, arr[]={9,8,5,7,4},i=1;  

 while(i<=5)

 {

   ptr=&arr[i]; 

   printf("Value of ptr is %u and value is  %d\n",ptr, *ptr);

   i++;

 }

  

}

 

//Reason:- Parameter of fun in main() it's changed that why address is not same.

 

//Write a program to print the address of a variable. Use this address to get the value of this variable.

#include<stdio.h>

 

void main()

{

  int i=7, *j;

  j=&i;

  printf("Address of Variable i=> %d",&i);

  printf("\nAddress of Variable j=> %d",&j);

  printf("\nValue of Variable i=> %d",i);

  printf("\nValue of Variable *(&j)=> %d",*(&j));

}

 

//WAP to swap the number in c language.

#include<stdio.h>

void swap(int x,int y);

void main()

{

  int a=5,b=9; //arument 

  printf("Before Swap=>\na=> %d\nb=> %d",a,b);

  swap(a,b);//call by value:- assign value of argument to function 

}

 

void swap(int a,int b) //fucntion reutrn only one value that why useing the void type of function 

{

  int temp;

  temp=a;

  a=b;

  b=temp;

  printf("\nAfter Swap=>\na=> %d\nb=> %d",a,b);        

}

 

 

 

/// check the pointer basic :- 

 int i=5;

 printf("&i=> %u",&i); //printf address of i 

 printf("\ni=>%u",i); //value of i assing to i

 printf("\n*(&i)=>%u",*(&i)); //value of address of i

 

void main()

{

 int i=5;

 printf("&i=> %d",&i); //printf address of i 

 printf("\ni=>%d",i); //value of i assing to i

 printf("\n*(&i)=>%d",*(&i)); //value of address of i

}

 

//Write a program using recursion to calculate the nth element of the Fibonacci series.

 

#include<stdio.h>

 

void main()

{

  int temp=0,n1=0,n2=1,i=0;

  printf("%d,%d,",n1,n2);

  while(i<=10)

  {

    temp=n1+n2;

    printf("%d,",temp);

    n1=n2;

    n2=temp;

    i++;

  }

}

//Write a function to convert Celcius temperature into Fahrenheit.

/*

c=5/9(F-32)

F=9/5*C+32

*/

 

#include<stdio.h>

#include<math.h>

 

float celsius(float f);

 

void main()

{

  float c;

  printf("Enter Celsius value=> ");

  scanf("%f",&c);

  printf("%f 'f",celsius(c));

}

 

float celsius(float c)

{

  return floorf(3.08125*c);

}

 

 

 

 

//Write a program using functions to print the following pattern(first n lines):

/*

*

 

***

 

*****

 

*/

 

#include<stdio.h>

 

void main()

{

  for(int i=1;i<=5;i++)

  {

    if(i%2 !=0)

    {

      for(int j=1;j<=i;j++)

      {

        printf("*");

      }

      printf("\n\n");

    }    

  }

}

//Write a program using functions to print the following pattern(first n lines):

/*

*

 

***

 

*****

 

*/

 

#include<stdio.h>

 

int sum(int );

 

void main()

{

  for(int i=1;i<=5;i++)

  {

    if(i==3)

    printf("*\n\n");

    if(i==3)

    {

        for(int j=1;j<=3;j++)

        {

          printf("*");

        }

        printf("\n\n");

    }

 

     if(i==3)

    {

      int j=1;

        while(j<=5)

        {

          printf("*");

          j++;

        }

        printf("\n");

    }

 

  }

}

 

 

 

 

*********************************************************************Functions**************************************************************

//Write a recursive function to calculate the sum of first n natural numbers.

 

#include<stdio.h>

 

int sum(int );

 

void main()

{

  int n;

  printf("\nEnter a Number=> ");

  scanf("%d",&n);

  printf("sum of nth number is => %d",sum(n));

}

 

int sum(int n)

{

  int temp=0;

  if(n==1)

  return 1;

  else

  temp=n+sum(n-1); //Function calling it's self called recursion function

  return temp;

}

 

//output:- 2 2 0

 

//What will the following line produce in a C program: printf(“%d %d %d\n”,a,++a,a++);

 

#include<stdio.h>

 

void main()

{

 int a;

 printf("%d %d %d\n",a,++a,a++);

}

 

output:- 2 2 0

 

==================

//Write a program using functions to find the average of three numbers.

 

#include<stdio.h>

float avg(float a,float b,float c);

 

void main()

{

  float x,y,z,result;

  printf("Enter any 3 number=> ");

  scanf("%f%f%f", &x, &y, &z);

  result=avg(x,y,z);

  printf("%f",result);

}

 

float avg(float a,float b, float c)

{

  return (a+b+c)/3;

}

==================

-------------------------------------Factorial using Function:- 

#include<stdio.h>

//Function to calculate factorial 

 

int factorial(int );

 

void main()

{

  int n;

  printf("Enter Number to get factorial=> ");

  scanf("%d",&n);

   

  printf("\n",factorial(n));

}

 

int factorial(int n)

{

  printf("\nFactorial of number is :-");

  for(int i=1;i<=n;i++)

  {

    if(n%i==0)

    {

      if(n==i)

      {

        printf("%d.",i);

        break;

      }

      else

      {

        printf("%d, ",i);  

      }         

    }

  }

  return 0;

}

 

Note Function call itself called reursion function and calling called recursive function.

 

 

-------------------------------------

==============

#include<stdio.h>

//program to calculate the area of the square

int msg();

 

void main()

{

  int result;

  result=msg();

  printf("Area of Square is %d",result);

}

 

int msg()

{

  int a;

  printf("Enter the Number => ");

  scanf("%d,",&a);

  return a*a;

}

 

OR

 

//program to calculate the area of the square

int msg(int,int );

 

void main()

{

  int k,j;//It's mendatory to at least declare the function parameter in main function

  printf("Area of Square is %d",msg(k,j));

}

 

int msg(int a,int b)

{

  printf("Enter the Number => ");

  scanf("%d\n%d",&a,&b); //we can define input fuction in main() also then Need to return calculated result from the function.

  return a*b;

}

 

OR

 

#include<stdio.h>

//program to calculate the area of the square

int msg(int,int );

 

void main()

{

  int k,j;//It's mendatory to at least declare the function parameter in main function

  printf("Enter the Number => ");

  scanf("%d\n%d",&k,&j);

  printf("Area of Square is %d",msg(k,j));

}

 

int msg(int a,int b)

{

  return a*b;

}

==============

#include<stdio.h>

/*

Quick Quiz: Write a program with three functions,

 

Good morning function which prints "Good Morning."

Good afternoon function which prints "Good Afternoon."

Good night function, which prints "Good night."

main() should call all of these in order 1 - 2 - 3

*/

 

//function prototype/declarations

void goodmorning(); 

void goodafternoon();

void goodnight();

 

void main()

{

  //function calling

    goodmorning();

    goodafternoon();

    goodnight();

}

 

//function definitions

void goodmorning()

{

  printf("Good Morning");

}

 

void goodafternoon()

{

  printf("\nGood Afternoon");

}

 

void goodnight()

{

  printf("\nGood Night");

}

===============================================================

#include<stdio.h>

 

void main()

{

  int i=2,flag=1,n;

  printf("Enter any number=> ");

  scanf("%d",&n);

  while(n>1) //2>1 true, 3>1

  {

    if(i<=n-1) //2<=1 false, 2<=2

    {

      flag=0;

    }

    i++;

  }

  if(flag==1)

  {

    printf("Prime Number is %d",n);

  }

  else

  {

    printf("%d is not prime number",n);

  }

}

/*

=================================================

#include<stdio.h>

#include<stdlib.h>

//#include<time.h>

  /*

Problem: This is going to be fun!!  We will write a program that generates a random number and asks the player to guess it. If the player’s guess is higher than the actual number, the program displays “Lower number please.” Similarly, if the user’s guess is too low, the program prints “Higher number please.”

When the user guesses the correct number, the program displays the number of guesses the player used to arrive at the number.

 

Hints:

 

Use loops

Use a random number generator.

  */

 

void main()

{

   int guessnum, randam,i;

   randam=rand()%100+1;  

   printf("Randam number is %d",randam); 

 do

 {

   printf("\nGuess the number Between 1 to 10=>");

   scanf("%d",&guessnum);

 

   if(guessnum>randam)

   {

     printf("\nPlease enter lower number");

   }

 

   else if(guessnum<randam)

   {

     printf("\nPlease enter higer number");

   }

 

   else //guessnum == randam

   {

      printf("\nyou guessed it and attempt %d round",i);

   }

   i++;

 } while (guessnum != randam);

}

 

=================================================

Factorial and Prime Number :- 

#include<stdio.h>

 

void main()

{

  int flag=1,n;

  printf("Enter any number to check prime=> ");

  scanf("%d",&n);

  if(n>1)

  {

    for(int i=2;i<=n-1;i++)

    {

      if(n%i==0)

      {

        flag=0;

      }

    }

    if(flag==1)

    {

      printf("%d is prime number",n);

    }

    else

    {

      printf("%d is not prime number",n);

      printf("\n Factorial of %d is as below :- ",n);

      for(int j=1;j<=n;j++)

      {

        if(n%j==0)

        {

          if(n==j)

          {

            printf("%d.",n);

            break;

          }

          else

          {

            printf("%d, ",j);

          }

          

        }

      }

    }

  }

  else

  {

    printf("Prime Number Should be greater than 1");

  }

}

====================================

 

//Prime Number Program:- 

#include<stdbool.h>

#include<stdio.h>

 

bool flag=true;

  int n,i=2;

  printf("Enter number :- ");

  scanf("%d",&n);

  if(n>1)

  {

    while(i<= n-1)

    {

     if(n%i==0)

     {

       flag=false;

     }

     i++;

   }

 }

  else

  {

    printf("Prime Number should be greater than 1");

  } 

  if(flag==true)

  {

    printf("Prime Number is %d",n);

  }

  else

  {

      printf("%d is not Prime Number",n);

  }

In factorial:- to find out the factorial of number can not be greater than of the factorial number

 

 //Write a program to calculate the factorial of a given number using for loop.

 int n;

 printf("Enter No to findout the factorial number=> ");

 scanf("%d",&n);

 printf("Factorial of Number %d is ",n);

 for(int i=1;i<=n;i++)

 {

    if(n%i==0)

    {

       printf("\n%d",i);

    }

 }

 

 //Write a program to calculate the sum of the numbers occurring in the multiplication table of 8.(Consider 8x1 to 8x10)

 int temp=0,t=0;

 

 for(int i=1;i<=10;i++)

 {  

   printf("%d ",i*8);

   temp=temp+(i*8);

 }

 printf("\nTotal Sum of multiplication of 8 is %d",temp);

 

}

 

//Write a program to sum the first ten natural numbers using a while loop.

  int temp=0;

  int i=0;

 do

 {

   temp=temp+i;

   i++; 

 }  while (i<=10);

 

   printf("Total sum of number 1 to 10 is %d",temp);

 

//Write a program to sum the first ten natural numbers using a while loop.

  int temp=0;

  for(int i=1;i<=10;i++)

  {

      temp=temp+i;

  }

  printf("Total sum of number 1 to 10 is %d",temp);

 

//Write a program to print a multiplication table of 10 in reversed order

 int n=10;

 printf("Enter number to find table=> \n");

 printf("Table of %d is :- \n",n);

 for(int i=10;i;i--)

 {

    printf("%d \n",i*n);

 }

 

//Write a program to print the multiplication table of a given number n. 

 int n;

 printf("Enter number to find table=> ");

 scanf("%d",&n);

 printf("Table of %d is :- \n",n);

 for(int i=1;i<=10;i++)

 {

    printf("%d \n",i*n);

 }

*/

/*

 //Didn't find the output of the below code :- 

  int skip=5;

 int i=0;

 while(i<10)

 {

     if(i != skip) //0/1/2/3/4/5 != 5

     continue; //i++

     else

     printf("%d",i);

 }

 

 

 //Write a program to print first n natural numbers using for loop.

   int n;

   printf("Enter Number to get asc order=> ");

   scanf("%d",&n);

 

    for(int i=1; i<=n; i++)

    {

        printf("%d ",i);

    }

  output:- Enter Number to get asc order=> 6

  1 2 3 4 5 6

    --------------------------------------OR 

     for(int i=1; i<=1000; i++)

    {

        printf("%d ",i);

        if(i==5)

        {

            break;

        }

    }

    output:- 1 2 3 4 5

*/

 

/*

 //Write a program to print n natural numbers in reverse order.

    int n;

    printf("Enter Number to get reverse order=> ");

    scanf("%d",&n);

 

    for(int i=n; i; i--)

    {

        printf("%d ",i);

    }

    output:- Enter Number to get reverse order=> 8

    8 7 6 5 4 3 2 1 //It'll not print til 0 because may be by default It's taking till 1 not 0 but maually we can specify compare condition 

*/

 Write a program with a structure representing a Complex number

#include<stdio.h>
#include<string.h>
//Write a program with a structure representing a Complex number.
/*
A complex number is a number that can be written in the form x+yi 
where x and y are real numbers and i is an imaginary number.

Therefore a complex number is a combination of:
real number.
imaginary number.

Representation of complex numbers in C
In C language, we can represent or can work on complex numbers by using

I) structure, a C feature
II) <complex.h> library

Example:

struct complex
{
    int real, imag; 
};
CCopy
here, struct is a keyword for creating a structure and complex is the name of the structure.
real is variable to hold the real part and imag is a variable to hold the imaginary part.
real and imag can be of any data type (int, float, double).
*/
struct complex
{
  double real, img;
};
struct complex c1,c2,result;
void main()
{
  printf("Enter 1st Complex Number:- \n");
  scanf("%lf\n%lf",&c1.real,&c1.img);
  printf("1st Complex Number is :- %.2lf%+.2lfi",c1.real,c1.img);
 
  printf("\n\nEnter 2nd Complex Number:- \n"); 
  scanf("%lf\n%lf",&c2.real,&c2.img);
  printf("2nd Complex Number is :- %.2lf%+.2lfi",c2.real,c2.img);

  result.real=c1.real+c2.real; //addition of real part
  result.img=c1.img+c2.img; //addition of imaginary part

  printf("\n\nSum of Complex Number Addition is :- %.2lf%+.2lfi",result.real,result.img);
}
/*
Result:- 
Enter 1st Complex Number:- 
1
2
1st Complex Number is :- 1.00+2.00i

Enter 2nd Complex Number:-
3
4
2nd Complex Number is :- 3.00+4.00i

Sum of Complex Number Addition is :- 4.00+6.00i
*/

--Date :- 19-03-2022
Typedef :- 
it is used to create your own datatype or alian name of datatype in c Progrmaming 
or Synonmns create of datatpe

Syntax:- 
typedef keyword olddatatype  newdatatype

Example :- 
typedef int integer;

Program:- 
#include<stdio.h>

//typedef :- It is used to create own datatype and alian name of datatype.
//It not hold any memory 
//WAP to solve problem 9 for time using typedef keyword.

typedef int Integer; 

typedef struct student
{
  int id;
  char name[50];
}std; ///here  std is alias name of struct datatype

void main()
{
  int a=5;
  Integer b=10;
  printf("int :- %d",a);
  printf("\nInteger :- %d",b);

  std s;
  printf("\nStudent Information :- \nEnter ID & Name:- \n");
  scanf("%d%s",&s.id,&s.name);
  printf("Id:-\t%d\nname:-\t%s",s.id,s.name);  
}
/*
Result:- 
int :- 5
Integer :- 10
Student Information :- 
Enter ID & Name:-      
6000
Shanker
Id:-    6000
name:-  Shanker 
*/

FILE I/O :-

File I/O:-
A) Why do we need a file?
1) Files are used to store data and information.
Note :- 
a) Collection of bit and byte called Data which is not meaning full
b) Collection of data->Process it with menaning things is called information.
2) Files are used to read & access data anytime from the hard disk.
3) Files make it easy for a programmer to accesss and store content without losing it on program termination.
B) Volatile Vs Non-volatile Memory
Volatile           
1) Volatile memory is computer storage that only maintain 
   its data while the device is powered.
2) The RAM will hold data, program, and information as long 
   as it has  a constant power supply but immediately the 
   power is interrupted all that content is cleared. 
   
3) The Volatile memory will only hold data termporarily.
Example :- RAM (Random Access Memory)


Non Volatile
1)Non-volatile memeory is computer memory that can retain 
  the stored information even when not powered.
2)The type of memory is also referred to as permanent memory 
  since data stored within it can be retrieved even when there 
  is no constant power supply.
3)It is used for the long-term storage of data.
Example :- Hard Disk

C) When do we need files?
1) When a C Program is terminated, the data stored in ram is lost.
2) Storing in a file will preserve out data even the program terminated.
3) RAM is not able to handle quite large amonut of data due to its small size relateive to the hard disk.
4) It is easy to transfer data as files.

D) Type of Files:-
1) Text files :- It's like as plan text file such as .txt file. 
2) Binary files :- it's like as img file such as .jpg. Or 0/1 formate

E) Operation on files in C:-
1) Creating a new file.
2) Opening a file..
3) Closing a file.
4) Reading from and writing to a file.

Date:- 20-03-2022
#include<stdio.h>
#include<stdlib.h>
//File I/O Program
//WAP to create and write a single character in file?
void main()
{
 FILE *fp=NULL;
 char ch='S';
 //file creation using w mode
 fp=fopen("Files/SingleCharFile.txt","w"); //New File is created
 if(fp==NULL)
 {
   printf("\nFile not found!");
   exit(1); //for it used #include<stdlib.h> library
 }
 else{
 printf("\nFile Created Successfully");
 fputc(ch,fp); //writing S character in MyFirstFile 
 printf("\nfile writting string successfully..!");
 fclose(fp);
 }
}
/*
Output:- 
Check file in E:\C_Programming\Files location.
File Created Successfully
file writting single charcater successfully..!
*/
---------------
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//File I/O Program
//WAP to create and write a string in existing file?
void main()
{
 FILE *fp=NULL;
 int i;
 char str[50];
 fp=fopen("Files/StringWFile.txt","w");//New File Creation
 if(fp==NULL)
 {
   printf("File not found/created");
   exit(1);
 }
 else
 {
   printf("Enter string to write in file:-  ");
   gets(str);
   
   //we can use this 
   fputs(str,fp);
   printf("\nFile Created and Write Successfully");
   /*
   OR
   for(i=0;i<=strlen(str);i++)
   {
     fputc(str[i],fp);   //To write string used fputs() method  
     fclose(fp);
   }
   */
  fclose(fp);
 }
}
/*
Output:- 
Check file in E:\C_Programming\Files location.
Enter string to write in file:-  Krishna
File Created and Write Successfully
*/
----------------------------------------
#include<stdio.h>
#include<stdlib.h> //It is used for exit(1)
#include<string.h> //It is used for string function like as strlen()
//File I/O Program
//WAP to create and write a student id, name and marks in existing/ Nex file?
typedef struct Student 
{
 int i,id;
 char name[50];
 float mark;
}std;
void main()
{
 FILE *fp=NULL;
 int i;//,id;
 //char name[50];
 //float mark;
 std s;
 fp=fopen("Files/Student.txt","w");//New File Creation
 if(fp==NULL)
 {
   printf("File not found/created");
   exit(1);
 }
 else
 {
   fputs("Student Information as below:-\n",fp);
   printf("\nEnter Student ID:- ");
   scanf("%d",&s.id);
   printf("Enter Student Name:- ");
   scanf("%s",&s.name);
   printf("Enter Student Mark:- ");
   scanf("%f",&s.mark);
   //To write int, float, char or string together then use fprintf()
   fprintf(fp,"ID:-\t%d\nName:-\t%s\nMark:-\t%.2f",s.id,s.name,s.mark);
   //we can use this 
   //fputs(str,fp);//To write string in file then used
   printf("\nFile Created and Write Successfully");
   /*
   OR
   for(i=0;i<=strlen(str);i++)
   {
     fputc(str[i],fp);   //To write string used fputs() method  
     fclose(fp);
   }
   */
  fclose(fp);
 }
}
/*
Output:- 
Check file in E:\C_Programming\Files location.
Enter Student ID:- 6
Enter Student Name:- Ram
Enter Student Mark:- 500
File Created and Write Successfully
------
In file :- 
Student Information as below:-
ID:- 6
Name:- Ram
Mark:- 500.00
*/



#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//File I/O Program
//WAP to read a file from system?

void main()
{
 FILE *fp=NULL;
 char str[500];
 int count1=0;
 fp=fopen("Files/Student.txt","r");//New File Creation
 if(fp==NULL)
 {
   printf("File not found/created");
   exit(1);
 }
 else
 {
   printf("File Cotent are :-\n");
   /* By Character Reading
   while(!feof(fp)) //feof is used to check the content till end.
   {
     //when reading character by character and char ch; define under main ()
    //ch=fgetc(fp);
    //printf("%c",ch);
   }
  */
   //OR //by String Reading
    //When reading string :- here char str[50] define
    while (!feof(fp))
    {
     fgets(str,140,fp); //here 5 is the size then every 5 character it'll again read 5 next 5 with next line.
     printf("%s",str);
     count1=count1+1;
    }
     printf("\nLoop count is :- %d",count1);
     count1=0;//loop will be count as per count line in .txt file.
   //To Read single character used fgetc(fp) and To read string used fgets(fp)          
    fclose(fp);
 }
}

/*
Result:-
Reading file from this location :-  E:\C_Programming\Files location.
//---------------> If we read character by character:-
Outpu :-
Student Information as below:-
ID:-  200
Name:-  Krishna
Mark:-  65.00

//-----------------> If we read string :-
if you give 7 character (Student string) to read then It'll print only "Studen" not a "t" becasue
It's contain last space as a NULL or End with NULL '\0' in string.
Outpu:-
File Cotent are :-
Student Information as below:-
ID:-    200
Name:-  Krishna
Mark:-  65.00
Loop count is :- 4

-----------> if file not exist then it will through message :-
File not found/created

*/


#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//File I/O Program
//WAP to append data or information in existing  file in system?

void main()
{
 FILE *fp=NULL;
 char str[500];
 fp=fopen("Files/Student.txt","a");//Append(Add) New Content in File
 if(fp==NULL)
 {
   printf("File not found/created");
   exit(1);
 }
 else
 {
   printf("append content in File:- \n");
   printf("Enter content to appen in file:- ");
   gets(str);
   
   //fputs(str,fp);  Any one can use
   //OR
   fprintf(fp,"\n\n%s",str);  //Any one can use to append
   printf("\nAppend Successfully Completed..!")

   //Notes :- To Read single character used fgetc(fp) and To read string used fgets(fp)          
    fclose(fp);
   
 }
}

/*
Result:-
Reading file from this location :-  E:\C_Programming\Files location.

(Add) Append content in exsting file:-
Output:-
append content in File:-
Enter content to appen in file:- *** Thank you ***

Append Successfully Completed..!
:- File Ouout :-
Student Information as below:- ID:- 200 Name:- Krishna Mark:- 65.00 *** Thank you ***
*/

Date :- 23-03-2022
#include<stdio.h>
#include<string.h>

typedef struct Bank
{
  int id;
  char name[50];
  char mobile[11];
  float balc;
  float deposit;
  float withdraw;
} bank;


void main()
{
  bank b;
  int n,i=0;
  printf("\n*********Choose option *********:\n");
  printf("1 -> Open Account\n2 -> Deposit Amount\n3 -> withdraw amount\n4 -> account details\n5 -> Exit\n\n");
  scanf("%d",&n);
  if(n>=1 && n<=5)
  {
      while(i<15)
      {        
          if(n==5)
          {
            printf("Thank you..!");
            break;
          }          
          else
          {
              if(n==1)
              {                
                  printf("Enter your ID:- ");
                  scanf("%d",&b.id);

                  printf("Enter you Name :- ");
                  scanf("%s",&b.name);

                  printf("Enter you Mobile Number:- ");
                  scanf("%s",&b.mobile);

                  printf("Enter Minimum 500 Rs.r:- ");
                  scanf("%f",&b.deposit);
                  if(b.deposit<500)
                  {          
                    printf("\nCan not't open account with less then 500 Rs.\nEnter Minimum 500 Rs.r:- ");
                    scanf("%f",&b.deposit);          
                    b.balc=0;                  
                    b.balc=b.deposit; printf("\n"); n=0;
                  }
                  else
                  {
                    printf("\nLow Balance mintaintence required...!");
                  }
                  b.balc=0;                  
                  b.balc=b.deposit; printf("\n"); n=0;

              }  

              else if(n==2)
              {
                printf("Enter your deposit amount:- ");
                scanf("%f",&b.deposit);
                b.balc=b.deposit+b.balc; printf("\n\n");  n=0;
              }    

              else if(n==3)
              {
                printf("Enter your withdraw amount:- ");
                scanf("%f",&b.withdraw);
                b.balc=b.balc-b.withdraw;                
                if(b.balc<500)
                {
                  printf("\nCan not't withdraw amount..!\n Please maintain minimum amount 500 Rs.\n");
                  b.balc=b.balc+b.withdraw;
                }
                else
                {
                  b.balc=b.balc-b.withdraw;
                  printf("\nMust maintain at least minimum amount 500Rs.\n\n");  n=0;
                }

              }

              else if(n==4)
              {
                printf("Account Details :- \n-------------------------------\n");
                printf("ID:-        \t%d\nName:-        \t%s\nMobile:-\t%s\nBalance:-\t%.2f\n-------------------------------",b.id,b.name,b.mobile,b.balc); printf("\n\n");
                n=0;
              }
              else
              {
                printf("\n*********Choose option *********\n");
                printf("1 -> Open Account\n2 -> Deposit Amount\n3 -> withdraw amount\n4 -> account details\n5 -> Exit\n\n");
                scanf("%d",&n); printf("\n");
              }
          }
        i++;
      }
  }
  else {printf("Choose Correct Option");}
}


/*
Output:-

*********Choose option *********:
1 -> Open Account
2 -> Deposit Amount
3 -> withdraw amount
4 -> account details
5 -> Exit

1
Enter your ID:- 10001
Enter you Name :- Kewalram
Enter you Mobile Number:- 6985742130
Enter Minimum 500 Rs.r:- 500

Low Balance mintaintence required...!

*********Choose option *********
1 -> Open Account
2 -> Deposit Amount
3 -> withdraw amount
4 -> account details
5 -> Exit

4

Account Details :-
-------------------------------
ID:-            10001
Name:-          Kewalram  
Mobile:-        6985742130
Balance:-       500.00  
-------------------------------


*********Choose option *********
1 -> Open Account  
2 -> Deposit Amount
3 -> withdraw amount
4 -> account details
5 -> Exit

3

Enter your withdraw amount:- 500

Can not't withdraw amount..!
 Please maintain minimum amount 500 Rs.
Enter your withdraw amount:-

0

Must maintain at least minimum amount 500Rs.


*********Choose option *********
1 -> Open Account
2 -> Deposit Amount
3 -> withdraw amount
4 -> account details
5 -> Exit

4

Account Details :-
-------------------------------
ID:-            10001
Name:-          Kewalram
Mobile:-        6985742130
Balance:-       500.00
-------------------------------


*********Choose option *********
1 -> Open Account
2 -> Deposit Amount
3 -> withdraw amount
4 -> account details
5 -> Exit

2

Enter your deposit amount:- 1  



*********Choose option *********
1 -> Open Account
2 -> Deposit Amount
3 -> withdraw amount
4 -> account details
5 -> Exit

4

Account Details :-
-------------------------------
ID:-            10001
Name:-          Kewalram
Mobile:-        6985742130
Balance:-       501.00
-------------------------------


*********Choose option *********
1 -> Open Account
2 -> Deposit Amount
3 -> withdraw amount
4 -> account details
5 -> Exit

3

Enter your withdraw amount:- 1

Must maintain at least minimum amount 500Rs.

*/
Date:- 28-03-2022

Memory Allocation :

A) Static Memory Allocation(SMA) :

-> meoery allocated during compile time or programmer which create during the program creation time is called static memory.
-> The memory allocated is fiexed and cannot be increased or decreased during the run time.

Example :- 
int main()
{
int arr[5]={1,2,3,4,5};
}

Note :-Memory is allocated at compile time and is fixed.

=> Problems faced in static memory alloaction :- 
1)If you are allocating memory for an array during compile time then you have to fix the size at the time of declaration.
Size is fixed and user cannot increase or decrease the size of the array at run time.

2) If the values stored by the user in the array at run time is less than
the size specified then (tab) there will be wastage of memory.

3) If the values stored by the user in the array at run time is more than
the size specified then the program may crash or misbehave.
  

B) Dynamica Memory Allocation (DMA):-

->The processs of allocating memory at the time of execution (Runtime) is called dynamic memory allocation(DMA).
->Momory Segment :- 


_________________________
Stack                    |
-------------------------|
.                        |
.                        |
.                        |
-------------------------|
Heap                     |
-------------------------|
Uninitialized data (bss) |
-------------------------|
Initialized data         |
-------------------------|
Text/Code Segment        |
_________________________|
1) Heap is the segment of memory where dynamic memory alloaction takes place
2) Unlike stake where  memoery is allocated or deallocated in a defined order,
heap is an area of memory where memory is allocated or deallocated without any order or randomly.
3) There are certain built-in functions that can help in allocating or deallocating some memory sapce at run time.

Note:- 
->Pointers play an important role in dynamica memory allocation.
->Allocated memory can only be accessed through pointer.

C) Build in Functions 

a) malloc()
b) calloc()
c) realloc
d) free()
Date :- 29-03-2022

a) malloc() :-
-> malloc is a  built in function declared in the header file <stdlib.h>
-> malloc is the short name for "memory allocation" and is used to dynamically allocate
a single large block of contiguous memory according to the size specified.
->Syntax:-
   (void *)malloc(size_t size)
Explaination:- malloc required a size which return to the void pointer.

-> malloc function simply allocates a memory block according to the size
specified in the heap and on success it returns a pointer pointing to the 
first byte of the allocated memory else returns NULL.

-> size_t is defined in <stdlib.h> as unsigned int. (you should specify size in positibe 
not a negative means unsigned integer).


Date :-30-03-2022
b) Callloc():-
-> calloc() function is used to dynamically allocate multiple blocks of memory.
-> It is different from malloc in two ways:
i)calloc() needs two arguments instead of just one.
Syntax:- void *calloc(size_t n, size_t size);

where 
size_t n:- number of blocks
size_t size:- Size of each block

Example :-
int *ptr=(int *)calloc(10,sizeof(int));
An equvalent malloc call:

int *ptr=(int *)malloc(10*sizeof(int));


ii) Memory allocated by calloc is initialized to zero.
-> it is not the case with malloc. Memory allocated by malloc is initialized
with some garbage value.
Note:- I)When calloc initialized then every block of memory initialized with zero.
II)malloc and calloc both return NULL when sufficient memory is not available in the heap.

III)
callow stands for clear allloaction
malloc stands for memory allocation.

--Program:-
#include<stdio.h>
#include<stdlib.h>

//calloc () in DMA:-calloc() function is used to dynamically allocate multiple blocks of memory.
void main()
{
  int i,n;
  //n is place where store the number enter by user
  printf("Enter the size of integers to store: ");
  scanf("%d",&n);

  int *ptr=(int *)calloc(n,sizeof(int));

  if(ptr==NULL)
  {
    printf("memory not available.");
    exit(1);
  }
  //Enter No. of input as per provided by calloc function:- 
  for(i=0;i<n;i++) //loop will run till n-1 
  {
    printf("Enter an integer: ");
    scanf("%d",ptr+i);
  }

  printf("Address:-\tValues (as per int size):\n");
  for(i=0;i<n;i++)
  {
    printf("%u:-\t%d\n",ptr+i,*(ptr+i));//*(address of ptr+i(0-4-8-12 as per int byte))
  }
  free(ptr);
  ptr=NULL;
  if(ptr==NULL)
  {
    printf("\nMemory is deallocated/free..!");
    exit(1);
  }
}

/*Output:- 
PS E:\C_Programming> gcc Test.c
PS E:\C_Programming> .\a.exe   
Enter the size of integers to store: 3
Enter an integer: 1
Enter an integer: 2
Enter an integer: 3
Address:-       Values (as per int size):
1260655584:-    1
1260655588:-    2
1260655592:-    3
*/

c) realloc() :- 
-> realloc() function is used to change the size of memory block without losing the old data.

Syntax:- void *realloc(void *ptr, size_t newsize)

on the failur, realloc return NULL.

->Program:- 
#include<stdio.h>
#include<stdlib.h>

//realloc () in DMA:--> realloc() function is used to change the size of memory block without losing the old data.
void main()
{
  int i,n; 
  int *ptr=(int *)calloc(2,sizeof(int));
  
  if(ptr==NULL)
  {
    printf("Memory is not available");
    exit(1);
  }
  //n is place where store the number enter by user
  printf("Enter first two integers: \n");
  for(i=0;i<2;i++)
  {
      printf("Enter %d integer: ",i);
      scanf("%d",ptr+i);
  }

  //memory allocation for 2 more integers
  ptr=(int *)realloc(ptr,4*sizeof(int));  
  if(ptr==NULL)
  {
    printf("memory not available.");
    exit(1); //exit the program with exit failure status
  }

  //Enter No. of input as per provided by calloc function:-
  printf("\nEnter the size of integer including old interger size:-\n") ;
  scanf("%d",&n);
  for(i=2;i<n;i++) //loop will run till n-1 
  {
    printf("Enter integer: ");
    scanf("%d",ptr+i);
  }
  
  printf("\nAddress:-\tValues (as per int size):\n");
  for(i=0;i<n;i++)
  {
    printf("%u:-\t%d\n",ptr+i,*(ptr+i));//*(address of ptr+i(0-4-8-12 as per int byte))
  }

  free(ptr);//used to release the allocated memory in heap.
  ptr=NULL;
  if(ptr==NULL)
  {
    printf("\nMemory is deallocated/free..!");
    exit(1);
  }
}

/*Output:- 
PS E:\C_Programming> gcc Test.c
PS E:\C_Programming> .\a.exe 
Enter first two integers: 
Enter 0 integer: 19
Enter 1 integer: 20

Enter the size of integer including old interger size:-
3
Enter integer: 21

Address:-       Values (as per int size):
2208502752:-    19
2208502756:-    20
2208502760:-    21  

*/
Example :- 
int *ptr=(int *)malloc(sizeof(int));
ptr=(int *) realloc(ptr,2*sizeof(int));

-> This will allocate memory space of 2*sizeof(int).
-> Also, this function moves the contents of the old block
   to a new block and the data of the old block is not lost.
-> We may lose the data when the new size of smaller than the old size.
->Newly allocated bytes are uninitialized.

The malloc fiex the memory in heap which remain the same then we need to release or deallocate
the allocated memory maually from the heap and provider null that value.

d) free():-
-> free() function is used to release the dynamically allocated memory in heap.
syntax:- void free(ptr);

-> The memory allocated in heap will not be released automatically after
 using the memory. The space remains there and can't be used.
 
-> It is the prorammer's responsibilty to release the memory after use.

Example :- 
int main()
{
int *ptr=(int *)malloc(4*sizeof(int)); //4 block of memory allocated to inter 4 number.
...
free(ptr);
}

Programm:- 
#include<stdio.h>
#include<stdlib.h>

//free() :-function is used to release the dynamically allocated memory in heap.
int *input()
{
  int *ptr,i;
  ptr=(int*)malloc(5*sizeof(int));
  printf("Enter 5 numbers: ");
  for(i=0;i<5;i++)
  {
    scanf("%d",ptr+i);
  }
  return ptr;
}

int main()
{
  int i,sum=0;
  int *ptr=input();
  for(i=0;i<5;i++)
  sum+=*(ptr+i);

  printf("Sum is: %d",sum);
  free(ptr);
  ptr=NULL;
  if(ptr==NULL)
  {
    printf("\nMemory is deallocated/free..!");
    exit(1);
  }
  return 0;
}
/*output:- 

PS E:\C_Programming> gcc Test.c
PS E:\C_Programming> .\a.exe   
Enter 5 numbers: 1
2
3
4
5
Sum is: 15
Memory is deallocated/free..!*/



Comments

Popular Post

SQL Server Database Interview Questions and Answers

SQL Server Database Details