Sunteți pe pagina 1din 55

UNIT -2

1. Determinant of 2x2 matrix


#include<stdio.h>
#include<conio.h>
void main()
{
int rows, columns, a[2][2], Determinant = 0;

printf("\n Please Enter the 2 * 2 Matrix Elements \n ");


for(rows = 0; rows < 2; rows++)
{
for(columns = 0;columns < 2; columns++)
{
scanf("%d", &a[rows][columns]);
}
}

Determinant = (a[0][0] * a[1][1]) - (a[0][1] * a[1][0]);

printf("\n The Determinant of 2 * 2 Matrix = %d", Determinant);


getch();

}
2. Determinant of 3x3 matrix

#include<stdio.h>

int main()
{
int rows, columns, a[3][3];
int x, y, z, Determinant = 0;

printf("\n Please Enter the 3 * 3 Matrix Elements \n");


for(rows = 0; rows < 3; rows++)
{
for(columns = 0;columns < 3; columns++)
{
scanf("%d", &a[rows][columns]);
}
}

x = (a[1][1] * a[2][2]) - (a[2][1] * a[1][2]);


y = (a[1][0] * a[2][2]) - (a[2][0] * a[1][2]);
z = (a[1][0] * a[2][1]) - (a[2][0] * a[1][1]);

Determinant = (a[0][0] * x) - (a[0][1] * y) + (a[0][2] * z);

printf("\n The Determinant of 3 * 3 Matrix = %d", Determinant);


return 0;
}
3. Transpose of a matrix
#include <stdio.h>
int main()
{
int m, n, c, d, matrix[10][10], transpose[10][10];
printf("Enter the number of rows and columns of matrix\n");
scanf("%d%d", &m, &n);
printf("Enter elements of the matrix\n");
for (c = 0; c < m; c++)
{
for(d = 0; d < n; d++)
{
scanf("%d", &matrix[c][d]);
}
}
for (c = 0; c < m; c++)
{
for( d = 0 ; d < n ; d++ )
{
transpose[d][c] = matrix[c][d];
}
}
printf("Transpose of the matrix:\n");
for (c = 0; c < n; c++)
{
for (d = 0; d < m; d++)
{
printf("%d\t", transpose[c][d]);
}
printf("\n");
}

return 0;
}

4. Addition of a matrix
#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int mat1[5][5], mat2[5][5], i, j, mat3[5][5],m,n;
printf("Enter the no of rows and cols for first matrix:");
scanf("%d %d",&m,&n);
printf("Enter the no of rows and cols for second matrix:");
scanf("%d %d",&p,&q);
if((m==p)&&(n==q))
{
printf("Matrix can be added");
}
else
{
printf("Rows and columns are not equal");
}
printf("Enter matrix 1 elements :");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
scanf("%d",&mat1[i][j]);
}
}
printf("Enter matrix 2 elements :");
for(i=0; i<p; i++)
{
for(j=0; j<q; j++)
{
scanf("%d",&mat2[i][j]);
}
}
printf("Adding the two matrix to form the third matrix .....\n");
for(i=0; i<m; i++)
{
for(j=0; j<n; j++)
{
mat3[i][j]=mat1[i][j]+mat2[i][j];
}
}
printf("The two matrix added successfully...!!");
printf("The new matrix will be :\n");
for(i=0; i<3; i++)
{
for(j=0; j<3; j++)
{
printf("%d ",mat3[i][j]);
}
printf("\n");
}
getch();
}

5. Multiplication of a matrix

#include<stdio.h>
#include<conio.h>
void main()
{
int a[10][10],b[10][10],c[10][10],i,j,k,r1,c1,r2,c2;
int sum=0;
clrscr();
printf("Enter number of rows and columns of first matrix (MAX 10)\n");
scanf("%d%d",&r1,&c1);
printf("Enter number of rows and columns of second matrix MAX 10)\n");
scanf("%d%d",&r2,&c2);
if(r2==c1)
{

printf("\n Enter First Matrix:");

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


{
for(j=0; j<c1; j++)
{
scanf("%d",&a[i][j]);
}
}

printf("\n Enter Second Matrix: ");


for(i=0; i<r2; i++)
{
for(j=0; j<c2; j++)
{
scanf("%d",&b[i][j]);
}
}

printf("The First Matrix Is: \n");


//print the first matrix
for(i=0; i<r1; i++)
{
for(j=0; j<c1; j++)
printf(" %d ",a[i][j]);
printf("\n");
}

printf("The Second Matrix Is:\n");


// print the second matrix
for(i=0; i<r2; i++)
{
for(j=0; j<c2; j++)
printf(" %d ",b[i][j]);
printf("\n");
}

printf("Multiplication of the Matrices:\n");

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


{
for(j=0; j<c2; j++)
{
c[i][j]=0;
for(k=0; k<r1; k++)
c[i][j]+=a[i][k]*b[k][j];
printf("%d ",c[i][j]);
}
printf("\n");
}

}
else
{
printf("Matrix Multiplication is Not Possible");
}
getch();
}

