IT Solution Menu

N O T I C E

Project on Computer topics, Programs for practicals for BCA Students, and Mobile Android app requirements. Please pay less and get more immediate delivery for school and higher level. Thank You. Contact me - at +91-8800304018(w)

Saturday, August 31, 2024

Top Programming on Structure, Enumeration (enum), and their output in C Language by Md Farrukh Asif

 Top Programming on Structure, Enumeration (enum), and their output in C Language.

by Md Farrukh Asif Run

C Structures (structs)

Structures:

Structures is very important data member. It (also called structs) is a way to group several related variables into one place. Each variable in the structure is known as a member of the structure.

Unlike an array, a structure can contain many different data types (int, float, char, etc.).

 

struct MyStructure {             // Structure declaration
  int myNum;                          // Member (int variable)
  char myLetter;                     // Member (char variable)
};                                 
            // End the structure with a semicolon

 

Access Structure Members

To access members of a structure, use the dot syntax (.):

 

 // Create a structure called studStructure
struct myStructure {
  int Num;
  char Letter;
};
int main() {
  // Create a structure variable of myStructure called s1
  struct studStructure s1;

  // Assign values to members of s1
  s1.Num = 13;
  s1.Letter = 'B';

  // Print values
  printf("My number: %d\n", s1.Num);
  printf("My letter: %c\n", s1.Letter);

  return 0;
}

 

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

Output:

 

My number: 13
My letter: B

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

 

Simpler Syntax

You can also assign values to members of a structure variable at declaration time, in a single line.

Just insert the values in a comma-separated list inside curly braces {}. Note that you don't have to use the strcpy() function for string values with this technique:

 

// Create a structure
struct studentStructure {
  int  Num;
  char  Letter;
  char  String[30];
};

int main() {
  // Create a structure variable and assign values to it
  struct myStructure s1 = {13, 'B', "Example of string data member"};

  // Print values
  printf("%d %c %s", s1.Num, s1.Letter, s1.String);

  return 0;
}

 

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

Output:

13 B Exxample of string ddata member

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

 

Copy Structures:

You can also assign one structure to another.

In the following example, the values of s1 are copied to s2:

Example

struct myStructure s1 = {13, 'B', "Example of string data member"};
struct myStructure s2;

s2 = s1;

 

Here, s1 data structure will be copied into s2.

 

Modify Values

If you want to change/modify a value, you can use the dot syntax (.).

And to modify a string value, the strcpy() function is useful again:

Example

struct myStructure {
  int myNum;
  char myLetter;
  char myString[30];
};

int main() {
  // Create a structure variable and assign values to it
  struct myStructure s1 = {13, 'B', "Some text"};

  
// Modify values
  s1.myNum = 30;
  s1.myLetter = 'C';
  strcpy(s1.myString, "Write something else");

  // Print values
  printf("%d %c %s", s1.myNum, s1.myLetter, s1.myString);

  return 0;
}

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

 

Real-Life Example

Use a structure to store different information about Cars:

Example

struct Car {
  char brand[50];
  char model[50];
  int year;
};

int main() {
  struct Car car1 = {"BMW", "X5", 1999};
  struct Car car2 = {"Ford", "Mustang", 1969};
  struct Car car3 = {"Toyota", "Corolla", 2011};
// Printing the Object or variables
  printf("%s %s %d\n", car1.brand, car1.model, car1.year);
  printf("%s %s %d\n", car2.brand, car2.model, car2.year);
  printf("%s %s %d\n", car3.brand, car3.model, car3.year);
  return 0;
}

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

C Enums

An enum is a special type that represents a group of constants or numeric only (unchangeable values).

To create an enum, use the enum keyword, followed by the name of the enum, and separate the enum items with a comma:

enum Level {
  LOW,
  MEDIUM,
  HIGH
};

Note that the last item does not need a comma.

It is not required to use uppercase, but often considered as good practice.

Enum is short for "enumerations", which means "specifically listed".

To access the enum, you must create a variable of it.

Inside the main() method, specify the enum keyword, followed by the name of the enum (Level) and then the name of the enum variable (myVar in this example):

enum Level myVar;

Now that you have created an enum variable (myVar), you can assign a value to it.

The assigned value must be one of the items inside the enum (LOWMEDIUM or HIGH):

enum Level myVar = MEDIUM;

By default, the first item (LOW) has the value 0, the second (MEDIUM) has the value 1, etc.

If you now try to print myVar, it will output 1, which represents MEDIUM:

#include <stdio.h>

 

enum Level {

  LOW,

  MEDIUM,

  HIGH

};

 

