Subject: Principles of Programming using C(BPOPS103)
1. Define an Array? List the operations on One- dimensional arrays? Explain how to declare and
store values in an array with an example.
An array is a collection of elements. Typically, these elements are of the same data type and are stored
in contiguous memory locations.
Operations on One-Dimensional Arrays
Traversal: Accessing each element of the array.
Insertion: Adding a new element at a specific position.
Deletion: Removing an element from a specific position.
Searching: Finding the location of an element within the array.
Updating: Changing the value of an element at a specific index.
Sorting: Arranging elements in a particular order (ascending or descending).
Merging: Combining two arrays into one.
Declaring and Storing Values in an Array
Example in C:
#include <stdio.h>
int main() {
// Declaration and Initialization of an array
int numbers[5] = {10, 20, 30, 40, 50};
// Accessing and displaying the elements of the array
for (int i = 0; i < 5; i++) {
printf("Element at index %d: %d\n", i, numbers[i]);
}
return 0;
}
2. Define structure. How to declare, initialize and access the members of a structure by taking an
example. Implement structures to read, write and compute average- marks of the students, list
the students scoring above and below the average marks for a class of N students.
In C, a structure (also called struct) is a user-defined data type that allows you to group together
variables of different data types under a single name.
To declare a structure, use the struct keyword
struct Person {
char name[50];
int age;
float height;
};
Accessing Members of a Structure
Members of a structure are accessed using the dot (.) operator for normal variables and the arrow (->)
operator for pointers.
#include <stdio.h>
#include <string.h>
// Structure declaration
struct Person {
char name[50];
int age;
float height;
};
int main() {
// Declaring and initializing a structure variable
struct Person person1;
// Initializing members of the structure
strcpy(person1.name, "John Doe");
person1.age = 30;
person1.height = 5.9;
// Accessing and displaying the structure members
printf("Name: %s\n", person1.name);
printf("Age: %d\n", person1.age);
printf("Height: %.1f\n", person1.height);
return 0;
}
Implement structures to read, write and compute average- marks of the students, list the
students scoring above and below the average marks for a class of N students.
#include<stdio.h>
struct Student {
char name[20];
float sub1, sub2, sub3;
float total, avg;
};
int main(){
struct Student s[20];
int n, i;
float classAvg, totalAvg = 0.0;
printf("Enter the total number of students\n");
scanf("%d", &n);
for(i=0;i<n;i++){
printf("\nEnter the name of student %d\n",i+1);
scanf("%s", s[i].name);
printf("Enter the marks of student %d\n",i+1);
scanf("%f%f%f", &s[i].sub1, &s[i].sub2, &s[i].sub3);
s[i].total = s[i].sub1 + s[i].sub2 + s[i].sub3;
s[i].avg = s[i].total / 3;
totalAvg = totalAvg + s[i].avg;
}
classAvg = totalAvg / n;
printf("\nClass Average=%f\n",classAvg);
for(i=0;i<n;i++){
printf("\n Total marks scored by %s is %f\n", s[i].name, s[i].total);
printf("Average marks scored: %f\n", s[i].avg);
if(s[i].avg >= classAvg){
printf("%s has scored above average\n", s[i].name);
} else {
printf("%s has scored below average\n", s[i].name);
}
}
return 0;
3. Define union. How are they different from structures? Create a Structure employee with
members emp_no, emp_name, emp_salary with appropriate datatypes. Write a program to read
and display the information of N employees of an organization.
A union in programming is a user-defined data type, similar to a structure, but with a key
difference: all members of a union share the same memory location. This means that at any
given time, a union can store a value for only one of its members, and the size of the union
is determined by the size of its largest member.
Differences Between Structures and Unions
Aspect Structure Union
Allocates separate
Memory All members share the
memory for each
Allocation same memory location.
member.
The size of a structure is The size of a union is
Size the sum of the sizes of its the size of its largest
members. member.
Can hold multiple values Can hold only one
Usage
simultaneously. value at a time.
Used when variables
Used when multiple related
share the same memory
Use variables need to be grouped
location and only one
Case together and accessed
variable is needed at a
simultaneously.
time.
Using a Union
#include <stdio.h>
#include <string.h>
// Union declaration
union Data {
int i;
float f;
char str[20];
};
int main() {
// Declaring a union variable
union Data data;
// Assigning an integer value
data.i = 10;
printf("Data as integer: %d\n", data.i);
// Assigning a float value
data.f = 220.5;
printf("Data as float: %.1f\n", data.f);
// Assigning a string value
strcpy(data.str, "Hello");
printf("Data as string: %s\n", data.str);
// Observing how the value of `i` gets overwritten
printf("After assigning string, data as integer: %d\n", data.i);
return 0;
}
Create a Structure employee with members emp_no, emp_name, emp_salary with appropriate
datatypes. Write a program to read and display the information of N employees of an
organization.
#include <stdio.h>
// Structure definition
struct Employee {
int emp_no;
char emp_name[50];
float emp_salary;
};
int main() {
int N;
// Ask the user for the number of employees
printf("Enter the number of employees: ");
scanf("%d", &N);
// Declare an array of structure to store information of N employees
struct Employee employees[N];
// Reading information for each employee
for (int i = 0; i < N; i++) {
printf("\nEnter details for employee %d:\n", i + 1);
printf("Employee Number: ");
scanf("%d", &employees[i].emp_no);
printf("Employee Name: ");
scanf(" %[^\n]%*c", employees[i].emp_name); // Read string with spaces
printf("Employee Salary: ");
scanf("%f", &employees[i].emp_salary);
}
// Displaying the information of each employee
printf("\nEmployee Details:\n");
for (int i = 0; i < N; i++) {
printf("\nEmployee %d:\n", i + 1);
printf("Employee Number: %d\n", employees[i].emp_no);
printf("Employee Name: %s\n", employees[i].emp_name);
printf("Employee Salary: %.2f\n", employees[i].emp_salary);
}
return 0;
}
4. Define string. Explain any 4 string manipulation functions with suitable Examples.
A string is a sequence of characters terminated by a null character (\0). In C, strings are represented as
arrays of characters. For example, "Hello" is a string with characters 'H', 'e', 'l', 'l', 'o', and a
terminating null character.
String Manipulation Functions
1. strlen(): String Length, Returns the length of the string, excluding the null terminator.
2. strcpy(): String Copy. Copies one string into another.
3. strcat(): String Concatenation. Appends one string to the end of another.
4. strcmp(): String Comparison. Compares two strings lexicographically
strlen(): Calculates the length of a string.
strcpy(): Copies one string into another.
strcat(): Concatenates two strings.
strcmp(): Compares two strings and returns an integer based on their lexicographical order.
Example:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
printf("Length of the string: %zu\n", strlen(str));
return 0;
}
Output: Length of the string: 13
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "OpenAI";
char destination[20];
strcpy(destination, source);
printf("Copied string: %s\n", destination);
return 0;
}
Output: Copied string: OpenAI
#include <stdio.h>
#include <string.h>
int main() {
char str1[20] = "Hello";
char str2[] = ", World!";
strcat(str1, str2);
printf("Concatenated string: %s\n", str1);
return 0;
}
Output: Concatenated string: Hello, World!
#include <stdio.h>
#include <string.h>
int main() {
char str1[] = "Apple";
char str2[] = "Orange";
int result = strcmp(str1, str2);
if (result < 0) {
printf("str1 is less than str2\n");
} else if (result > 0) {
printf("str1 is greater than str2\n");
} else {
printf("str1 is equal to str2\n");
}
return 0;
}
Output: str1 is less than str2
5. Explain the different parameter passing methods in functions. Write a recursive C Program to
find the factorial of a number.
In programming, parameter passing methods determine how arguments are passed to functions and
how the function interacts with the caller. The main parameter passing methods are:
1. Pass by Value
2. Pass by Reference
Pass by Value:
A copy of the actual value is passed to the function. The function operates on the copy, so changes
made to the parameter inside the function do not affect the original value.
#include <stdio.h>
void addOne(int x) {
x = x + 1;
printf("Inside function: %d\n", x);
}
int main() {
int num = 5;
addOne(num);
printf("Outside function: %d\n", num);
return 0;
}
Output:
Inside function: 6
Outside function: 5
Pass by Reference:
Description: A reference (or address) to the actual variable is passed to the function. The function can
modify the original variable.
#include <stdio.h>
void addOne(int *x) {
*x = *x + 1;
}
int main() {
int num = 5;
addOne(&num);
printf("After function call: %d\n", num);
return 0;
}
Output:
After function call: 6
6. Write a C program to implement string operations such as compare, concatenate, and find
string length without using built-in functions.
#include <stdio.h>
// Function to find the length of a string
int stringLength(char *str) {
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
// Function to compare two strings
int stringCompare(char *str1, char *str2) {
int i = 0;
while (str1[i] != '\0' && str2[i] != '\0') {
if (str1[i] != str2[i]) {
return str1[i] - str2[i]; // Difference of ASCII values
}
i++;
}
// If strings are of different lengths
if (str1[i] != '\0' || str2[i] != '\0') {
return str1[i] - str2[i];
}
return 0; // Strings are equal
}
// Function to concatenate two strings
void stringConcatenate(char *str1, char *str2, char *result) {
int i = 0, j = 0;
// Copy str1 to result
while (str1[i] != '\0') {
result[i] = str1[i];
i++;
}
// Append str2 to result
while (str2[j] != '\0') {
result[i] = str2[j];
i++;
j++;
}
result[i] = '\0'; // Null-terminate the result string
}
int main() {
char str1[100], str2[100], result[200];
int choice;
printf("Enter the first string: ");
gets(str1);
printf("Enter the second string: ");
gets(str2);
do {
printf("\nChoose an operation:\n");
printf("1. Find length of strings\n");
printf("2. Compare strings\n");
printf("3. Concatenate strings\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // To consume the newline character left by scanf
switch (choice) {
case 1: {
printf("Length of string 1: %d\n", stringLength(str1));
printf("Length of string 2: %d\n", stringLength(str2));
break;
}
case 2: {
int cmp = stringCompare(str1, str2);
if (cmp == 0) {
printf("The strings are equal.\n");
} else if (cmp > 0) {
printf("String 1 is greater than String 2.\n");
} else {
printf("String 1 is less than String 2.\n");
}
break;
}
case 3: {
stringConcatenate(str1, str2, result);
printf("Concatenated string: %s\n", result);
break;
}
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice. Please try again.\n");
}
} while (choice != 4);
return 0;
}
OR
#include<stdio.h>
#include<string.h>
void stringLength(char s1[50], char s2[50]);
void stringConcatenation(char s1[50], char s2[50]);
void stringCompare(char s1[50], char s2[50]);
int main(){
char a[50], b[50];
printf("Enter the first String:\n");
scanf("%s", a);
printf("Enter the second String:\n");
scanf("%s", b);
stringLength(a, b);
stringCompare(a,b);
stringConcatenation(a,b);
return 0;
}
void stringLength(char s1[50], char s2[50]) {
int len1, len2;
len1 = strlen(s1);
len2 = strlen(s2);
printf("\nLength of first string is %d", len1);
printf("\nLength of second string is %d", len2);
}
void stringConcatenation(char s1[50], char s2[50]) {
printf("\nConcatenated String is %s\n", strcat(s1,s2));
}
void stringCompare(char s1[50], char s2[50]) {
if(strcmp(s1,s2) == 0){
printf("\nStrings are equal");
}else {
printf("\nStrings are not equal");
}
}
7. Write a C program to search an element using Binary Search (For numerals).
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
int a[10],n,i,key,low,high,mid;
//clrscr();
printf("enter the value for n\n");
scanf("%d",&n);
printf("the elements in ascending order....\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("the elements of array are\n");
for(i=0;i<n;i++)
printf("%d\n",a[i]);
printf("enter the key element for search\n");
scanf("%d",&key);
low=0;
high=n-1;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==key)
{
printf("the %d no is found in %d position \n",key,mid+1);
getch();
exit(0);
}
else
if(a[mid]<key)
low=mid+1;
else
high=mid-1;
}
printf("the %d no is not found\n",key);
getch();
}