Files in C - Demo 2
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file;
char filename[] = "example.txt";
char bu er[100];
file = fopen(filename, "w+");
if (file == NULL) {
printf("Error creating file!\n");
return 1;
}
printf("=== Writing toa file ===\n");
fprintf(file, "Hello,\n I MCA B Class.\n This is a demo for handling Files.\n");
lush(file); //Send everything to file
printf("Current position after writing: %ld\n", ftell(file));
rewind(file);
printf("Position after rewind: %ld\n", ftell(file));
printf("\nEnd of file reached: %s\n", feof(file) ? "Yes" : "No");
fseek(file, 0, SEEK_SET);
printf("Seek to beginning - Position: %ld\n", ftell(file));
fseek(file, 6, SEEK_SET);
printf("Seek to position 6 - Position: %ld\n", ftell(file));
fgets(bu er, sizeof(bu er), file);
printf("Content from position 6: %s", bu er);
fseek(file, 0, SEEK_END);
printf("Seek to end - File size: %ld bytes\n", ftell(file));
fseek(file, -10, SEEK_END);
printf("Seek 10 bytes from end - Position: %ld\n", ftell(file));
fgets(bu er, sizeof(bu er), file);
printf("Last 10 bytes: %s", bu er);
clearerr(file);
fclose(file);
remove(filename);
return 0;
}
Files in C - Demo 1
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file;
char content[] = "Hello,\n I MCA B Class.\n This is a demo for handling Files.\n";
char bu er[100];
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file for writing!\n");
return 1;
}
fprintf(file, "%s", content);
fclose(file);
printf("Content written to file successfully!\n\n");
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file for reading!\n");
return 1;
}
while (fgets(bu er, sizeof(bu er), file) != NULL)
printf("%s", bu er);
fclose(file);
return 0;
}
Sample and Practice questions in Union
#include <stdio.h>
union SensorData {
int errorCode;
float temp;
};
enum DataType { ERROR, TEMP };
int main() {
union SensorData hallSense;
enum DataType type;
hallSense.errorCode = 404;
type = ERROR;
hallSense.temp = 36.7;
type = TEMP;
if (type == ERROR)
printf("Error: %d\n",hallSense.errorCode);
else if (type == TEMP)
printf("Temperature: %.2f",hallSense.temp);
return 0;
}
1. Create a union named Value with members: int i, float f, and char str[20]. Write a
program to input a choice from the user (1 for int, 2 for float, 3 for string), store the
corresponding value in the union. Display the stored value.
2. Write a C program to create a union TravelCard that can hold the balance currency
either in INR or USD or AED. Define a enum to store the current country. Depending on
the country, move the balance to the corresponding variable.
Practice questions on Structures
1. Write a program to read and display the details of a single student (roll number,
name, marks) using a structure.
2. Write a program to store the marks of 5 students in an array of structures and
display them.
3. Using an array of structures, store details of 3 cities (name, population, area).
Find the city with the highest population.
4. Declare a structure Book with members title, author, and price. Write a function to
print book details, passing the structure as an argument.
5. Write a program to store details of products (id, name, price, quantity) in a
structure array. Find the total value of all products in stock.
Demo - Structures
#include<stdio.h>
#include<string.h>
struct players{
int playerNo;
char playerName[50];
int playerTotal;
} player_3;
void main(void){
struct players player_1;
player_1.playerNo=1;
strcpy(player_1.playerName,"Ashok");
player_1.playerTotal=0;
struct players player_2={2,"Immanuel",0};
struct players player[5];
player[0].playerNo=3;
printf("Player 1 Name: %s\n",player_1.playerName);
printf("Player 2 Name: %s\n",player_2.playerName);
printf("player 3 No: %d\n",player[0].playerNo);
}
Answers to Practice Questions on Recursive Functions
Q1
#include<stdio.h>
int sumn(int);
void main(void){
int n=15;
printf("Sum of first %d natural numbers is %d",n,sumn(n));
}
int sumn(int n){
if(n==0)
return 0;
else
return(n+sumn(n-1));
}
Q2
#include<stdio.h>
int gcd(int,int);
void main(void){
int a=48, b=18;
if(a>b)
printf("GCD(%d, %d) is %d",a,b,gcd(a,b));
else
printf("GCD(%d, %d) is %d",b,a,gcd(b,a));
}
int gcd(int a, int b){
printf("%d %d\n",a,b);
if(b==0)
return a;
else
return(gcd(b,a%b));
}
Q3
#include<stdio.h>
int numDigit(int);
void main(void){
int n = 100;
printf("No of digits in %d is %d",n, numDigit(n));
}
int numDigit(int n){
if(n==0)
return 1;
if(n<10)
return 1;
else
return(1+numDigit(n/10));
}
Q4
#include <stdio.h>
#include <string.h>
int isPalindrome(char *s, int left, int right) {
if (left >= right) {
return 1;
}
if (s[left] != s[right]) {
return 0;
}
return isPalindrome(s, left + 1, right - 1);
}
int main() {
char str[] = "racecar";
int len=strlen(str);
printf("%s is a palindrome: %d\n", str, isPalindrome(str,0,len-1));
return 0;
}
Practice questions on Recursive Functions
1. Write a recursive function to find the sum of the first N natural numbers.
2. Write a recursive function to find the Greatest Common Divisor (GCD) of two
numbers.
GCD(48, 18) = GCD(18, 48 % 18) =
GCD(18, 12)
GCD(18, 12) = GCD(12, 6)
GCD(12, 6) = GCD(6, 0)
GCD(6, 0) = 6 (base case)
3. Write a recursive function to count the number of digits in an integer.
Hint: Each time you divide the
number by 10, you remove the last digit. Repeat this process until the number
becomes 0.
4. Write a recursive function to check if a string is a palindrome.
Practice questions on Arrays to Functions
•Write
a function that takes a 1D array of integers and its size, and prints each
element multiplied by 2.
•Write
a function that calculates the sum of elements in a 1D array using pointers.
•Write
a function that doubles every element of a 1D array.
•Write
a function to reverse a 1D array of integers in
place.
•Write
a function to find the second largest number
in a 1D array using a pointer.
•Write
a function to compute the transpose
of a 2D matrix.
•Calculate
the sum of both diagonals
of a square matrix using a function.
String functions in C
(Source: https://ladderpython.com/lesson/string-functions-in-c-language-with-
examples-strcpy-strcat-strcmp-strrev-strlen/)
1. strcpy()
strcpy() function is used to store a value in a string variable.
We can’t use the assignment operator = to assign a value to a string variable.
Syntax :
strcpy(Str2,Str1);
Str2 is the string variable to store the value.
Str1 is the string value to be stored in the string variable Str2.
2. strcat()
strcat() function is used to combine the values of two string variables.
Syntax:
strcat(Str2,Str1);
Str2 is the string variable whose value will be combined with another string value.
Str1 is the string value to be combined with the string variable Str2.
3. strlen()
strlen() function is used to count and return the number of characters in a string value.
Syntax :
strlen(Str);
Str is the string value whose length we want to find.
4. strrev()
strrev() function is used to reverse the characters stored in a string value.
Syntax:
strrev(Str);
Str is the string variable whose value we want to reverse.
5. strcmp()
strcmp() function is used to compare two string values. 0 is returned if the values of the
strings being compared are the same.
Syntax:
strcmp(Str1,Str2);
Here, Str1 and Str2 are string variables or constants that we want to compare.
6. strcmpi()
strcmpi() function is used to compare string values, but capital letters and small letters
are considered the same. 0 is returned if the values of the strings being compared are
the same.
Syntax:
strcmpi(Str1,Str2);
Here, Str1 and Str2 are string variables or constants that we want to compare.
7. strlwr()
strlwr() function converts uppercase letters to lowercase letters in a string value.
Syntax:
strlwr(Str);
Str is the string variable whose value we want to convert into lowercase.
8. strupr()
strupr() function converts the lowercase letters to capital letters in a string value.
Syntax:
strupr(Str);
Str is the string variable whose value we want to convert into capital letters.
Character functions in C
(Source: https://ladderpython.com/lesson/character-functions-in-c/)
Character functions need ctype.h header file to be included in the pgoram. Di erent
character functions provided by C Language are:
1. isalpha():
This function checks whether the character variable/constant contains alphabet or
not.
2. isdigit()
This function checks whether the character variable/ constant contains a digit or not.
3. isalnum()
This function checks whether the character variable/constant contains an alphabet or a
digit.
4. ispunct()
This function checks whether the character variable/constant contains a punctuation
mark or not. Punctuators are commas, semicolons etc.
5. isspace()
This function checks whether the character variable/constant contains a space or not.
6. isupper()
This function checks whether the character variable/constant contains a capital letter
alphabet or not.
7. islower()
This function checks whether the character variable/constant contains a lowercase
alphabet or not.
8. toupper()
This function converts lowercase alphabet into uppercase alphabet.
9. tolower()
This function converts an uppercase alphabet into a lowercase alphabet.
Practice Questions On Pointers
1. Write a C program to input 5 numbers into an array. Use a pointer to traverse and print
all the values.
2. Write a C program to calculate the sum of elements in an array using pointer
arithmetic.
3. Write a C program that prints the greater of two integer values using a pointer.
4. Write a C program to reverse a string using pointer manipulation without using built-in
functions.
5. Write a C program that uses a pointer to traverse and count how many vowels it
contains.
6. Write a C program to declare an array of 5 integers. Use a pointer to traverse the array
and update each element by squaring it. Print the updated array using only pointers.
Demo program for ARRAYS#include <stdio.h>
#include <string.h>
int main()
{
int a[5] = {10, 20, 30, 40, 50}; // Static initialization
int b[5]; // Dynamic initialization
for (int i = 0; i < 5; i++)
b[i] = i * 2;
for(int i = 0; i < 5; i++)
printf("%d ", b[i]);
printf("\n");
int max = a[0], min = a[0]; // Traversing the array
for (int i = 1; i < 5; i++)
{
if (a[i] > max) max = a[i];
if (a[i] < min) min = a[i];
}
printf("Max: %d, Min: %d\n", max, min);
//--------2D Arrays
int matrix1[2][2] = {{1, 2}, {3, 4}};
int matrix2[2][2] = {{5, 6}, {7, 8}};
int result[2][2];
for (int i = 0; i < 2; i++) // Matrix Addition
for (int j = 0; j < 2; j++)
result[i][j] = matrix1[i][j] + matrix2[i][j];
printf("Matrix Addition Result:\n");
for(int i = 0; i < 2; i++)
{
for(int j = 0; j < 2; j++)
printf("%d ", result[i][j]);
printf("\n");
}
//--------Multidimensional Array
int arr3D[2][2][2] = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};
printf("3D Array Elements:\n");
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
for (int k = 0; k < 2; k++)
printf("arr3D[%d][%d][%d] = %d\n", i, j, k, arr3D[i][j][k]);
//---------Array of Strings
char fruits[3][20] = {"Apple", "Banana", "Cherry"};
printf("Fruits:\n");
for (int i = 0; i < 3; i++)
printf("%s\n", fruits[i]);
// String input and modification
char name[20];
printf("Enter your name: ");
scanf("%s", name);
printf("Hello, %s!\n", name);
return 0;
}
Practice questions on ARRAYS
1. Declare an integer array of size 10 and read values from the user and print it in the
reverse order.
2. Initialize an array with values 1 to 10 and print the even numbers and odd numbers
separately.
3. Write a program to count how many elements in an array are greater than 50.
4. Copy the contents of one array to another.
5. Find the average of the array elements.
6. Write a program to insert an element at a given position in an array.
7. Delete an element from a specific position in an array.
8. Count the frequency of each element in the array.
9. Merge two arrays of size 5 and display the merged array.
10. Check if an array is a palindrome.
11. Remove duplicate elements from an array.
12. Rotate an array to the right by k positions.
13. Rearrange positive and negative numbers alternatively in an array.
14. Implement matrix multiplication using 2D arrays.
15. Find the transpose of a matrix.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int U1=0, U2=0, chance=1, target=10, dice=0, userChoice=1;
while(userChoice!=0 && (U1<target || U2<target))
{
printf("Press any key to continue or 0 to exit. Player %d Chance",chance);
scanf("%d",&userChoice);
dice=rand()%6+1;
printf("%d",dice);
if(chance==1)
{
if(U1==0)
{
if(dice==1)
U1=1;
}
else
U1=U1+dice;
chance=2;
}
else
{
if(U2==0)
{
if(dice==1)
U2=1;
}
else
U2=U2+dice;
chance=1;
}
printf("Game Status: User 1 - %d User 2 - %d\n",U1,U2);
}
if(userChoice==0)
{
if(chance==1)
printf("User 1 Quits; User 2 is the Winner\n");
else
printf("User 2 Quits; User 1 is the Winner\n");
}
else
{
if(U1>=target)
printf("User 1 is the Winner with score %d\n",U1);
else
printf("User 2 is the Winner with score %d\n",U2);
}
return 0;
}