int main() {

  // Create an enum variable and assign a value to it

  enum Level myVar1 = MEDIUM;

  enum Level myVar2 = LOW;

  enum Level myVar3 = HIGH;

 

  // Print the enum variable

  printf("%d", myVar1);

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

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

 

  return 0;

} ===============

Output:

1

0

2

==========

Enum in a Switch Statement

Enums are often used in switch statements to check for corresponding values:

enum Level {
  LOW = 1,
  MEDIUM,
  HIGH
};

int main() {
  enum Level myVar = MEDIUM;
  switch (myVar) {
    case 1:
      printf("Low Level");
      break;
    case 2:
      printf("Medium level");
      break;
    case 3:
      printf("High level");
      break;
  }
  return 0;
}

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

C Language:

C for the beginner 's by Md Farrukh Asif

Operators in C by Md. Farrukh Asif

C's Control Flow by Md. Farrukh Asif

String handling in C by Md Farrukh Asif

The Function of C Language by Md. Farrukh Asif

File Handling With Various Statements/Syntaxes In Programming And Their Output In C Language.

C For Beginner's Programming With Output. Course Code – 106 [‘C’]) TMBU,BGP

Bca Solved Examination Questions With Answers Course Code – 106 [‘C’]) Tmbu,Bgp

Top Programming on Structure, Enumeration (enum), and their output in C Language by Md Farrukh Asif

Here’s a FAQ on structures and enumerations (enum) in C:

Structures in C:

Q1: What is a structure in C?
A structure is a user-defined data type in C that allows grouping variables of different data types together under a single name. This is particularly useful for representing more complex data entities.

Q2: How do you define a structure in C?

struct StructureName {
    dataType1 member1;
    dataType2 member2;
    ...
};

Example:

struct Student {
    char name[50];
    int rollNumber;
    float marks;
};

 

 

Q3: How do you declare and initialize a structure variable?

struct Student student1 = {"John Doe", 101, 85.5};

Q4: How do you access members of a structure?
You can access the members of a structure using the dot (
.) operator.

printf("Name: %s\n", student1.name);
printf("Roll Number: %d\n", student1.rollNumber);
printf("Marks: %.2f\n", student1.marks);

Q5: Can you have a pointer to a structure?
Yes, you can have a pointer to a structure and access its members using the arrow (
->) operator.

struct Student *ptr = &student1;
printf("Name: %s\n", ptr->name);

Q6: Can structures contain other structures?
Yes, structures can contain other structures, allowing for the creation of complex data types.

struct Address {
    char city[50];
    int pin;
};
 
struct Student {
    char name[50];
    struct Address address;
};

Q7: What is the size of a structure?
The size of a structure is the sum of the sizes of its members, but it may also include padding bytes to ensure proper alignment in memory.

Q8: Can structures be passed to functions?
Yes, structures can be passed to functions by value or by reference (using pointers).

Enumerations (enum) in C:

Q1: What is an enumeration in C?
An enumeration (enum) is a user-defined data type that consists of integral constants. It is used to assign names to the integral constants which make the code more readable.

Q2: How do you define an enumeration in C?

enum EnumName {
    constant1,
    constant2,
    ...
};

Example:

enum WeekDay {
    Sunday,
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday
};

Q3: What are the default values of enum constants?
By default, the first constant is assigned the value 0, and each subsequent constant is assigned the value incremented by 1.

enum WeekDay {
    Sunday,    // 0
    Monday,    // 1
    Tuesday,   // 2
    ...
};

Q4: Can you assign specific values to enum constants?
Yes, you can assign specific values to enum constants.

enum WeekDay {
    Sunday = 1,
    Monday = 2,
    Tuesday = 5,
    Wednesday = 10
};

Q5: How do you declare and use an enum variable?

enum WeekDay today;
today = Wednesday;
printf("Day: %d\n", today);  // Output will be 10

Q6: What is the size of an enum in C?
The size of an enum in C is the same as the size of an
int, since enums are implemented as integers in C.

Q7: Can enums be used in switch statements?
Yes, enums are often used in switch statements to handle different cases.

switch (today) {
    case Sunday:
        printf("It's Sunday\n");
        break;
    case Monday:
        printf("It's Monday\n");
        break;
    ...
}

Q8: Can two enum constants have the same value?
Yes, two enum constants can have the same value, but it is generally discouraged as it can lead to confusion.

 *** See You Again ***

************************

Share and Subscribe with Like

************************

Thursday, August 29, 2024

File Handling with various statements/syntaxes in Programming and their output in C Language.

 



File Handling with various statements/syntaxes in Programming and their output in C Language.

