You are on page 1of 7

Write a program to show different way of accessing structure

elements:

#include <stdio.h>

int main() {
struct address{
char phone[15];
char state[25];
int pin;
};
struct address add1={"987456321","Bihar",220145};
struct address *ptr;
ptr=&add1;
printf("Method-1: %s %s %d\n",add1.phone,add1.state,add1.pin);
printf("Method-2: %s %s %d\n",ptr->phone,ptr->state,ptr->pin);
return 0;
}

Output:
Method-1: 987456321 Bihar 220145
Method-2: 987456321 Bihar 220145
Write a program to take input book’s name,price,pages using
structure:

#include <stdio.h>
#include<string.h>
int main ()
{
struct book{
char name[25];
float price;
int pages;
};
struct book b1;
printf("Enter names, price & no.pages in a book\n");
scanf("%s %f %d",&b1.name,&b1.price,&b1.pages);
printf("%s %f %d",b1.name,b1.price,b1.pages);
return 0;
}

Output:
Enter names, price & no.pages in a book
MATHS
100
250
MATHS 100.000000 250
Write a program using nested structure:

#include <stdio.h>

int main() {
struct address{
char phone[15];
char city[25];
int pin;
};
struct emp{
char name[25];
struct address a;
};
struct emp e={"RAM","987654321","Ayodhya",224001};
printf("name= %s phone = %s\n",e.name,e.a.phone);
printf("city = %s pin=%d\n",e.a.city,e.a.pin);
return 0;
}

Output:
name= RAM phone = 987654321
city = Ayodhya pin=4202500
Write a program read a file from disk:

#include <stdio.h>

int main()
{
FILE *fp;
char ch;
fp = fopen("welcome.txt", "r");
while (1)
{
ch = fgetc(fp);
if (ch == EOF)
{
break;
}
printf("%c", ch);
// printf("\n");
}
fclose(fp);
return 0;
}

Output:
Content inside welcome.txt: Welcome to The world of programming.
Write a program to compare string using library function:

#include <stdio.h>
#include<string.h>
int main ()
{
char string1[] = "jerry";
char string2[] = "ferry";
int i, j, k;
i = strcmp (string1, "jerry");
j = strcmp (string1, string2);
k = strcmp (string1, "jerry boy");
printf ("%d %d %d\n", i, j, k);
return 0;
}
Output:
0 4 -32
Write a program to find the factor of given digit and count total
number of factors:

#include <stdio.h>

int main() {
int num,count=0;
printf("Enter number: ");
scanf("%d",&num);
for(int i=1;i<=num/2;i++){
if(num%i==0){
count+=1;
printf("%d is a factor of = %d\n",i,num);
}
}
printf("Total factors = %d",count);
}

Output:
Enter number: 8
1 is a factor of = 8
2 is a factor of = 8
4 is a factor of = 8
Total factors = 3
Write a program to reverse a string:

#include <stdio.h>
#include <string.h>

int main()
{
char str[100] = "string";
printf("Original String: %s\n", str);
int len = strlen(str);
for (int i = 0, j = len - 1; i <= j; i++, j--) {
char c = str[i];
str[i] = str[j];
str[j] = c;
}
printf("Reversed String: %s", str);
return 0;
}

Output:
Original String: string
Reversed String: gnirts

You might also like