parajulirajesh.com.np

Define the term "constant'", "identifier", and "keyword" in c program?

1. Constant:
A constant is a fixed value that does not change during the execution of a program.
Example: 10, 3.14, 'A'

2. Identifier:
An identifier is the name given to a variable, function, or any other user-defined item in a C program.
Example: num, total_sum, main

3. Keyword:
A keyword is a reserved word in C that has a special meaning and cannot be used as an identifier.
Example: int, return, if, while

#include <stdio.h>
int main()
{
int radius = 5;
float area;
const float PI = 3.14;
area = PI * radius * radius;
printf(“Area = %f”, area);
return 0;
}

output:
Area = 78.500000

What is variable? List the major data types which is used in c program?

Variable is a container that stores the values of its type, which may change during program execution.
Example: int age = 20; (age is a variable)

Data TypeDescriptionExample
intStores integer valuesint x = 10;
floatStores single-precision floating-point numbersfloat y = 3.5;
doubleStores double-precision floating-point numbersdouble z = 3.14159;
charStores a single characterchar c = 'A';
voidRepresents no value (used for functions)void func()

What is structure in c program? Explain.

A structure is a user-defined data type in C that allows grouping of different types of variables under a single name. Different datatypes are the members of the structue. Dot(.) operator is used to access the structure members.

Syntax:

struct StructureName {
data_type member1;
data_type member2;

};

#include <stdio.h>
struct Student {
int rollNo;
char name[20];
float marks;
};

int main() {
struct Student s1;
printf(“Enter Roll Number: “);
scanf(“%d”, &s1.rollNo);
printf(“Enter Name: “);
scanf(“%s”, s1.name);
printf(“Enter Marks: “);
scanf(“%f”, &s1.marks);

printf(“\nStudent Details:\n”);
printf(“Roll No is %d\n”, s1.rollNo);
printf(“Name is %s\n”, s1.name);
printf(“Marks is %f\n”, s1.marks);
return 0;
}

List out the different types of operator in c? Describe the logical operator with example

operators are the symbols that are used to perform operations on variables.

Different Types of Operators in C

Operator TypeDescription
Arithmetic Operators+, -, *, /, % — used for mathematical calculations
Relational Operators==, !=, >, <, >=, <= — used to compare values
Logical Operators&&, ||, !=
Assignment Operators=, +=, -=, *=, /=, %= — used to assign values
Increment/Decrement++, -- — used to increase or decrease a value by 1
Bitwise Operators&, |,>>,<<
Conditional Operator?: — ternary operator, used for short if-else
Comma Operator, — separates expressions
Sizeof Operator

sizeof() — returns the size of a data type or variable

2. Logical Operators in C

Logical operators are used to combine or reverse the result of relational expressions.

OperatorMeaningExample
&&Logical AND(a > 5 && b < 10) is true if both conditions are true
` `
!Logical NOT!(a > 5) is true if a > 5 is false

#include <stdio.h>
int main() {
int a, b;
printf(“Enter two numbers: “);
scanf(“%d %d”, &a, &b);
if (a > 0 && b > 0)
printf(“Both numbers are positive\n”);
if (a > 0 || b > 0)
printf(“At least one number is positive\n”);
if (!(a > 0))
printf(“a is not positive\n”);
return 0;
}

Define Pointer in c

A pointer is a variable that stores the address of another variable instead of a direct value.

  • Pointers are used to access or manipulate memory directly.
  • In C, the * symbol is used to declare a pointer, and the & symbol is used to get the address of a variable.
  • * is deference operator and & is address operator.

#include <stdio.h>
int main() {
int num = 10; // normal variable
int *ptr; // pointer variable
ptr = &num; // storing the address of num in ptr
printf(“Value of num: %d\n”, num);
printf(“Address of num: %p\n”, &num);
printf(“Value stored in ptr (address of num): %p\n”, ptr);
printf(“Value pointed by ptr: %d\n”, *ptr);
return 0;
}

Note:

  • ptr stores the address of num.
  • *ptr gives the value at that address (dereferencing).

Describe the different mode of file handling in c?

A file is a collection of related information stored on a permanent storage device (like a hard disk).

  • Files are used to store data permanently, unlike variables which store data temporarily in memory.
  • In C, files are handled using file pointers and functions like fopen(), fclose(), fprintf(), fscanf(), etc.