by Md Farrukh Asif

 

C File Handling

·        A file is a container in computer storage devices used for storing data.

Why files are needed?

Storing your data in a file is a great way to ensure that it won't be lost if the program terminates unexpectedly. This can save you a lot of time, especially when dealing with a large amount of data. Additionally, having your data in a file allows for easy access and transfer between computers without any modifications.

Types of Files

When dealing with files, there are two types of files you should know about:

1.     Text files

2.     Binary files

1. Text files

Text files, known as .txt files, can be effortlessly created using simple text editors like Notepad. Upon opening these files, you will see the contents displayed as plain text, making it easy to edit or delete them as needed. Text files are low-maintenance, easily readable, and offer minimal security while requiring a larger storage space. space.

2. Binary files

Binary files, often denoted with the .bin extension, are a common file type on your computer. Unlike plain text files, they store data in a binary format comprised of 0's and 1's. Due to their nature, they can accommodate larger volumes of data, are not easily readable, and offer enhanced security compared to text files..

 C Language:

C for the beginner 's by Md Farrukh Asif

Operators in C by Md. Farrukh Asif

C's Control Flow by Md. Farrukh Asif

String handling in C by Md Farrukh Asif

The Function of C Language by Md. Farrukh Asif

File Handling With Various Statements/Syntaxes In Programming And Their Output In C Language.

C For Beginner's Programming With Output. Course Code – 106 [‘C’]) TMBU,BGP

Bca Solved Examination Questions With Answers Course Code – 106 [‘C’]) Tmbu,Bgp

File Operations

In C, you can perform four major operations on files, 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

 

Working with files

When working with files, you need to declare a pointer of type file. This declaration is needed for communication between the file and the program.

 

FILE *fptr;

Opening a file - for creation and edit

Opening a file can be accomplished by using the fopen() function, which is defined in the stdio.h header file. The syntax for opening a file in standard I/O is as follows:

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

As an example,

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

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

Suppose the file newprogram.txt does not exist in the location E:\cprogram. The first function is used to create a new file named newprogram.txt and opens it for writing in the mode 'w', allowing the creation and editing (overwriting) of the file contents.

 

Now, let's consider that the second binary file, oldprogram.bin, exists in the location E:\cprogram. The second function is intended to open the existing file for reading in binary mode 'rb'. This reading mode limits the operation to reading the file, disallowing any writing into the file.

Opening Modes in Standard I/O

Mode

Meaning of Mode

During Inexistence of file

r

Open for reading.

If the file does not exist, fopen() returns NULL.

rb

Open for reading in binary mode.

If the file does not exist, fopen() returns NULL.

w

Open for writing.

If the file exists, its contents are overwritten.
If the file does not exist, it will be created.

wb

Open for writing in binary mode.

If the file exists, its contents are overwritten.
If the file does not exist, it will be created.

a

Open for append.
Data is added to the end of the file.

If the file does not exist, it will be created.

ab

Open for append in binary mode.
Data is added to the end of the file.

If the file does not exist, it will be created.

r+

Open for both reading and writing.

If the file does not exist, fopen() returns NULL.

rb+

Open for both reading and writing in binary mode.

If the file does not exist, fopen() returns NULL.

w+

Open for both reading and writing.

If the file exists, its contents are overwritten.
If the file does not exist, it will be created.

wb+

Open for both reading and writing in binary mode.

If the file exists, its contents are overwritten.
If the file does not exist, it will be created.

a+

Open for both reading and appending.

If the file does not exist, it will be created.

ab+

Open for both reading and appending in binary mode.

If the file does not exist, it will be created.

Closing a File

The file (both text and binary) should be closed after reading\writing.

 

Closing a file is performed using the fclose() function.

fclose(fptr);

Here, fptr is a file pointer associated with the file to be closed.


Reading and writing to a text file

When working with text files, we can utilize the functions fprintf() and fscanf(). These are essentially the file counterparts of printf() and scanf(). The key distinction is that fprintf() and fscanf() require a pointer to the FILE structure.

Example 1: Write to a text file

 

#include <stdio.h>

#include <stdlib.h>

 

int main()

{

   int num;

   FILE *fptr;

 

   // use appropriate location if you are using MacOS or Linux

   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;

}

===========

This program takes a number from the user and stores in the file program.txt.

After you compile and run this program, you can see a text file program.txt created in C drive of your computer. When you open the file, you can see the integer you entered.

Example 2: Read from a text file

 

#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;

}

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

This code reads the integer stored in the program.txt file and displays it on the screen. If you've followed the instructions from Example 1 to create the file, running this code will output the integer you inputted. Other functions like fgetchar() and fputc() can also be applied in a similar manner.

 