COMPARISON OF STRINGS:

#include<stdio.h>
#include<conio.h>
void main()
{

char string1[5],string2[5];
int i,temp = 0;
printf("Enter the string1 value: ");
gets(string1);
printf(" Enter the String2 value: ");
gets(string2);
for(i=0; string1[i]!='\0'; i++)
{
if(string1[i] == string2[i])
temp = 1;
else
temp = 0;
}
if(temp == 1)
printf("Both strings are same.");
else
printf("Both strings are not same.");
getch();
}

2. USING LIBRARY FUNCTION

#include <stdio.h>
#include <string.h>
void main()
{
char a[100], b[100];
printf("Enter a string\n");
gets(a);
printf("Enter a string\n");
gets(b);
if (strcmp(a,b) == 0)
printf("The strings are equal.\n");
else
printf("The strings are not equal.\n");
getch();
}

2.CONCATENATION OF STRINGS
1.USING LIBRARY FUNCTION

#include <stdio.h>
#include <string.h>
void main()
{
char a[100], b[100];
printf("Enter the first string\n");
gets(a);
printf("Enter the second string\n");
gets(b);
strcat(a, b);
printf("String obtained on concatenation: %s\n", a);
getch();
}

2.WITHOUT LIBRARY FUNCTION

#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
void main()
{
char str1[MAX_SIZE], str2[MAX_SIZE];
int i, j;
/* Input two strings from user */
printf("Enter first string: ");
gets(str1);
printf("Enter second string: ");
gets(str2);
/* Move till the end of str1 */
i=0;
while(str1[i] != '\0')
{
i++;
}
/* Copy str2 to str1 */
j = 0;
while(str2[j] != '\0')
{
str1[i] = str2[j];
i++;
j++;
}
// Make sure that str1 is NULL terminated
str1[i] = '\0';
printf("Concatenated string = %s", str1);
getch();
}

3.COPYING A STRING

1.WITHOUT LIBRARY FUNCTION

#include <stdio.h>
#include<conio.h>
void main()
{
char s1[100], s2[100], i;
printf("Enter string s1: ");
scanf("%s",s1);
for(i = 0; s1[i] != '\0'; ++i)
{
s2[i] = s1[i];
}
s2[i] = '\0';
printf("String s2: %s", s2);
getch(); }
2.USING LIBRARY FUNCTION

#include <stdio.h>
#include<conio.h>
#include <string.h>
void main()
{
char source[100], destination[1000];
printf("Input a string\n");
gets(source);
strcpy(destination, source);
printf("Source string: %s\n", source);
printf("Destination string: %s\n", destination);
getch();
}

SELECTION SORT:

#include<stdio.h>
#include<conio.h>
void main()
{
int i, j, count, temp, number[25];
printf("How many numbers u are going to enter?: ");
scanf("%d",&count);
printf("Enter %d elements: ", count);
for(i=0;i<count;i++)
{
scanf("%d",&number[i]);
}
// Logic of selection sort algorithm
for(i=0;i<count;i++)
{
for(j=i+1;j<count;j++)
{
if(number[i]>number[j])
{
temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
printf("Sorted elements: ");
for(i=0;i<count;i++)
{
printf(" %d",number[i]);
}
getch();
}

LINEAR SEARCH

METHOD 1:

/* C Program - Linear Search */

#include<stdio.h>
#include<conio.h>
void main()
{
clrscr();
int arr[10], i, num, n, c=0, pos;
printf("Enter the array size : ");
scanf("%d",&n);
printf("Enter Array Elements : ");
for(i=0; i<n; i++)
{
scanf("%d",&arr[i]);
}
printf("Enter the number to be search : ");
scanf("%d",&num);
for(i=0; i<n; i++)
{
if(arr[i]==num)
{
c=1;
pos=i+1;
break;
}
}
if(c==0)
{
printf("Number not found..!!");
}
else
{
printf("%d found at position %d",num, pos);
}
getch();
}

METHOD 2:

#include<stdio.h>
#include<conio.h>
void main()
{
int a[20],i,x,n;
printf("How many elements?");
scanf("%d",&n);
printf("Enter array elements:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("\nEnter element to search:");
scanf("%d",&x);
for(i=0;i<n;i++)
{
if(a[i]==x)
break;
if(i<n)
printf("Element found at index %d",i);
else
printf("Element not found");
getch();
}

BINARY SEARCH:
#include<stdio.h>
#include<conio.h>
void main()
{
int arr[50],i,n,x,flag=0,first,last,mid;
printf("Enter size of array:");
scanf("%d",&n);
printf("\nEnter array element(ascending order)\n");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("\nEnter the element to search:");
scanf("%d",&x);
first=0;
last=n-1;
while(first<=last)
{
mid=(first+last)/2;
if(x==arr[mid])
{
flag=1;
break;
}
else
{
if(x>arr[mid])
first=mid+1;
else
last=mid-1;
}
}
if(flag==1)
printf("\nElement found at position %d",mid+1);
else
printf("\nElement not found");
getch();}
UNIT -3

ARRAY OF POINTERS

#include<stdio.h>
#define SIZE 10

int main()
{
int *arrop[3];
int a = 10, b = 20, c = 50, i;

arrop[0] = &a;
arrop[1] = &b;
arrop[2] = &c;

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


{
printf("Address = %d\t Value = %d\n", arrop[i], *arrop[i]);
}

return 0;
}
POINTER TO ARRAYS

#include <stdio.h>

int main()
{
int i;
int a[5] = {1, 2, 3, 4, 5};
int *p = a; // same as int*p = &a[0]
for (i = 0; i < 5; i++)
{
printf("%d", *p);
p++;
}

return 0;
}

EXAMPLE 2

#include <stdio.h>

const int MAX = 3;

int main () {

int var[] = {10, 100, 200};


int i, *ptr[MAX];

for ( i = 0; i < MAX; i++) {


ptr[i] = &var[i]; /* assign the address of integer. */
}

for ( i = 0; i < MAX; i++) {


printf("Value of var[%d] = %d\n", i, *ptr[i] );
}

return 0;
}

OUTPUT

Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

Example 1: Pointers and Arrays

#include <stdio.h>

int main()

int i, x[6], sum = 0;

printf("Enter 6 numbers: ");

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

scanf("%d", x+i);

sum += *(x+i);

printf("Sum = %d", sum);

return 0;

When you run the program, the output will be:

Enter 6 numbers: 2

3
4

12

Sum = 29

Example 2: Arrays and Pointers

#include <stdio.h>

int main()

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

int* ptr;

ptr = &x[2];

printf("*ptr = %d \n", *ptr);

printf("*ptr+1 = %d \n", *ptr+1);

printf("*ptr-1 = %d", *ptr-1);

return 0;

}
Example: Access Array Elements Using Pointers

#include <stdio.h>

void main()

int data[5], i;

printf("Enter elements: ");

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

scanf("%d", data + i);

printf("You entered: \n");

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

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

getch();

/* PROGRAM FOR SUM OF SIN (X) SERIES */


/*x -x^3/3! + x^5/5! - .........*/
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
float x,s=0;
int fact(int x);
int n,i,t=1;
clrscr();
printf("Enter the value of x & n ");
scanf("%f%d",&x,&n);
for(i=1; i<=n; i++)
{
s=s+pow(-1,(i+1))*(pow(x,t))/((float)fact(t));
printf("x^%d/%d!",t,t);
if(i%2==0)
printf("+");
else
printf("-");
t=t+2;
}
printf("\nSum of series = %.2f",s);
getch();
}
int fact(int x)
{
int i,f=1;
for(i=1; i<=x; i++)
f=f*i;
return(f);
}

BINARY SEARCH USING RECURSION


#include <stdio.h>
int binarysearch(int[ ] , int , int , int ) ;
void main()
{
int a[100];
int len, pos, search_item;
printf("Enter the length of the array\n");
scanf("%d", &len);
printf("Enter the array elements\n");
for (int i=0; i<len; i++)
{
scanf("%d", &a[i]);
}
printf("Enter the element to search\n");
scanf("%d", &search_item);
pos = binarysearch(a,0,len-1,search_item);
if (pos < 0 )
printf("Cannot find the element %d in the array.\n",
search_item);
else
printf("The position of %d in the array is %d.\n",
search_item, pos+1);
getch( );
}
int binarysearch(int a[], int low, int high, int x)
{
int mid = (low + high) / 2;
if (low > high)
return -1;
if (a[mid] == x)
return mid;
if (a[mid] < x)
return binarysearch(a, mid + 1, high, x);
else
return binarysearch(a, low, mid-1, x);
}

POINTER ARITHMETIC:

Pointer Operators:
2 Special operators:
1. * (dereference operator) – gives the value at the address
2. & (reference operator) – gives the address of a variable

Following arithmetic operations are possible on the pointer in C language:


o Increment
o Decrement
o Addition
o Subtraction
o Comparison

INCREMENTING A POINTER

#include<stdio.h>

void main()

int number=50;

int *p;//pointer to int

p=&number;//stores the address of number variable

printf("Address of p variable is %u \n",p);

p=p+1;

printf("After increment: Address of p variable is %u \n",p); // in our ca

se, p will get incre mented by 4 bytes.

getch();

OUTPUT:
Address of p variable is 3214864300
After increment: Address of p variable is 3214864304

DECREMENTING A POINTER
#include <stdio.h>

void main()

int number=50;

int *p;//pointer to int


p=&number;//stores the address of number variable

printf("Address of p variable is %u \n",p);

p=p-1;

printf("After decrement: Address of p variable is %u \n",p); // P will no

w point to the imm

ediate previous loc

ation

}
OUTPUT

Address of p variable is 3214864300

After decrement: Address of p variable is 3214864296

POINTER ADDITION
#include<stdio.h>

void main()

number=50;

int *p;//pointer to int

p=&number;//stores the address of number variable

printf("Address of p variable is %u \n",p);

p=p+3; //adding 3 to pointer variable

printf("After adding 3: Address of p variable is %u \n",p);

getch();

OUTPUT:

Address of p variable is 3214864300


After adding 3: Address of p variable is 3214864312

POINTER SUBTRACTION:
#include<stdio.h>

int main()

int number=50;

int *p;//pointer to int

p=&number;//stores the address of number variable

printf("Address of p variable is %u \n",p);

p=p-3; //subtracting 3 from pointer variable

printf("After subtracting 3: Address of p variable is %u \n",p);

return 0;

OUTPUT :

Address of p variable is 3214864300

After subtracting 3: Address of p variable is 3214864288

SUBTRACTION OF TWO POINTERS

#include <stdio.h>

int main()

int num=45;

int *ptr1,*ptr2;

ptr1=&num;

ptr2=ptr1+1;

printf("address ptr1 %u",ptr1);


printf("\naddress ptr2 %u",ptr2);

printf("\nsub address %u",ptr2-ptr1);

return 0;

OUTPUT :

address ptr1 3596536972

address ptr2 3596536976

sub address 1

POINTER COMPARISONS

#include <stdio.h>

const int MAX = 3;

int main ()

int var[] = {10, 100, 200};

int i, *ptr;

/* let us have address of the first element in pointer */

ptr = var;

i = 0;

while ( ptr <= &var[MAX - 1] )

printf("Address of var[%d] = %x\n", i, ptr );


printf("Value of var[%d] = %d\n", i, *ptr );

/* point to the previous location */

ptr++;

i++;

return 0;

EXAMPLE 2:
#include<stdio.h>
void main()
{
int a=6;
int*p1,*p2;
p1=&a;
p2=&a;
if(p1==p2)
{
printf("The addresses are equal");
}
getch();
}

ARRAY OF POINTERS –SORTING NAMES

#include<stdio.h>
void main()
{
char *T;
int I,J,K;
char *ARRAY[5]={"SUNIL","ANIL","DILIP","JAY","BHARAT"};
clrscr();
for(I=0;I<5;I++)
{
printf("%s \t",ARRAY[I]);
}
printf("\n");
for(I=0;I<4;I++)
{
for(J=0;J<4;J++)
{
K=strcmp(ARRAY[J],ARRAY[J+1]);
if(K>0)
{
T=ARRAY[J];
ARRAY[J]=ARRAY[J+1];
ARRAY[J+1]=T;
}
}
}
for(I=0;I<5;I++)
{
printf("%s \t",ARRAY[I]);
}
getch();
}

EXAMPLE 2

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
char *x[20];
int i,n=0;
void reorder(int n,char *x[]);
clrscr();
printf("Enter no. of String : ");
scanf("%d",&n);
printf("\n");
for(i=0;i<n;i++)
{
printf("Enter the Strings %d : ",i+1);
x[i]=(char *)malloc(20*sizeof(char));
scanf("%s",x[i]);
}
reorder(n,x);
printf("\nreorder list is : \n");
for(i=0;i<n;i++)
{
printf("%d %s\n",i+1,x[i]);
}
getch();

}
void reorder(int n,char *x[])

{
int i,j;
char t[20];
for(i=0;i<n-1;i++)

{
for(j=i+1;j<n;j++)

{
if(strcmp(x[i],x[j])>0)
{
strcpy(t,x[j]);
strcpy(x[j],x[i]);
strcpy(x[i],t);
}
}
}

PARAMETER PASSING

CALL BY VALUE/PASS BY VALUE

#include <stdio.h>
void add(int num);
void main()
{
int num = 5;
printf("\n The value of 'num' before the calling function is = %d", num);
add(num);
printf("\n The value of 'num' after calling the function is = %d", num);
getch();
}
void add(int num)
{
num = num +10;
printf("\n Value of 'num' in the called function is = %d", num);
}

OUTPUT:

The value of 'num' before the calling function is =5

The value of 'num' in the called function is = 15

The value of 'num' after the calling function is =5

CALL BY REFERENCE/PASS BY REFERENCE


#include <stdio.h>
void add(int num);
void main()
{
int num = 5;
printf("\n The value of 'num' before the calling function is = %d", num);
add(&num);
printf("\n The value of 'num' after calling the function is = %d", num);
getch();
}
void add(int *num)
{
* num = *num +10;
printf("\n Value of 'num' in the called function is = %d", *num);
}

OUTPUT:

The value of 'num' before the calling function is =5

The value of 'num' in the called function is = 15

The value of 'num' after the calling function is =15

SWAPPING THE VALUE OF TWO VARIABLES USING PASS BY VALUE

#include<stdio.h>
#include<conio.h>
void swap(int,int) ; // function declaration
void main()
{
int num1, num2 ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(num1, num2) ; // calling function
printf("\nAfter swap: num1 = %d,num2 = %d", num1, num2);
getch() ;
}
void swap(int num1, int num2) // called function
{
int temp ;
temp = num1;
num1 = num2;
num2 = temp;
printf("\nIn swap function num1=%d num2=%d",num1,num2);
}

OUTPUT:

Before swap : num1 =10 , num2 = 20

In swap function num1=20, num2=10

After swap : num1 =10 , num2 = 20

SWAPPING THE VALUE OF TWO VARIABLES USING PASS BY REFERNCE

#include<stdio.h>
#include<conio.h>
void swap(int*,int*) ; // function declaration
void main()
{
int num1, num2 ;
clrscr() ;
num1 = 10 ;
num2 = 20 ;
printf("\nBefore swap: num1 = %d, num2 = %d", num1, num2) ;
swap(&num1,&num2) ; // calling function
printf("\nAfter swap: num1 = %d,num2 = %d", num1, num2);
getch() ;
}
void swap(int *num1, int *num2) // called function
{
int temp ;
temp = *num1;
*num1 = *num2;
*num2 = temp;
printf("\nIn swap function num1=%d num2=%d",*num1,*num2);
}

OUTPUT:

Before swap : num1 =10 , num2 = 20

In swap function num1=20 , num2=10

After swap : num1 =20 , num2 = 10

UNIT -4

STRUCTURES

#include <stdio.h>
#include <string.h>
struct student
{
int roll_no;
char name[30];
int phone_number;
};
void main()
{
struct student p1 = {1,"Brown",123443};

struct student p2, p3;

p2.roll_no = 2;

strcpy(p2.name,"Sam");

p2.phone_number = 1234567822;

p3.roll_no = 3;

strcpy(p3.name,"Addy");

p3.phone_number = 1234567844;

printf("First Student\n");

printf("roll_no : %d\n", p1.roll_no);

printf("name : %s\n", p1.name);

printf("phone_number : %d\n", p1.phone_number);

printf("Second Student\n");

printf("roll_no : %d\n", p2.roll_no);

printf("name : %s\n", p2.name);

printf("phone_number : %d\n", p2.phone_number);

printf("Third Student\n");

printf("roll_no : %d\n", p3.roll_no);

printf("name : %s\n", p3.name);

printf("phone_number : %d\n", p3.phone_number);


getch();

COPYING A STRUCTURE

#include <stdio.h>
#include <string.h>
int main()
{
struct student
{
int roll_no;
char name[30];
int phone_number;
};
struct student p1 = {1,"Brown",123443};
struct student p2;
p2 = p1;
printf("roll_no : %d\n", p2.roll_no);
printf("name : %s\n", p2.name);
printf("phone_number : %d\n", p2.phone_number);
return 0;
}

ARRAY OF STRUCTURES
#include <stdio.h>
struct student
{
int roll_no;
char name[30];
int phone_number;
};
void main()
{
struct student stud[5];
int i;
for(i=0; i<4; i++)
{
printf("Student %d\n",i+1);
printf("Enter roll no. :\n");
scanf("%d", &stud[i].roll_no);
printf("Enter name :\n");
scanf("%s",stud[i].name);
printf("Enter phone number :\n");
scanf("%d", &stud[i].phone_number);
}
for(i=0; i<4; i++)
{
printf("Student %d\n",i+1);
printf("Roll no. : %d\n", stud[i].roll_no);
printf("Name : %s\n", stud[i].name);
printf("Phone no. : %d\n", stud[i].phone_number);
}
getch();
}

Example: Store Information and Display it Using Structure

#include <stdio.h>
struct student
{
char name[50];
int roll;
float marks;
} s;

void main()
{
printf("Enter information:\n");

printf("Enter name: ");

scanf("%s", s.name);

printf("Enter roll number: ");

scanf("%d", &s.roll);

printf("Enter marks: ");

scanf("%f", &s.marks);

printf("Displaying Information:\n");

printf("Name: ");

puts(s.name);

printf("Roll number: %d\n",s.roll);

printf("Marks: %.1f\n", s.marks);

getch();

OUTPUT:

Enter information:

Enter name: Jack

Enter roll number: 23

Enter marks: 34.5

Displaying Information:

Name: Jack

Roll number: 23

Marks: 34.

NESTED STRUCTURES
struct structure1
{
----------
----------
};
struct structure2
{
----------
----------
struct structure1 obj1;
};

EXAMPLE: 1

#include<stdio.h>
struct person
{
char name[20];
int age;
char dob[10];
};
struct student
{
struct person info;
int roll_no;
float marks;
};
void main()
{
struct student s1;

printf("Details of student: \n\n");

printf("Enter name: ");

scanf("%s", s1.info.name);

printf("Enter age: ");


scanf("%d", &s1.info.age);

printf("Enter dob: ");

scanf("%s", s1.info.dob);

printf("Enter roll no: ");

scanf("%d", &s1.roll_no);

printf("Enter marks: ");

scanf("%f", &s1.marks);

printf("\n*******************************\n\n");

printf("Name: %s\n", s1.info.name);

printf("Age: %d\n", s1.info.age);

printf("DOB: %s\n", s1.info.dob);

printf("Roll no: %d\n", s1.roll_no);

printf("Marks: %.2f\n", s1.marks);

getch();

OUTPUT
EXAMPLE :

#include<stdio.h>
struct Address
{
char HouseNo[25];
char City[25];
char PinCode[25];
};

struct Employee
{
int Id;
char Name[25];
float Salary;
struct Address Add;
};

void main()
{
int i;
struct Employee E;

printf("\n\tEnter Employee Id : ");


scanf("%d",&E.Id);

printf("\n\tEnter Employee Name : ");


scanf("%s",&E.Name);

printf("\n\tEnter Employee Salary : ");


scanf("%f",&E.Salary);

printf("\n\tEnter Employee House No : ");


scanf("%s",&E.Add.HouseNo);
printf("\n\tEnter Employee City : ");
scanf("%s",&E.Add.City);

printf("\n\tEnter Employee House No : ");


scanf("%s",&E.Add.PinCode);

printf("\nDetails of Employees");
printf("\n\tEmployee Id : %d",E.Id);
printf("\n\tEmployee Name : %s",E.Name);
printf("\n\tEmployee Salary : %f",E.Salary);
printf("\n\tEmployee House No : %s",E.Add.HouseNo);
printf("\n\tEmployee City : %s",E.Add.City);
printf("\n\tEmployee House No : %s",E.Add.PinCode);

Output :

Enter Employee Id : 101

Enter Employee Name : Suresh

Enter Employee Salary : 45000

Enter Employee House No : 4598/D

Enter Employee City : Delhi

Enter Employee Pin Code : 110056

Details of Employees

Employee Id : 101

Employee Name : Suresh

Employee Salary : 45000


Employee House No : 4598/D

Employee City : Delhi

Employee Pin Code : 110056

EMBEDDED STRUCTURES

#include <stdio.h>
#include <string.h>
struct Employee
{
int id;
char name[20];
struct Date
{
int dd;
int mm;
int yyyy;
} doj;
} e1;
void main( )
{
//storing employee information
e1.id=101;
strcpy(e1.name, "Sonoo Jaiswal");//copying string into char array
e1.doj.dd=10;
e1.doj.mm=11;
e1.doj.yyyy=2014;

//printing first employee information


printf( "employee id : %d\n", e1.id);
printf( "employee name : %s\n", e1.name);
printf( "employee date of joining (dd/mm/yyyy) : %d/%d/%d\n",
e1.doj.dd,e1.doj.mm,e1.doj.yyyy);
getch();
}
OUTPUT
employee id : 101
employee name : Sonoo Jaiswal
employee date of joining (dd/mm/yyyy) : 10/11/2014

RELATION BETWEEN ARRAYS AND POINTERS

#include <stdio.h>
int main()
{
int x[4];
int i;

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


{
printf("&x[%d] = %u\n", i, &x[i]);
}

printf("Address of array x: %u", x);

return 0;
}

When you run the program, the output will be something like:

&x[0] = 1450734448

&x[1] = 1450734452

&x[2] = 1450734456

&x[3] = 1450734460

Address of array x: 1450734448


POINTERS AND STRUCTURES

EXAMPLE 1

#include <stdio.h>
struct Book
{
char bname[10];
int price;
char author[15];
};
void main()
{
struct Book a ={"c program",170,"Reema Thareja"}; //Single structure
variable
struct Book* ptr; //Pointer of Structure type
ptr = &a;
printf("\nBOOK NAME:\t%s",ptr->bname);
printf("\nPRICE:\t%d",a.price);
printf("\nAUTHOR:\t%s",(*ptr).author);
getch();
}

EXAMPLE 2 :

#include <stdio.h>
struct student
{
char id[15]; // student structure
char firstname[64];
char lastname[64];
float points;
};
void main()
{

// student structure variable


struct student std;

// student structure pointer variable

struct student *ptr = NULL;

// assign std to ptr

ptr = &std;

// get student detail from user

printf("Enter ID: ");

scanf("%s", ptr->id);

printf("Enter first name: ");

scanf("%s", ptr->firstname);

printf("Enter last name: ");

scanf("%s", ptr->lastname);

printf("Enter Points: ");

scanf("%f", &ptr->points);

// display result via std variable

printf("ID: %s\n", std.id);

printf("First Name: %s\n", std.firstname);

printf("Last Name: %s\n", std.lastname);

printf("Points: %f\n", std.points);

// display result via ptr variable

printf("\nResult via ptr\n");


printf("ID: %s\n", ptr->id);

printf("First Name: %s\n", ptr->firstname);

printf("Last Name: %s\n", ptr->lastname);

printf("Points: %f\n", ptr->points);

getch();
}

OUTPUT

Enter ID: s01


Enter first name: Yusuf
Enter last name: Shakeel
Enter Points: 8.44

Result via std


ID: s01
First Name: Yusuf
Last Name: Shakeel
Points: 8.440000

Result via ptr


ID: s01
First Name: Yusuf
Last Name: Shakeel
Points: 8.440000

DYNAMIC MEMORY ALLOCATION USING malloc()

#include <stdio.h>
#include <stdlib.h>
int main()
{

// This pointer will hold the


// base address of the block created
int* ptr;
int n, i;

// Get the number of elements for the array


n = 5;
printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using malloc()


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

// Check if the memory has been successfully


// allocated by malloc or not
if (ptr == NULL)
{
printf("Memory not allocated.\n");
}
else
{

// Memory has been successfully allocated


printf("Memory successfully allocated using malloc.\n");

// Get the elements of the array


printf(“Enter the values”);
for (i = 0; i < n;i++)
{
scanf(“%d”,(ptr+i));
}

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n;i++)
{
printf("%d, ", *(ptr+i));
}
}
return 0;
}

DYNAMIC MEMORY ALLOCATION USING calloc()

#include <stdio.h>
#include <stdlib.h>

int main()
{

// This pointer will hold the


// base address of the block created
int* ptr;
int n, i;

// Get the number of elements for the array


n = 5;
printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using calloc()


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

// Check if the memory has been successfully


// allocated by calloc or not
if (ptr == NULL)
{
printf("Memory not allocated.\n");
}
else
{

// Memory has been successfully allocated


printf("Memory successfully allocated using calloc.\n");

// Get the elements of the array


printf(“Enter the elements”);
for (i = 0; i < n;i++)
{
scanf(“%d”,(ptr+i));
}

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n; ++i)
{
printf("%d, ", *(ptr+i));
}
}

return 0;
}

RELEASING THE USED SPACE:

#include <stdio.h>
#include <stdlib.h>
int main()
{

// This pointer will hold the


// base address of the block created
int *ptr, *ptr1;
int n, i;

// Get the number of elements for the array


n = 5;
printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using malloc()


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

// Dynamically allocate memory using calloc()


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

// Check if the memory has been successfully


// allocated or not
if (ptr == NULL || ptr1 == NULL)
{
printf("Memory not allocated.\n");

}
else
{

// Memory has been successfully allocated


printf("Memory successfully allocated using malloc.\n");

// Free the memory


free(ptr);
printf("Malloc Memory successfully freed.\n");

// Memory has been successfully allocated


printf("\nMemory successfully allocated using calloc.\n");

// Free the memory


free(ptr1);
printf("Calloc Memory successfully freed.\n");
}

return 0;
}

TO ALTER THE SIZE OF ALLOCATED MEMORY

#include <stdio.h>
#include <stdlib.h>

int main()
{

// This pointer will hold the


// base address of the block created
int* ptr;
int n, i;

// Get the number of elements for the array


n = 5;
printf("Enter number of elements: %d\n", n);

// Dynamically allocate memory using calloc()


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

// Check if the memory has been successfully


// allocated by calloc or not
if (ptr == NULL)
{
printf("Memory not allocated.\n");

}
else
{

// Memory has been successfully allocated


printf("Memory successfully allocated using calloc.\n");

// Get the elements of the array


for (i = 0; i < n;i++)
{
scanf(“%d”,(ptr+i));
}

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n;i++)
{
printf("%d, ",*( ptr+i));
}

// Get the new size for the array


n = 10;
printf("\n\nEnter the new size of the array: %d\n", n);
// Dynamically re-allocate memory using realloc()
ptr = realloc(ptr, n * sizeof(int));

// Memory has been successfully allocated


printf("Memory successfully re-allocated using realloc.\n");

// Get the new elements of the array


for (i = 5; i < n;i++)
{
scanf(“%d”,(ptr+i));
}

// Print the elements of the array


printf("The elements of the array are: ");
for (i = 0; i < n;i++) {
printf("%d, ",*( ptr+i));
}

free(ptr);
}

return 0;
}

Declaration of structure:

struct book
{
char title[20];
char publisher[20];
char author[20];
int year;
int pages;
};

Declaration of structure variable


struct book b1,b2;

Typedef structure in C

SYNTAX

typedef struct tagname


{
data_type member1;
data_type member1;
...
} newname;

Example:

Method 1:

typedef struct book


{
char title[20];
char publisher[20];
char author[20];
int year;
int pages;
} Book;

Book b1,b2;

Method 2:

struct book
{
char title[20];
char publisher[20];
char author[20];
int year;
int pages;
};
typedef struct book Book;

Example 2:
typedef struct Record
{
char ename[30];
int ssn;
int deptno;
}employee;

employee e1,e2;

PROGRAM:

#include <stdio.h>

//structure declaration
struct employee
{
char name[100];
int age;
};

//typedef structure declaration


typedef struct employee EMP;

int main()
{
//declare structure variable
EMP employee1;

printf("Enter employee's name: ");


gets(employee1.name);
printf("Enter age: ");
scanf("%d",&employee1.age);
printf("Name: %s\nAge: %d\n",employee1.name,employee1.age);
return 0;
}

UNIT -5

File Operations
File Mode Meaning of Mode
r Open for reading.
rb Open for reading in binary mode.
w Open for writing.
wb Open for writing in binary mode.
a Open for append. i.e, Data is added to end of file.

ab Open for append in binary mode. i.e, Data is added to end of file.
r+ Open for both reading and writing.
rb+ Open for both reading and writing in binary mode.
w+ Open for both reading and writing.
wb+ Open for both reading and writing in binary mode.
a+ Open for both reading and appending.
ab+ Open for both reading and appending in binary mode.

In C, you can perform four major operations on the file, either text or binary:

1. Creating a new file


2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file

Opening a file - for creation and edit

Opening a file is performed using the library function in the "stdio.h" header file:
fopen().
The syntax for opening a file in standard I/O is:

ptr = fopen("fileopen","mode")

For Example:

fopen("E:\\cprogram\\newprogram.txt","w");

fopen("E:\\cprogram\\oldprogram.bin","rb");

Example 1: Write to a text file using fprintf()

#include <stdio.h>
#include <stdlib.h>

int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");

if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);

return 0;
}

Example 2: Read from a text file using fscanf()

#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){


printf("Error! opening file");

// Program exits if the file pointer returns NULL.


exit(1);
}

fscanf(fptr,"%d", &num);

printf("Value of n=%d", num);


fclose(fptr);

return 0;
}

S-ar putea să vă placă și