EX.
NO:1(A) PROGRAMS USING I/O STATEMENTS AND EXPRESSIONS
DATE TO CONVERT CELSIUS TO FAHRENHEIT
PROGRAM:
#include<stdio.h>
#include<conio.h>
int main()
{
float celsius, fahrenheit;
clrscr();
printf("\n Enter the Temparature in Celsius : ");
scanf("%f",&celsius);
fahrenheit = (1.8 * celsius) + 32;
printf("\n Temperature in Fahrenheit : %f ", fahrenheit);
getch();
}
OUTPUT:
Enter the Temparature in Celsius : 38
Temperature in Fahrenheit : 100.400002
[Link](B) PROGRAM TO PRINT THE ADDRESS AND SIZE OF THE DATA &
DATE: DATA TYPE
PROGRAM:
#include <stdio.h>
int main()
{
int x=62;
char a='b';
float p=8.5,q=3.32;
// Print Address
printf("%c is Stored at Address %u\n",a,&a);
printf("%d is Stored at Address %u\n",x,&x);
printf("%f is Stored at Address %u\n",p,&p);
printf("%f is Stored at Address %u\n",q,&q);
// Print Size
printf("\n size of short: %d", sizeof(short));
printf("\n size of int: %d", sizeof(int));
printf("\n size of long int: %d", sizeof(long));
}
OUTPUT:
b is Stored at Address 552292491
14 is Stored at Address 552292492
8.100000 is Stored at Address 552292484
5.200000 is Stored at Address 552292480
size of short: 2
size of int: 4
size of long int: 8
[Link](C) SIMPLE INTEREST CALCULATION
DATE:
PROGRAM:
#include<stdio.h>
int main()
{
float amount, rate, time, si;
printf("\nEnter Principal Amount : ");
scanf("%f", &amount);
printf("\nEnter Rate of Interest : ");
scanf("%f", &rate);
printf("\nEnter Period of Time : ");
scanf("%f", &time);
si = (amount * rate * time) / 100;
printf("\nSimple Interest : %f", si);
return(0);
}
OUTPUT:
Enter Principal Amount : 100000
Enter Rate of Interest : 10
Enter Period of Time : 3
Simple Interest : 30000.000000
[Link](A) PROGRAMS USING DECISION-MAKING CONSTRUCTS
DATE: PRINT FIRST N TERMS OF THE FIBONACCI SERIES
PROGRAM:
#include<stdio.h>
#include<conio.h>
int main()
int range,first=0,second=1,third,i;
clrscr();
printf("Enter the number of terms:");
scanf("%d",&range);
printf("%d\t%d",first,second);
for(i=2;i<range;i++)
third=first+second;
printf("\t%d\t",third);
first=second;
second=third;
getch();
OUTPUT:
Enter the number of terms:14
0 1 1 2 3 5 8 13
21 34 55 89 144 233
[Link](A) PROGRAMS USING DECISION-MAKING CONSTRUCTS
DATE: PRINT FIRST N TERMS OF THE FIBONACCI SERIES
PROGRAM:
#include<stdio.h>
#include<conio.h>
int main()
int range,first=0,second=1,third,i;
clrscr();
printf("Enter the number of terms:");
scanf("%d",&range);
printf("%d\t%d",first,second);
for(i=2;i<range;i++)
third=first+second;
printf("\t%d\t",third);
first=second;
second=third;
getch();
OUTPUT:
Enter the number of terms:14
0 1 1 2 3 5 8 13
21 34 55 89 144 233
[Link] :2(C) TO CHECK WHETHER AN ALPHABET IS VOWEL OR
DATE: CONSONANT
PROGRAM:
#include <stdio.h>
int main(){
char ch;
printf("Enter anycharacter: ");
scanf("%c", &ch); /* Reads a character from user */
if(ch=='a' || ch=='e' || ch=='i' || ch=='o' || ch=='u' || ch=='A' || ch=='E' || ch=='I' || ch=='O' ||
ch=='U')
{
printf("%c is VOWEL.\n", ch);
}
else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
printf("%c is CONSONANT.\n", ch);
}
return 0;
}
OUTPUT :
Enter any character: X
X is CONSONANT.
[Link] :2(D) PRINT FLOYD’S TRIANGLE
DATE:
PROGRAM:
#include <stdio.h>
int main()
{
int rows, a, b, number = 1;
printf("Number of rows of Floyd's triangle to print:");
scanf("%d",&rows);
printf("FLOYD'S TRIANGLE\n\n");
for ( a = 1 ; a <= rows ; a++ )
{
for ( b = 1 ; b <= a ; b++ )
{
printf("%d ", number);
number++;
}
printf("\n");
}
return 0;
}
OUTPUT:
Number of rows of Floyd's triangle to print:8
FLOYD'S TRIANGLE
1
23
456
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
[Link] : 3 WRITE A PROGRAM TO FIND WHETHER THE GIVEN YEAR IS
DATE: LEAP YEAR OR NOT? (HINT: NOT EVERY CENTURION YEAR IS
LEAP. FOR EXAMPLE 1700, 1800 AND 1900 IS NOT LEAP YEAR)
PROGRAM:
#include <stdio.h>
#include <conio.h>
int main()
{
int year;
clrscr();
printf("Enter the Year (YYYY) : ");
scanf("%d",&year);
if(year%4==0 && year%100!=0 || year%400==0)
printf("\nThe Given year %d is a Leap Year");
else
printf("\nThe Given year %d is Not a Leap Year");
getch();
}
OUTPUT :
Enter the Year (YYYY) : 2008
The Given year 2008 is a Leap Year
[Link]: 4 PROGRAM TO DESIGN A CALCULATOR TO PERFORM
DATE: ARITHMETIC OPEARTIONS AND SQUARE OF A NUMBER
PROGRAM:
#include<stdio.h>
int main(){
int a,b,op;
printf("[Link]\[Link]\[Link]\[Link]\[Link] \n"); printf("Enter
the values of a & b: ");
scanf("%d %d",&a,&b);
printf("Enter your Choice : ");
scanf("%d",&op);
switch(op)
{
case 1:
printf("Sum is : %d",a+b);
break;
case 2:
printf("Difference is : %d",a-b);
break;
case 3:
printf("Multiplication is : %d",a*b);
break;
case 4:
printf("Division is :%d ",a/b);
break;
case 5:
printf(“Square is: %d”,a*a);
break;
default:
printf(" Enter Your Correct Choice.");
break;
}
return 0;
}
OUTPUT:
[Link]
[Link]
[Link]
[Link]
[Link]
Enter the values of a & b: 14
8
Enter your Choice : 5
Square is: 196
[Link]: 5 CHECK THE GIVEN NUMBER IS ARMSTRONG NUMBER OR NOT
DATE:
PROGRAM:
#include<stdio.h>
#include<math.h>
int main()
{
int num,rem,arm=0,temp,count;
printf("Enter a number: ");
scanf("%d",&num);
temp=num;
printf("Enter the digit of your number");
scanf("%d",&count);
while (num!=0){
rem=num%10;
arm=arm+pow(rem,count);
num=num/10;
}
if(arm==temp)
printf("%d is an Armstrong number",temp);
else
printf("%d is not an Armstrong number",temp);
return 0;
}
OUTPUT:
Enter a number: 1634
Enter the digit of your number:4
1634 is an Armstrong number
[Link]: 6 GIVEN A SET OF NUMBERS LIKE <10,36,54,89,12,27> , FIND SUM
DATE: OF WEIGHTS BASED ON THE FOLLOWING CONDITIONS
PROGRAM:
#include <stdio.h>
#include <math.h>
// Function to check for Prime Numbers
int prime(int num)
{
if (num <= 1)
return 1; // 1 means not prime for this logic, handles invalid input
int i, flag = 0;
for(i = 2; i * i <= num; i++) // Optimized loop condition
{
if(num % i == 0)
{
flag = 1; // Set flag if a divisor is found (not prime)
break;
}
}
return flag; // returns 0 if prime, 1 if not prime
}
// Function to calculate weight based on user's conditions
int getWeight(int n)
{
int w = 0;
// Condition 1: 5 if it is a perfect cube
// We use a small epsilon for floating point comparison
float cube_root = pow(n, 1.0/3.0);
if (fabs(cube_root - round(cube_root)) < 0.0001) {
w += 5;
}
// Condition 2: 4 if it is a multiple of 4 AND divisible by 6 (multiple of 12)
if(n % 4 == 0 && n % 6 == 0)
w += 4;
// Condition 3: 3 if it is a prime number
if(prime(n) == 0) w += 3;
return w;
}
int main()
{
int nums[15];
int ws[15]; // weights array
int i, j, t, n;
printf("Enter number of numbers: ");
scanf("%d", &n);
printf("\nEnter numbers: ");
for(i = 0; i < n; i++) {
scanf("%d", &nums[i]);
}
// CALCULATE WEIGHTS *AFTER* reading the numbers
for(i = 0; i < n; i++) {
ws[i] = getWeight(nums[i]);
}
printf("\nBefore sorting:\n");
for(i = 0; i < n; i++) {
printf("%d:%d%s", nums[i], ws[i], (i == n - 1) ? "" : " ");
}
printf("\n");
// Sorting logic (Bubble Sort)
for(i = 0; i < n - 1; i++)
{
for(j = 0; j < n - i - 1; j++) {
if(ws[j] > ws[j + 1])
{
// Swap weights
t = ws[j + 1];
ws[j + 1] = ws[j];
ws[j] = t;
// Swap corresponding numbers to stay synchronized
t = nums[j + 1];
nums[j + 1] = nums[j];
nums[j] = t;
}
}
}
printf("\nSorted:\n");
for(i = 0; i < n; i++) {
// Changed to space for cleaner output as requested by your previous format
printf("%d:%d%s", nums[i], ws[i], (i == n - 1) ? "" : " ");
}
printf("\n");
return 0;
}
OUTPUT:
Enter number of numbers: 8
Enter numbers: 27 64 9 8 6 1 45 47
Before sorting:
27:5 64:5 9:0 8:5 6:0 1:5 45:0 47:3
Sorted:
9:0 6:0 45:0 47:3 27:5 64:5 8:5 1:5
[Link] POPULATE AN ARRAY WITH HEIGHT OF PERSONS AND FIND
DATE: HOW MANY PERSONS ARE ABOVE THE AVERAGE HEIGHT
PROGRAM:
#include <stdio.h>
#include <conio.h>
int main()
{
int i,n,sum=0,count=0,height[100];
float avg;
clrscr();
//Read Number of persons
printf("Enter the Number of Persons : ");
scanf("%d",&n);
//Read the height of n persons
printf("\nEnter the Height of each person in centimeter\n");
for(i=0;i<n;i++)
{
scanf("%d",&height[i]);
sum = sum + height[i];
}
avg = (float)sum/n;
//Counting
for(i=0;i<n;i++)
if(height[i]>avg)
count++;
//display
printf("\nAverage Height of %d persons is : %.2f\n",n,avg);
printf("\nThe number of persons above average : %d ",count);
getch();
}
OUTPUT:
Enter the Number of Persons : 5
Enter the Height of each person in centimeter
160 159 158 157 156
Average Height of 5 persons is : 158.00
The number of persons above average : 2
[Link] PROGRAM TO FIND THE STRING REVERSE WITHOUT
DATE: CHANGING THE POSITION OF SPECIAL CHARACTER
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<conio.h>
void reverse(char str[])
int l=0,r=strlen(str) - 1;
char temp;
while(l<r)
if(!(str[l] >= 'a' && str[l] <='z') || (str[l] >='A' && str[l]<= 'Z'))
l++;
else
if(!(str[r] >= 'a' && str[r] <='z') || (str[r] >='A' && str[r]<= 'Z'))
r--;
else
temp =str[l];
str[l]=str[r];
str[r]=temp;
l++;
r--;
}}}
int main()
char str[1000];
clrscr();
printf("enter the string");
scanf("%s",str);
reverse(str);
printf("After the reversal %s",str);
getch();
return 0;}
OUTPUT:
enter the stringa@r#u$t^s*e(l)v;i:
After the reversal i@v#l$e^s*t(u)r;a:
[Link] PROGRAM TO CONVERT THE DECIMAL NUMBER INTO
DATE: BINARY,OCTAL AND HEXADECIMAL NUMBERS USING USER
DEFINED FUNCTIONS
PROGRAM:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
/**
* Converts an integer to a binary string, trimming leading zeros.
*/
void decimalToBinaryTrimmed(int n, char* binary_str) {
if (n == 0) {
strcpy(binary_str, "0");
return;
int i = 0;
int j;
char temp[33]; // Temporary buffer for reverse order
unsigned int u = (unsigned int)n;
// Build binary string in reverse order
while (u > 0) {
temp[i++] = (u % 2) + '0';
u /= 2;
temp[i] = '\0';
// Reverse the string back into binary_str
for (j = 0; j < i; j++) {
binary_str[j] = temp[i - 1 - j];
binary_str[i] = '\0';
int main ()
int i;
char buffer[100]; // Single buffer for all output strings
printf("Enter a number: ");
if (scanf("%d", &i) != 1) {
printf("Invalid input.\n");
return 1;
// Use sprintf to prepare strings for combined output
sprintf(buffer, "%d", i);
printf("Decimal: %s\n", buffer);
sprintf(buffer, "%x", i);
printf("Hexadecimal:%s\n", buffer);
// Use custom function for binary
decimalToBinaryTrimmed(i, buffer);
printf("Binary:%s\n", buffer);
sprintf(buffer, "%o", i);
printf("Octal:%s\n", buffer);
return 0;
OUTPUT:
Enter a number: 14
Decimal: 14
Hexadecimal:e
Binary:1110
Octal:16
[Link]: 10(a) PROGRAM TO PERFORM STRING INBUILT FUNCTIONS
DATE: PROGRAM TO FIND THE TOTAL NUMBER OF
WORDS IN THE STRING
PROGRAM:
#include <stdio.h>
#include <conio.h>
#define MAX_SIZE 100 // Maximum string size
void main (){
char str [MAX_SIZE];
int i, words;
clrscr();
printf("Enter any string: ");
gets(str);
i = 0;
words = 1;
while(str[i] != '\0'){
if(str[i]==' ' || str[i]=='\n' || str[i]=='\t'){
words++;
}
i++;
}
printf("Total number of words = %d\n", words);
getch();
}
OUTPUT:
Enter any string: i am arutselvi studing in
panimalr engineering college
Total number of words = 8
[Link](b) PROGRAM TO CAPITALIZE THE FIRST WORD OF EACH
DATE: SENTENCE
PROGRAM:
#include <stdio.h>
#include <ctype.h> // Required for toupper() and tolower()
#include <string.h> // Required for safe string reading (if using fgets management)
#define MAX_SIZE 100 // Maximum string size
int main() // Standard C signature
{
char str[MAX_SIZE];
int i;
printf("Enter any string: ");
// Use fgets for safe input reading
if (fgets(str, sizeof(str), stdin) == NULL) {
printf("Error reading input.\n");
return 1;
}
// Remove the newline character added by fgets if it exists
str[strcspn(str, "\n")] = '\0';
// Loop through the string to apply capitalization
for (i = 0; str[i] != '\0'; i++)
{
// Check if the current character is a letter
if (isalpha(str[i]))
{
// If it's the very first character OR the character immediately after a space
if (i == 0 || isspace(str[i - 1]))
{
str[i] = toupper(str[i]); // Capitalize the first letter of the word
}
else
{
str[i] = tolower(str[i]); // Ensure all other letters are lowercase
}
}
}
printf("Capitalized string is: %s\n", str);
return 0; // Standard C return
}
OUTPUT:
Enter any string: i am arutselvi of panimalar engineering college
Capitalized string is: I Am Arutselvi Of Panimalar Engineering College
[Link](a)(i) PROGRAM TO SORT THE LIST OF NUMBERS USING
DATE: SELECTION SORT
PROGRAM:
#include <stdio.h>
int main()
{
int arr[50],n,i,j;
int temp;
printf("Enter the size of array: ");
scanf("%d",&n);
printf("Enter the elements of array:\n");
for(i=0;i<=n-1;i++)
scanf("%d",&arr[i]);
for(i=0;i<=n-1;i++)
{
for(j=i+1;j<=n-1;j++)
{
if(arr[i]>arr[j]) //sort array
{
temp =arr[i];
arr[i] =arr[j];
arr[j] =temp;
}
}
}
printf("\nArray elements after sorting:\n");
for(i=0;i<=n-1;i++)
{
printf("%d\n",arr[i]);
}
return (0);
}
OUTPUT:
Enter the size of array: 8
Enter the elements of array:
0 1 4 63 53 23 45 67
Array elements after sorting:
0
1
4
23
45
53
63
67
[Link](a)(ii) PROGRAM TO SORT THE LIST OF NUMBERS USING
DATE: INSERTION SORT
PROGRAM:
#include <stdio.h>
int main()
{
int a[100], n, i, j, key;
printf("Enter the size of the array: ");
scanf("%d", &n);
printf("Enter the array Elements:\n");
for(i = 0; i < n; i++) // Standard notation i < n
{
scanf("%d", &a[i]);
}
// --- Insertion Sort Algorithm ---
for(i = 1; i < n; i++) // Start from the second element
{
key = a[i];
j = i - 1;
// Move elements of a[0..i-1], that are greater than key,
// to one position ahead of their current position
while(j >= 0 && a[j] > key)
{
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = key;
}
// --- End of Sort ---
// Print the final sorted array *after* the entire sorting process is complete
printf("Sorted array is: ");
for(i = 0; i < n; i++)
{
printf("%d ", a[i]); // Added space for readability
}
printf("\n"); // Add a newline at the end
return 0;
}
OUTPUT:
Enter the size of the array: 8
Enter the array Elements:
1
3
45
67
34
54
33
4
Sorted array is: 1 3 4 33 34 45 54 67
[Link](b) PROGRAM TO SORT THE LIST OF NUMBERS USING PASS BY
DATE: REFERENCE
PROGRAM:
#include<stdio.h>
// Function prototype (already present in the original code, good practice)
void sort(int *);
int main()
{
int i;
// Hardcoded array of 10 integers
int a[10] = {99, 95, 93, 92, 98, 97, 93, 90, 98, 93};
// Call the sort function, passing the array (which decays to a pointer)
sort(a);
printf("Sorted List is: ");
for(i = 0; i < 10; i++) {
// Added a space for readability
printf("%d ", a[i]);
}
printf("\n"); // Add a newline at the end
return 0;
}
// Bubble Sort implementation using pointer syntax for the array argument
void sort(int *array)
{
int c, d, swap;
for(c = 0; c < 9; c++) {
for(d = 0; d < 9 - c; d++) {
if(array[d] > array[d + 1]) {
// Perform the swap
swap = array[d];
array[d] = array[d + 1];
array[d + 1] = swap;
}
}
}
}
OUTPUT:
Sorted List is: 90 92 93 93 93 95 97 98 98 99
[Link](a) PROGRAM FOR LINEAR SEARCH
DATE:
PROGRAM:
#include<stdio.h>
int main()
{
int array[100], item, i, n, found = 0;
printf("Enter the number of elements in array\n");
scanf("%d", &n);
printf("Enter the elements \n"); // Removed unused %n from prompt
for (i = 0; i < n; i++) // Standard notation i < n
scanf("%d", &array[i]);
printf("Enter the element to search\n");
scanf("%d", &item);
for (i = 0; i < n; i++)
{
if (array[i] == item) // if required element found
{
found = 1;
break; // Stop the loop immediately
}
}
if (found == 1)
// Note: i holds the index where the item was found
printf("%d is present in array at index %d (position %d)\n", item, i, i + 1);
else
printf("%d is not present in array.\n", item);
return 0;
}
OUTPUT:
Enter the number of elements in array
8
Enter the elements
23
5
67
54
32
90
34
45
Enter the element to search
5
5 is present in array at index 1 (position 2)
[Link](b) PROGRAM TO BINARY SEARCH USING RECURSION CALL
DATE:
PROGRAM:
#include <stdio.h>
// Function prototype (optional to name parameters here)
int bs(int a[], int left, int right, int x);
int main() {
int a[] = {14, 25, 34, 43, 44};
int x, result;
// Correct way to calculate the number of elements in the array
int n = sizeof(a) / sizeof(a[0]);
printf("Enter the element to search: ");
scanf("%d", &x);
result = bs(a, 0, n - 1, x);
// Corrected the comparison operator (==)
if (result == -1) {
printf("Element is not present in array\n"); // Added a newline for better output
} else {
printf("Element is present at index %d\n", result); // Added a newline for better output
}
return 0;
}
int bs(int a[], int left, int right, int x) {
if (right >= left) {
// Safer mid calculation to prevent overflow with very large arrays
int mid = left + (right - left) / 2;
if (a[mid] == x)
return mid;
if (a[mid] > x)
return bs(a, left, mid - 1, x);
return bs(a, mid + 1, right, x);
}
// Base case: element is not found
return -1;
}
OUTPUT:
Enter the element to search: 44
Element is present at index 4
[Link] PROGRAM TO GENERATE SALARY SLIP OF EMPLOYEES
DATE: USING STRUCTURES AND POINTERS
PROGRAM:
#include <stdio.h>
#include <stdlib.h> // Required for malloc
// Structure definition
struct employee
{
char name[20]; // Increased name size slightly for robustness
int basic, da, hra, ta, others;
int pf, it;
// Removed unused variable 't'
int net_salary;
};
// Removed the global declaration e[10] since dynamic allocation is used
int main()
{
int i, n;
struct employee *ptr;
printf("Enter the number of employees: ");
// Added newline for better formatting
scanf("%d", &n);
// Dynamically allocate memory for 'n' employees
ptr = (struct employee*)malloc(n * sizeof(struct employee));
// Check if memory allocation was successful
if (ptr == NULL) {
printf("Error: Memory allocation failed. Exiting.\n");
return 1;
}
for(i = 0; i < n; i++)
{
printf("\n--- Employee %d ---\n", i + 1);
printf("Enter the name: ");
scanf("%s", (ptr+i)->name);
printf("Enter Basic Salary (RS): ");
scanf("%d", &(ptr+i)->basic);
printf("Enter HRA (RS): ");
scanf("%d", &(ptr+i)->hra);
printf("Enter DA (RS): ");
scanf("%d", &(ptr+i)->da);
printf("Enter TA (RS): ");
scanf("%d", &(ptr+i)->ta);
printf("Enter Others (RS): ");
scanf("%d", &(ptr+i)->others);
printf("Enter PF (RS): ");
scanf("%d", &(ptr+i)->pf);
Type your text
printf("Enter IT (RS): ");
scanf("%d", &(ptr+i)->it);
// Calculate net salary:
// Earnings (Basic+DA+HRA+TA+Others) - Deductions (PF+IT)
(ptr+i)->net_salary = (ptr+i)->basic + (ptr+i)->da + (ptr+i)->hra +
(ptr+i)->ta + (ptr+i)->others -
((ptr+i)->pf + (ptr+i)->it);
}
// Printing Net salary for all employees
printf("\n--- Salary Details ---\n");
for(i = 0; i < n; i++)
{
printf("\nName: %s", (ptr+i)->name);
printf("\tNet Salary: RS %d\n", (ptr+i)->net_salary);
}
// Free the dynamically allocated memory
free(ptr);
return 0;
}
OUTPUT:
Enter the number of employees: 2
--- Employee 1 ---
Enter the name: arutselvi
Enter Basic Salary (RS): 1000000
Enter HRA (RS): 20000
Enter DA (RS): 10000
Enter TA (RS): 20000
Enter Others (RS): 10000
Enter PF (RS): 10000
Enter IT (RS): 10000
--- Employee 2 ---
Enter the name: deepu
Enter Basic Salary (RS): 1500000
Enter HRA (RS): 40000
Enter DA (RS): 20000
Enter TA (RS): 30000
Enter Others (RS): 20000
Enter PF (RS): 10000
Enter IT (RS): 20000
--- Salary Details ---
Name: arutselvi Net Salary: RS 1040000
Name: deepu Net Salary: RS 1580000
[Link]: 14
DATE: PROGRAMS USING POINTERS
A. Program using Pointers
B. Pointer Demonstration the Use Of & And *
[Link] Elements of an Array Using Pointer
D. Perform the String Operations like Length of the String, Concatenation
Of String and Compare the String Using Pointer
E. Count Number of Words, Digits, Vowels Using Pointers
F. Add Two Matrices Using Multidimensional Arrays with Pointers
G. Multiply Two Matrices Using Pointers
H. Multiply Two Numbers Using Function Pointers
Program: A. Program using Pointers
#include <stdio.h>
int main()
{
int var = 5;
printf("var: %d\n", var);
// Notice the use of & before var
printf("address of var: %p", &var);
return 0;
Output
var: 14
address of var: 0x7fffe17bfd1c
Program: B. Pointer Demonstration the Use Of & And *
#include <stdio.h>
int main()
{
/* Pointer of integer type, this can hold the
* address of a integer type variable.
*/
int *p;
int var = 14;
/* Assigning the address of variable var to the pointer
* p. The p can hold the address of var because var is
* an integer type variable.
*/
p= &var;
printf("Value of variable var is: %d", var);
printf("\nValue of variable var is: %d", *p);
printf("\nAddress of variable var is: %p", &var);
printf("\nAddress of variable var is: %p", p);
printf("\nAddress of pointer p is: %p", &p);
return 0;
}
Output:
Value of variable var is: 14
Value of variable var is: 14
Address of variable var is: 0x7ffd16364384
Address of variable var is: 0x7ffd16364384
Address of pointer p is: 0x7ffd16364388
Program:C Access Elements of an Array Using Pointer
#include <stdio.h>
int main() {
int data[5];
printf("Enter elements: ");
for (int i = 0; i < 5; ++i)
scanf("%d", data + i);
printf("You entered: \n");
for (int i = 0; i < 5; ++i)
printf("%d\n", *(data + i));
return 0;
}
Output:
Enter elements: 23 44 54 67 87
You entered:
23
44
54
67
87
Program: D Perform the String Operations like Length of the String, Concatenation
of String and Compare the String Using Pointer
i). Program to find Length of the string using pointer
#include <stdio.h>
int string_ln(char *p);
int main() {
char str[100];
int length;
printf("Enter any string: ");
fgets(str, sizeof(str), stdin);
// Remove the newline character from fgets
int i = 0;
while (str[i] != '\0') {
if (str[i] == '\n') {
str[i] = '\0';
break;
}
i++;
}
length = string_ln(str);
printf("The length of the given string \"%s\" is : %d\n", str, length);
return 0;
}
int string_ln(char *p) {
int count = 0;
while (*p != '\0') {
count++;
p++;
}
return count;
}
Output :
Enter any string: ARUTSELVI
The length of the given string "ARUTSELVI" is : 9
ii). Program to Concatenation of String using Pointers.
#include <stdio.h>
#define MAX_SIZE 100 // Maximum string size
int main()
{
char str1[MAX_SIZE], str2[MAX_SIZE];
char * s1 = str1;
char * s2 = str2;
// Inputting 2 strings from user
printf("Enter 1st string: ");
scanf("%s",(str1));
printf("Enter 2nd string: ");
scanf("%s",(str2));
// Moving till the end of str1
while(*(++s1));
// Coping str2 to str1
while(*(s1++) = *(s2++));
printf("Concatenated string: %s", str1);
return 0;
}
Output
Enter 1st string: arut
Enter 2nd string: selvi
Concatenated string: arutselvi
iii. Program to Compare two string using pointers:
#include<stdio.h>
int main()
{
char string1[50],string2[50],*str1,*str2;
int i,equal = 0;
printf("Enter The First String: ");
scanf("%s",string1);
printf("Enter The Second String: ");
scanf("%s",string2);
str1 = string1;
str2 = string2;
while(*str1 == *str2)
{
if ( *str1 == '\0' || *str2 == '\0' )
break;
str1++;
str2++;
}
if( *str1 == '\0' && *str2 == '\0' )
printf("\n\nBoth Strings Are Equal.");
else
printf("\n\nBoth Strings Are Not Equal.");
}
Output:-
Enter The First String: arut
Enter The Second String: arut
Both Strings Are Equal.
Program: E Count Number of Words, Digits, Vowels Using Pointers
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define LOW 1
#define HIGH 0
int main() {
char str[200];
int nob = 0, now = 0, nod = 0, nov = 0, nos = 0;
int pos = HIGH;
int i = 0;
printf("Enter any string: ");
fgets(str, sizeof(str), stdin);
while (str[i] != '\0') {
if (str[i] == ' ') {
nob++; // spaces
pos = HIGH;
}
else if (pos == HIGH) {
now++; // words
pos = LOW;
}
if (isdigit(str[i])) {
nod++; // digits
}
if (isalpha(str[i])) {
switch (str[i]) { // vowels
case 'a': case 'e': case 'i': case 'o': case 'u':
case 'A': case 'E': case 'I': case 'O': case 'U':
nov++;
break;
}
}
if (!isdigit(str[i]) && !isalpha(str[i]) && str[i] != ' ' && str[i] != '\n') {
nos++; // special chars (excluding space & newline)
}
i++;
}
printf("\nNumber of words: %d", now);
printf("\nNumber of spaces: %d", nob);
printf("\nNumber of vowels: %d", nov);
printf("\nNumber of digits: %d", nod);
printf("\nNumber of special characters: %d\n", nos);
return 0;
}
Output:
Enter any string : pritesh a taral from 2 IT C $
Number of words 7
Number of spaces 7
Number of vowels 6
Number of digits 1
Number of special characters 1
Program: F Add Two Matrices Using Multidimensional Arrays with Pointers
#include <stdio.h>
int main() {
int r, c, a[100][100], b[100][100], sum[100][100], i, j;
printf("Enter the number of rows (between 1 and 100): ");
scanf("%d", &r);
printf("Enter the number of columns (between 1 and 100): ");
scanf("%d", &c);
printf("\nEnter elements of 1st matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element a%d%d: ", i + 1, j + 1);
scanf("%d", (*(a + i) + j)); // pointer method
}
printf("\nEnter elements of 2nd matrix:\n");
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
printf("Enter element b%d%d: ", i + 1, j + 1);
scanf("%d", (*(b + i) + j)); // pointer method
}
// Adding two matrices
for (i = 0; i < r; ++i)
for (j = 0; j < c; ++j) {
*(*(sum + i) + j) = *(*(a + i) + j) + *(*(b + i) + j);
}
// Printing the result
printf("\nSum of two matrices:\n");
for (i = 0; i < r; ++i) {
for (j = 0; j < c; ++j) {
printf("%d ", *(*(sum + i) + j));
}
printf("\n");
}
return 0;
}
Output:
Enter the number of rows (between 1 and 100): 2
Enter the number of columns (between 1 and 100): 2
Enter elements of 1st matrix:
Enter element a11: 2
Enter element a12: 3
Enter element a21: 4
Enter element a22: 5
Enter elements of 2nd matrix:
Enter element b11: 6
Enter element b12: 6
Enter element b21: 7
Enter element b22: 8
Sum of two matrices:
89
11 13
Program: G Multiply Two Matrices Using Pointers
#include <stdio.h>
#define ROW 3
#define COL 3
/* Function declarations */
void matrixInput(int mat[][COL]);
void matrixPrint(int mat[][COL]);
void matrixMultiply(int mat1[][COL], int mat2[][COL], int res[][COL]);
int main() {
int mat1[ROW][COL];
int mat2[ROW][COL];
int product[ROW][COL];
printf("Enter elements in first matrix of size %dx%d\n", ROW, COL);
matrixInput(mat1);
printf("Enter elements in second matrix of size %dx%d\n", ROW, COL);
matrixInput(mat2);
matrixMultiply(mat1, mat2, product);
printf("Product of both matrices is : \n");
matrixPrint(product);
return 0;
}
void matrixInput(int mat[][COL]) {
int row, col;
for (row = 0; row < ROW; row++) {
for (col = 0; col < COL; col++) {
scanf("%d", (*(mat + row) + col));
}
}
}
void matrixPrint(int mat[][COL]) {
int row, col;
for (row = 0; row < ROW; row++) {
for (col = 0; col < COL; col++) {
printf("%d ", *(*(mat + row) + col));
}
printf("\n");
}
}
void matrixMultiply(int mat1[][COL], int mat2[][COL], int res[][COL]) {
int row, col, i;
int sum;
for (row = 0; row < ROW; row++) {
for (col = 0; col < COL; col++) {
sum = 0;
for (i = 0; i < COL; i++) {
sum += (*(*(mat1 + row) + i)) * (*(*(mat2 + i) + col));
}
*(*(res + row) + col) = sum;
}
}
}
Output
Enter elements in first matrix of size 3x3
124
247
563
Enter elements in second matrix of size 3x3
854
256
378
Product of both matrices is:
24 43 48
45 79 88
61 76 80
Program: H Multiply Two Numbers Using Function Pointers
#include <stdio.h>
#include <stdlib.h>
// Function prototype
int multiplyNum(int, int);
// Function pointer declaration
int (*fptr)(int, int);
int main() {
int num1, num2, product;
// Assign function to pointer
fptr = multiplyNum;
printf("Enter the two numbers: ");
scanf("%d %d", &num1, &num2);
// Calling normally
product = multiplyNum(num1, num2);
printf("The product using normal call: %d\n", product);
// Calling using function pointer
product = (*fptr)(num1, num2);
printf("The product using function pointer: %d\n", product);
return 0;
}
int multiplyNum(int a, int b) {
return a * b;
}
OUTPUT
Enter the two numbers: 14
8
The product using normal call: 112
The product using function pointer: 112
[Link] PROGRAM TO COMPUTE INTERNAL MARKS OF STUDENTS
DATE: FOR FIVE SUBJECTS USING STRUCTURES AND FUNCTIONS
PROGRAM:
#include <stdio.h>
#include <stdlib.h> // Recommended inclusion for standard practices
// Structure definition
struct stud {
int rollno, s1, s2, tot;
char name[20]; // Increased name size slightly for robustness
float avg;
};
// Global declaration of an array of up to 10 student structures
struct stud s[10];
int main()
int i, n;
// clrscr() and getch() are non-standard. We remove clrscr()
// and replace getch() functionality by pausing the console at the end if needed.
printf("Enter the number of students (max 10): ");
scanf("%d", &n);
// Input loop
for(i = 0; i < n && i < 10; i++){ // Added bound check for array size
printf("\n--- Student %d ---\n", i + 1);
printf("Enter the roll number: ");
scanf("%d", &s[i].rollno);
printf("Enter the name: ");
scanf("%s", s[i].name);
printf("Enter the marks in 2 subjects (Sub1 Sub2): ");
scanf("%d %d", &s[i].s1, &s[i].s2);
s[i].tot = s[i].s1 + s[i].s2;
// Ensure float division by using 2.0
s[i].avg = s[i].tot / 2.0;
// Output header
printf("\n\nRoll No.\tName\t\tSub1\tSub2\tTotal\tAverage\n");
printf("--------\t----\t\t----\t----\t-----\t-------\n");
// Output loop
for(i = 0; i < n && i < 10; i++){
// Adjusted spacing using tabs and format specifiers for better alignment
printf("%-8d\t%-15s\t%-4d\t%-4d\t%-5d\t%.2f\n",
s[i].rollno, s[i].name, s[i].s1, s[i].s2, s[i].tot, s[i].avg);
// Standard way to pause the console for Windows users if running from an IDE
// system("pause");
return 0; // main should return an int
OUTPUT:
[Link] PROGRAM TO DEMONSTRATE THE DIFFERENCE
DATE: BETWEEN UNIONS AND STRUCTURES
PROGRAM:
#include <stdio.h>
// Structure definition (Corrected capitalization and syntax)
struct Person {
char name[50];
int age;
};
// Union definition (Corrected capitalization and syntax)
union Data {
int intValue;
float floatValue;
char stringValue[50];
};
int main() {
// Variable declaration for the structure
struct Person person;
printf("Enter person's name: ");
// Use %s for strings; it handles the array address naturally
scanf("%s", [Link]);
printf("Enter person's age: ");
scanf("%d", &[Link]);
printf("\nStructure 'Person' Data:\n");
printf("Name: %s\n", [Link]);
printf("Age: %d\n", [Link]);
// Variable declaration for the union (Corrected capitalization)
union Data data;
printf("\nEnter an integer value: ");
scanf("%d", &[Link]);
printf("\nUnion 'Data' as Integer (last active member):\n");
printf("Value: %d\n", [Link]);
printf("\nEnter a float value: ");
scanf("%f", &[Link]);
// Fixed the misplaced 'float' keyword and redundant 'printf'
printf("\nUnion 'Data' as Float (last active member):\n");
printf("Value: %.2f\n", [Link]);
printf("\nEnter a string value: ");
scanf("%s", [Link]);
printf("\nUnion 'Data' as String (last active member):\n");
printf("Value: %s\n", [Link]);
return 0;
}
OUTPUT:
Enter person's name: arutselvi
Enter person's age: 17
Structure 'Person' Data:
Name: arutselvi
Age: 17
Enter an integer value: 3
Union 'Data' as Integer (last active member):
Value: 3
Enter a float value: 3.12
Union 'Data' as Float (last active member):
Value: 3.12
Enter a string value: female
Union 'Data' as String (last active member):
Value: female
[Link] INSERT , UPDATE, DELETE AND APPEND TELEPHONE DETAILS OF
DATE: AN INDIVIDUAL OR A COMPANY INTO A TELEPHONE
DIRECTORY USING RANDOM FILE ACCESS
PROGRAM:
#include <stdio.h>
#include <string.h> // REQUIRED for strcpy and strcmp
#include <stdlib.h>
// Define a structure to represent employee details
struct Employee {
int id;
char name[50]; // Correctly defined as a character array (string)
char designation[50]; // Correctly defined as a character array (string)
};
int main() {
// Correct Declaration: Create an array of 100 Employee structures
struct Employee employees[100];
int count = 0; // Tracks the number of employees entered
int i;
// We can use the name field in the struct directly, no need for a temp buffer
printf("Enter employee details\n");
// Loop for data input (max 100 entries)
for (i = 0; i < 100; i++) {
printf("Employee Id : ");
// Check for end-of-input failure just in case
if (scanf("%d", &employees[i].id) != 1) {
break;
}
printf("\tEnter Name (\"xxx\" to quit) : ");
// Read directly into the structure's name field
scanf("%s", employees[i].name);
// Check if the user wants to quit inputting data
if (strcmp(employees[i].name, "xxx") == 0) {
break; // Exit the input loop
}
printf("\tEnter Designation : ");
scanf("%s", employees[i].designation);
count++; // Increment the counter of valid records
}
// --- Search Functionality ---
int searchId;
int found = 0;
printf("Enter Employee id : ");
scanf("%d", &searchId);
// Loop through the entered records to find a match
for (i = 0; i < count; i++) {
if (employees[i].id == searchId) {
// Print the details in the exact format requested
printf("Employee Name : %s\n", employees[i].name);
printf("Designation: %s\n", employees[i].designation);
found = 1;
break; // Exit the search loop once found
}
}
// Optional: Only display this if we failed to find the ID they requested
if (!found) {
printf("Employee with ID %d not found.\n", searchId);
}
return EXIT_SUCCESS;
}
OUTPUT:
Enter employee details
Employee Id : 114
Enter Name ("xxx" to quit) : arut
Enter Designation : Prof
Employee Id : 113
Enter Name ("xxx" to quit) : Arun
Enter Designation : IAS
Employee Id : 117
Enter Name ("xxx" to quit) : xxx
Enter Employee id : 114
Employee Name : arut
Designation: Prof
[Link] PROGRAM TO COUNT THE NUMBER OF ACCOUNT HOLDERS
DATE: WHOSE BALANCE IS LESS THAN THE MINIMUM BALANCE
USING SEQUENTIAL ACCESS FILE
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
struct customer
char name[20];
int acct_num;
float acct_balance;
};
int main(){
FILE *fp;
struct customer cust;
float min=5000;
fp=fopen("[Link]","w");
if(fp==NULL){
printf("\n Error opening [Link]\n\n");
exit(1);
printf("\n Enter accounts information\n\n");
int choice=1;
do
printf("\n Name:");
scanf("%s",[Link]);
printf("Acct Num:");
scanf("%d",&cust.acct_num);
printf("Balance:");
scanf("%f",&cust.acct_balance);
fwrite(&cust,sizeof(struct customer),1,fp);
printf("Press 1 to enter one more entry:\n");
scanf"%d",&choice);
}while(choice==1);
fclose(fp);
fp=fopen("[Link]","r");
if(fp==NULL){
printf("\n Error opening [Link]\n\n");
exit(1);
else
printf("\n File opened for reading: [Link]\n\n");
while(fread(&cust,sizeof(struct customer),1,fp)){
if(cust.acct_balance<=min) {
printf("\n Name=%s /tAcct Num =%d /tBalance=%.2f\n",
[Link],cust.acct_num,cust.acct_balance);
}}
fclose(fp);
return 0;
}
OUTPUT:
Enter accounts information
Name:arutselvi
Acct Num:22435
Balance:4567
Press 1 to enter one more entry:
1
Name:deepu
Acct Num:25456
Balance:35465
Press 1 to enter one more entry:
7
File opened for reading: [Link]
Name=arutselvi Acct Num =22435 Balance=4567.00
MINI PROJECT