In addition, when dealing with binary files, the functions fread() and fwrite() are used for reading from and writing to a file on the disk. These functions are specifically designed for binary files.

Writing to a binary file

To write into a binary file, you need to use the fwrite() function. The functions take four arguments:

1.     address of data to be written in the disk

2.     size of data to be written in the disk

3.     number of such type of data

4.     pointer to the file where you want to write.

 

fwrite(addressData, sizeData, numbersData, pointerToFile);

 

Example 3:

Write to a binary file using fwrite()

 

#include <stdio.h>

#include <stdlib.h>

 

struct threeNum

{

   int n1, n2, n3;

};

 

int main()

{

   int n;

   struct threeNum num;

   FILE *fptr;

 

   if ((fptr = fopen("C:\\program.bin","wb")) == NULL){

       printf("Error! opening file");

 

       // Program exits if the file pointer returns NULL.

       exit(1);

   }

 

   for(n = 1; n < 5; ++n)

   {

      num.n1 = n;

      num.n2 = 5*n;

      num.n3 = 5*n + 1;

      fwrite(&num, sizeof(struct threeNum), 1, fptr);

   }

   fclose(fptr);

 

   return 0;

}

==========

In this program, we create a new file program.bin in the C drive.

In the main function, we define a structure called threeNum, which consists of three numbers: n1, n2, and n3. Inside the for loop, we use the fwrite() function to store the value into the file. The first parameter of fwrite() takes the address of num, while the second parameter takes the size of the threeNum structure. Since we're only inserting one instance of num, the third parameter is 1. The last parameter, *fptr, points to the file where we're storing the data. Finally, we close the file.

Reading from a binary file

Function fread() also take 4 arguments similar to the fwrite() function as above.

fread(addressData, sizeData, numbersData, pointerToFile);


Example 4:

Read from a binary file using fread()

#include <stdio.h>

#include <stdlib.h>

 

struct threeNum

{

   int n1, n2, n3;

};

 

int main()

{

   int n;

   struct threeNum num;

   FILE *fptr;

 

   if ((fptr = fopen("C:\\program.bin","rb")) == NULL){

       printf("Error! opening file");

 

       // Program exits if the file pointer returns NULL.

       exit(1);

   }

 

   for(n = 1; n < 5; ++n)

   {

      fread(&num, sizeof(struct threeNum), 1, fptr);

      printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);

   }

   fclose(fptr);

 

   return 0;

}

========

In this program, you read the same file program.bin and loop through the records one by one.

In simple terms, you read one threeNum record of threeNum size from the file pointed by *fptr into the structure num.

You'll get the same records you inserted in Example 3.

Getting data using fseek()

When you have numerous records inside a file and need to access a record at a specific position, you typically have to loop through all the records before it to retrieve the desired record. This process can consume a significant amount of memory and operation time. An alternative that can make accessing the required data easier is using the fseek() function. As its name implies, fseek() allows you to move the cursor to the specified record in the file.

Syntax of fseek()

```Use a professional and informative tone```

 

The function `fseek` is used to set the file position indicator for the stream represented by the pointer `stream`. The `offset` parameter specifies the number of bytes to move the position indicator, and the `whence` parameter specifies the reference position for the offset.

Different whence in fseek()

Whence

Meaning

SEEK_SET

Starts the offset from the beginning of the file.

SEEK_END

Starts the offset from the end of the file.

SEEK_CUR

Starts the offset from the current location of the cursor in the file.

Example 5: fseek()

#include <stdio.h>

#include <stdlib.h>

 

struct threeNum

{

   int n1, n2, n3;

};

 

int main()

{

   int n;

   struct threeNum num;

   FILE *fptr;

 

   if ((fptr = fopen("C:\\program.bin","rb")) == NULL){

       printf("Error! opening file");

 

       // Program exits if the file pointer returns NULL.

       exit(1);

   }

  

   // Moves the cursor to the end of the file

   fseek(fptr, -sizeof(struct threeNum), SEEK_END);

 

   for(n = 1; n < 5; ++n)

   {

      fread(&num, sizeof(struct threeNum), 1, fptr);

      printf("n1: %d\tn2: %d\tn3: %d\n", num.n1, num.n2, num.n3);

      fseek(fptr, -2*sizeof(struct threeNum), SEEK_CUR);

   }

   fclose(fptr);

 

   return 0;

}

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

This program will start reading the records from the file program.bin in the reverse order (last to first) and prints it.

 

*** See You Again ***

************************

Share and Subscribe with Like

************************ 

Top Popular Post