File handling allows a program to store data permanently on a disk instead of memory. C provides functions to create, open, read, write, and close files.

There are two types of file:

TypeDescriptionExample
Text FileStores data as human-readable characters.data.txt, info.csv
Binary FileStores data in machine-readable binary format.data.bin, records.dat

File Handling Modes in C

In C, when opening a file using fopen(), you must specify a mode, which tells the program how to access the file.

ModeMeaningDescription
"r"ReadOpen an existing file for reading. File must exist.
"w"WriteCreate a new file for writing. If file exists, it overwrites it.
"a"AppendOpen a file for writing at the end. If file doesn’t exist, it creates one.
"r+"Read/WriteOpen an existing file for both reading and writing.
"w+"Write/ReadCreate a new file for both reading and writing. Overwrites if exists.
"a+"Append/ReadOpen a file for reading and appending at the end. Creates file if not exist.
"rb"Read BinaryOpen an existing file in binary mode for reading.
"wb"Write BinaryCreate a new binary file for writing. Overwrites if exists.
"ab"Append BinaryOpen a binary file for appending at the end.
"rb+"Read/Write BinaryOpen a binary file for reading and writing.
"wb+"Write/Read BinaryCreate a new binary file for reading and writing.
"ab+"Append/Read BinaryOpen a binary file for reading and appending.

Simple Program of file handling

#include <stdio.h>
int main() {
FILE *fp;
fp = fopen(“myfile.txt”, “w”);
if (fp == NULL) {
printf(“Error opening file!\n”);
return 1;
}
fprintf(fp, “Hello C Programming!\n”);
fprintf(fp, “This is a text file.\n”);
fclose(fp);
return 0;
}

Difference between array and structure with example

ArrayStructure
Stores elements of same data typeStores elements of different data types
Declared using datatype arrayName[size];Declared using struct keyword
Example: int arr[5];Example: struct student { int id; char name[20]; };
Access elements using index like arr[0]Access members using dot operator like s.id
Memory is allocated for same type elements continuouslyMemory is allocated for different types together
Suitable for storing similar data (marks, numbers)Suitable for storing complex data (student details)
No need to define new type

Creates a new user-defined data type

 

  

 
 

Array program example

#include <stdio.h>
int main() {
int arr[5] = {10, 20, 30, 40, 50};
printf(“%d “, arr[0]);
}
return 0;
}

Structure program example

#include <stdio.h>
struct student {
int id;
char name[20];
};
int main() {
struct student s1;
s1.id=1;
s1.name=”Ram”;
printf(“%d %s”, s1.id, s1.name);
return 0;
}

Write the advantages of pointer? Write a c program to enter the radius of a football and find the area of football using user defined function.

  • Pointers allow dynamic memory allocation at runtime.
  • Pointers help in efficient handling of arrays and data.
  • Pointers enable passing arguments by reference to functions.
  • Pointers provide direct access to memory locations.
  • Pointers are essential for implementing data structures like linked lists.
  • Pointers reduce memory usage by avoiding unnecessary data copying.

#include <stdio.h>
float area(float r);
float area(float r)
{
return 4 * 3.14 * r * r;
}

int main()
{
float radius, result;
printf(“Enter radius of football: “);
scanf(“%f”, &radius);
result = area(radius);
printf(“Area of football = %f”, result);
return 0;
}

write a c program using structure to input staff id, name, and the salary of 50 staffs. Display staff id, name and salary of those whose salary range from 25 thousands to 40 thousands.

#include <stdio.h>
struct Staff {
    int id;
    char name[50];
    float salary;
};
int main() {
    struct Staff staff[50];
    int i;
    for(i = 0; i < 50; i++) {
        printf(“\nEnter details of staff %d:\n”, i+1);
        printf(“ID: “);
        scanf(“%d”, &staff[i].id);
        printf(“Name: “);
        scanf(” %[^\n]”, staff[i].name);
        printf(“Salary: “);
        scanf(“%f”, &staff[i].salary);
    }
    printf(“\nStaff with salary between 25,000 and 40,000:\n”);
    printf(“ID\tName\t\tSalary\n”);
    for(i = 0; i < n; i++) 
{
        if(staff[i].salary >= 25000 && staff[i].salary <= 40000) 
        {
            printf(“%d\t%s\t%f\n”, staff[i].id, staff[i].name, staff[i].salary);
        }
    }
    return 0;
}

write a c program to enter name, grade, age and address of 10 students in a structure and display the information

#include <stdio.h>
struct Student {
char name[50];
char grade;
int age;
char address[100];
};
int main() {
struct Student students[10];
int i;
// Input student details
for(i = 0; i < 10; i++) {
printf(“\nEnter details of student %d:\n”, i+1);
printf(“Name: “);
scanf(” %[^\n]”, students[i].name); // allows space in name
printf(“Grade: “);
scanf(” %c”, &students[i].grade);
printf(“Age: “);
scanf(“%d”, &students[i].age);
printf(“Address: “);
scanf(” %[^\n]”, students[i].address); // allows space in address
}
// Display student information
printf(“\nStudent Information:\n”);
printf(“Name\tGrade\tAge\tAddress\n”);

for(i = 0; i < 10; i++) {
printf(“%s\t%c\t%d\t%s\n”,
students[i].name,
students[i].grade,
students[i].age,
students[i].address);
}
return 0;
}

Describe file handling in c. write a c program to enter names and address of the student and store them in a datafile "student.dat"

File handling in C means storing data in a file and reading it later using functions from stdio.h. It helps save data permanently (even after the program ends).

  • FILE is a structure in C that represents a file.
  • fp is a file pointer that will point to the file you want to read/write

Basic steps:

  1. Create a file pointer → FILE *fp;
  2. Open file → fopen()
  3. Read/Write data → fprintf(), fscanf()
  4. Close file → fclose()

Program using fprintf() to  write readable characters in the  dat file.

#include <stdio.h>
int main() {
FILE *fp;
char name[50];
char address[100];

// Open file in write mode
fp = fopen(“student.dat”, “w”);

//checking file opening or not if incase of system resource failure
if (fp == NULL) {
printf(“Error opening file!”);
return 1;
}

// values from user input
printf(“\nEnter name and address of the student:”);
scanf(“%s%s”, name,address);

// Write to file
fprintf(fp, “Name: %s\n Address: %s”, name, address);
}
fclose(fp);
printf(“\nData stored successfully in student.dat”);

return 0;
}

 

Program using fwrite() to  write machine readable  binary blocks in the  dat file.

#include <stdio.h>
int main() {
FILE *fp;
char name[50];
char address[100];

// Open file in binary write mode
fp = fopen(“student.dat”, “wb”);

// checking file opening
if (fp == NULL) {
printf(“Error opening file!”);
return 1;
}

// values from user input
printf(“\nEnter name and address of the student: “);
scanf(“%s %s”, name, address);

// Write to file using fwrite
fwrite(name, sizeof(char), 50, fp); //syntax fwrite(variable, sizeof(variable), 1, filepointer);
fwrite(address, sizeof(char), 100, fp);

fclose(fp);
printf(“\nData stored successfully in student.dat”);
return 0;
}

write a program to enter name and salary of employee and write it in a .txt file using structure

#include <stdio.h>
struct employee {
char name[50];
float salary;
};

int main() {
FILE *fp;
struct employee e;

// Open file in text write mode
fp = fopen(“employee.txt”, “w”);

if (fp == NULL) {
printf(“Error opening file!”);
return 1;
}

// Take input
printf(“Enter employee name: “);
scanf(“%s”, e.name); // read full name with spaces

printf(“Enter salary: “);
scanf(“%f”, &e.salary);

// Write data to text file
fprintf(fp, “Name: %s\nSalary: %.2f\n”, e.name, e.salary);
fclose(fp);
return 0;
}

Write a c program to read from file:

  • If your file already exists and contains the line:
  • my name is Rajesh Parajuli

#include <stdio.h>
int main() {
FILE *fp;
char word[50];

fp = fopen(“file.txt”, “r”);
if (fp == NULL) {
printf(“Error opening file!\n”);
return 1;
}

while (fscanf(fp, “%s”, word) != EOF) {
printf(“%s “, word); // print each word
}

fclose(fp);
return 0;
}

Scroll to Top

Rajesh Parajuli

BICTE GMC

LEC.RAJESH PARAJULI

Address: Ghodaghodi Municipality-1 Sukhad kailali

Contact: 9847546279

Ghodaghodi Multiple Campus BICTE