0% found this document useful (0 votes)
97 views30 pages

C Programming Problem Solving Guide

My pps file

Uploaded by

divyathakran389
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
97 views30 pages

C Programming Problem Solving Guide

My pps file

Uploaded by

divyathakran389
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DEENBANDHU CHHOTU RAM UNIVERSITY, MURTHAL

SESSION: JAN 2024 - MAY 2024


Course CODE: CSE 102 C

PROGRAMMING WITH PROBLEM SOLVING FILE

NAME: Divya thakran SUBMITTED TO: DR. AJMER SINGH


ROLL NO.: 23001001029 DEPARTMENT: CSE
BRANCH: CSE
SECTION: A
INDEX
[Link] DATE programs REMARKs
1. Write a program in C to find the largest element in an array.

2. Write a program in C to find the average of elements in an array.

3. Write a program in C to search for an element in an array using


linear search.

4. Write a program in C to concatenate two strings without using


library functions.

5. Write a program in C to swap two numbers using pointers.

6. Write a program in C to reverse an array using pointers.

7. Write a program in C to find the sum of elements in an array


using pointers

8. Write a program in C to define a structure representing a student


with attributes like name, roll number, and marks.

9. Write a program in C to calculate the total marks and average


marks of students using structures.
10. Write a program in C to find the student with the highest marks
using structures.

11. Write a program in C to find the factorial of a number using a


recursive function.

12. Write a program in C to check whether a number is prime using a


function.

13. Write a program in C to calculate the area of a circle using a


function.
14. Write a program in C to create and write data to a text file.

15. Write a program in C to read data from a text file and display it.

16. Write a program in C to copy contents from one file to another.

17. Write a program in C to dynamically allocate memory for an


array and input its elements.

18. Write a program in C to use #define to define constants for


mathematical constants like pi.

19. Write a program in C to demonstrate the use of #ifdef, #ifndef,


#else, and #endif directives.
Program 1: Write a program in C to find the largest element
in an array.
Code:

int main()

int array[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};

int i, largest;

largest = array[0];

for(i = 1; i < 10; i++)

if( largest < array[i] )

largest = array[i];

printf("Largest element of array is %d", largest);

return 0;

Output :
Program 2: Write a program in C to find the average of
elements in an array.
#include <stdio.h>

int main()

int n, i;

float num[100], sum = 0.0, avg;

printf("Enter the numbers of elements: ");

scanf("%d", &n);

while (n > 100 || n < 1)

printf("Error! number should in range of (1 to 100).\n");

printf("Enter the number again: ");

scanf("%d", &n);

for (i = 0; i < n; ++i)

printf("%d. Enter number: ", i + 1);

scanf("%f", &num[i]);

sum += num[i];

avg = sum / n;

printf("Average = %.2f", avg);

return 0;

Output:
Program 3: Write a program in C to search for an element in
an array using linear search.
#include <stdio.h>
void linear_search(int a[], int n, int key)
{
int i, count = 0;
for(i = 0; i < n; i++)
{
if(a[i] == key)
{
printf("The element is found at %d position\n", i+1);
count = count + 1;
}
}

if(count == 0)
printf("The element is not present in the array\n");
}

int main()
{
int i, n, key;
n = 6;
int a[10] = {12, 44, 32, 18, 4, 10};
key = 18;
linear_search(a, n, key);
key = 23;
linear_search(a, n, key);
return 0;
}

Output:
Program 4: Write a program in C to concatenate two strings
without using library functions.
#include<stdio.h>
void main()
{
char str1[25] , str2[25];
int i=0,j=0;
printf("\nEnter First String:");
gets(str1);
printf("\nEnter Second String:");
gets(str2);
while(str1[i]!='\0')
i++;
while(str2[j]!='\0')
{
str1[i]=str2[j];
j++;
i++;
}
str1[i]='\0';
printf("\nConcatenated String is %s",str1);
}

Output:
Program 5: Write a program in C to swap two numbers
using pointers.
#include <stdio.h>
void swap(int *p1, int *p2)
{
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
int main()
{
int x, y;
printf("Enter Value of x ");
scanf("%d", &x);
printf("\nEnter Value of y ");
scanf("%d", &y);
swap(&x, &y);
printf("\nAfter Swapping: x = %d, y = %d", x, y);
return 0;
}

Output:
Program 6: Write a program in C to reverse an array using
pointers.
#include <stdio.h>
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void reverse(int array[], int array_size)
{
int *pointer1 = array,
*pointer2 = array + array_size - 1;
while (pointer1 < pointer2) {
swap(pointer1, pointer2);
pointer1++;
pointer2--;
}
}
void print(int* array, int array_size)
{
int *length = array + array_size,
*position = array;
printf("Array = ");
for (position = array; position < length; position++)
printf("%d ", *position);
}
int main()
{
int array[] = { 2, 4, -6, 5, 8, -1 };

printf("Original ");
print(array, 6);

printf("Reverse ");
reverse(array, 6);
print(array, 6);
return 0;
}

Output:
Program7: Write a program in C to find the sum of elements
in an array using pointers.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sum(int arr[], int n)
{
if (n == 0) {
return 0;
}
else {
return arr[0] + sum(arr + 1, n - 1);
}
}
int main()
{
int arr[] = { 12, 3, 4, 15 };
int n = sizeof(arr) / sizeof(arr[0]);
printf("%d", sum(arr, n));
return 0;
}

Output:
Program 8: Write a program in C to define a structure
representing a student with attributes like name, roll
number, and marks.
#include <stdio.h>
struct Student {
char* firstName[50];
int roll_number;
float marks;
} s[5];
int main()
{
int i;
printf("Enter information of students:\n");
for (i = 0; i < 5; ++i) {
s[i].roll = i + 1;
printf("\nFor roll number%d,\n", s[i].roll);
printf("Enter first name: ");
scanf("%s", s[i].firstName);
printf("Enter marks: ");
scanf("%f", &s[i].marks);
}
printf("Displaying Information:\n\n");

for (i = 0; i < 5; ++i)


{
printf("\nRoll number: %d\n", i + 1);
printf("First name: ");
puts(s[i].firstName);
printf("Marks: %.1f", s[i].marks);
printf("\n");
}
return 0;
}

Output:
Program 9: Write a program in C to calculate the total marks
and average marks of students using structures.
#include <stdio.h>
struct student
{
int sub1;
int sub2;
int sub3;
};
void main()
{
struct student s[10];
int i,total=0,av;

for(i=0;i<=2;i++)
{
printf("\nEnter Marks in Three Subjects");

scanf("%d%d%d",&s[i].sub1,&s[i].sub2,&s[i].sub3);

total=s[i].sub1+s[i].sub2+s[i].sub3;

printf("\nTotal marks of s[%d]Student=%d",i,total);

av= total/3;
printf(“\n average marks of students =%d”,av);
}

Output:
Program 10: Write a program in C to find the student with
the highest marks using structures.
#include<stdio.h>
struct student
{
char name[30];
int roll;
float marks;
};

int main()
{
/* Declaration of array of structure */
struct student s[20], lg;
int i,n;

printf("Enter n:\n");
scanf("%d",&n);
for(i=0;i< n;i++)
{
printf("Enter name, roll and marks of student:\n");
scanf("%s%d%f",s[i].name, &s[i].roll, &s[i].marks);
}
lg = s[0];
for(i=0;[Link])
{
lg = s[i];
}
}

Output:
Program 11: Write a program in C to find the factorial of a
number using a recursive function.
#include<stdio.h>
long int multiplyNumbers(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d",&n);
printf("Factorial of %d = %ld", n, multiplyNumbers(n));
return 0;
}
long int multiplyNumbers(int n) {
if (n>=1)
return n*multiplyNumbers(n-1);
else
return 1;
}

Output:
Program 12: Write a program in C to check whether a
number is prime using a function.
#include <stdio.h>
void checkPrime(int N)
{
int flag = 1;
for (int i = 2; i <= N / 2; i++) {

if (N % i == 0) {
flag = 0;
break;
}
}
if (flag) {
printf("The number %d is a Prime Number\n", N);
}
else {
printf("The number %d is not a Prime Number\n", N);
}
return;
}

int main()
{
int N = 546;
checkPrime(N);
return 0;
}

Output:
Program 13: Write a program in C to calculate the area of a
circle using a function.
#include <math.h>
#include <stdio.h>
#define PI 3.142

// Function to find the area of


// of the circle
double findArea(int r) { return PI * r * r; }

// Driver code
int main()
{
printf("Area is %f", findArea(5));
return 0;
}

Output:
Program 14: Write a program in C to create and write data
to a text file.
#include <stdio.h>

main() {

FILE *fp;

char buff[255];

fp = fopen("/tmp/[Link]", "r");

fscanf(fp, "%s", buff);

printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);

printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);

printf("3: %s\n", buff );

fclose(fp);

Output:
Program 15: Write a program in C to read data from a text
file and display it.
#include <stdio.h>
#include<ctype.h>
#include<stdlib.h>
int main(){
char ch;
FILE *fp;
fp=fopen("[Link]","w");
printf("enter the [Link] cntrl Z:");
while((ch = getchar())!=EOF){
putc(ch,fp);
}
fclose(fp);
fp=fopen("[Link]","r");
printf("text on the file:");
while ((ch=getc(fp))!=EOF){
if(ch == ',')
printf("\t\t");
else
printf("%c",ch);
}
fclose(fp);
return 0;
}
Output:
Program 16: Write a program in C to copy contents from
one file to another.
#include <stdio.h>
#include <stdlib.h> // For exit()
int main(){
FILE *fptr1, *fptr2;
char filename[100], c;
printf("Enter the filename to open for reading ");
scanf("%s",filename);
// Open one file for reading
fptr1 = fopen(filename, "r");
if (fptr1 == NULL){
printf("Cannot open file %s ", filename);
exit(0);
}
printf("Enter the filename to open for writing ");
scanf("%s", filename);
// Open another file for writing
fptr2 = fopen(filename, "w");
if (fptr2 == NULL){
printf("Cannot open file %s ", filename);
exit(0);
}
// Read contents from file
c = fgetc(fptr1);
while (c != EOF){
fputc(c, fptr2);
c = fgetc(fptr1);
}
printf("Contents copied to %s", filename);
fclose(fptr1);
fclose(fptr2);
return 0;}

output:
Program 17: Write a program in C to dynamically allocate
memory for an array and input its elements.
#include <stdio.h>
#include <stdlib.h>
int main()
{

// address of the block created hold by this pointer


int* ptr;
int size;

// Size of the array


printf("Enter size of elements:");
scanf("%d", &size);

// Memory allocates dynamically using malloc()


ptr = (int*)malloc(size * sizeof(int));

// Checking for memory allocation


if (ptr == NULL) {
printf("Memory not allocated.\n");
}
else {

// Memory allocated
printf("Memory successfully allocated using "
"malloc.\n");

// Get the elements of the array


for (int j = 0; j < size; ++j) {
ptr[j] = j + 1;
}
// Print the elements of the array
printf("The elements of the array are: ");
for (int k = 0; k < size; ++k) {
printf("%d, ", ptr[k]);
}
}
return 0;
}

Output:
Program 18: Write a program in C to use #define to define
constants for mathematical constants like pi.
#include <stdio.h>
#define PI 3.14159 // <-- Define constant PI
int main()
{
float radius, area;
printf("Enter radius: ");
scanf("%f", &radius);

area = PI * radius * radius;

printf("Area = %f", area);

return 0;
}

Output:
Program 19: Write a program in C to demonstrate the use of
#ifdef, #ifndef, #else, and #endif directives.
#include <stdio.h>
#define gfg 7
#if gfg > 200
#undef gfg
#define gfg 200
#elif gfg < 50
#undef gfg
#define gfg 50
#else
#undef gfg
#define gfg 100
#endif
void printValue(int value) { printf("%d", value); }
int main()
{
printValue(gfg); // gfg = 50
return 0;
}

Output:

Common questions

Powered by AI

To reverse an array using pointers in C, two pointers are used: one starting at the beginning of the array and the other at the end. By swapping elements at these pointer locations and incrementing/decrementing the pointers toward the middle, the array can be reversed efficiently. Benefits of using pointers include reduced memory footprint as pointers directly manipulate the original data locations without needing additional temporary arrays or excessive memory allocation. The provided code in Source 1 effectively demonstrates this by utilizing a loop over the pointers for swapping elements without additional array overhead.

The implementation of a linear search algorithm in C involves iterating over each element of the array and comparing it with the key element you are searching for. The key components to consider include the loop for iterating through the array, a mechanism to count occurrences or to flag when the element is found, and logic to print output depending on whether the element is present or not. This is demonstrated in the code from Source 3, where the function linear_search iterates through the array 'a' of size 'n', and checks if 'key' is present at each index. If found, it prints the position; if not, it indicates the element is absent in the array.

Conditionally compiling code segments in C is achieved using preprocessor directives such as #ifdef, #ifndef, #else, and #endif. #ifdef checks if a macro is defined, and if it is, the block following the directive is compiled. Conversely, #ifndef checks if a macro is not defined. #else provides an alternative block that is compiled if the previous conditions are not met. #endif is used to close the directives. Collectively, these directives allow for conditional compilation, facilitating different configurations or environments without code duplication. These concepts are demonstrated in Source 5, which includes logic to set a constant value based on these conditions.

Structures in C are user-defined data types that group different variables under a single name, allowing for the management of related data items as a cohesive unit. In the context of storing student information, structures can hold attributes such as name, roll number, and marks, enabling easy data manipulation and improved code organization. They provide advantages like clear data representation, better manageability, and encapsulation, reducing complexity in large programs. This is illustrated in Source 3 where a student structure is used to efficiently manage multiple students' details.

Validating user input in C is crucial to avoid undefined behavior or program crashes that can occur from invalid values, such as an array size being out of bounds. Effective input validation involves checking if the user-provided values fall within a specific and acceptable range before proceeding with computation or memory allocation, as shown in Source 2. This ensures program robustness and reliability. Methods include looping input requests until valid entries are received, using conditional statements to validate inputs, and providing clear user feedback on errors.

Finding the largest element in an array involves initializing a variable to hold the largest value, initially set to the first element, and then iterating over the array to compare each element against this variable, updating it when a larger element is found. This simple linear search is implemented by traversing the array once, ensuring time complexity of O(n), as shown in the example from Source 1. Here, a for loop is used to traverse the array, and the value of 'largest' is updated every time a larger array element is encountered.

Swapping two numbers using pointers in C involves using the address of the numbers. Pointers allow direct manipulation of the variables' memory without copying the data. This can be efficient in terms of memory and execution time. In the provided example , the function 'swap' takes two integer pointers, swaps the values they point to by using a temporary variable, which minimizes data copying and allows the original variables to be updated directly from within the function.

File handling in C involves using standard library functions like fopen, fprintf, fscanf, fgets, and fclose to manage file writing and reading operations. Common issues include accessing non-existent files, permissions, and file closing errors, which can be resolved by proper error checking after each file operation, such as verifying file pointers are not NULL after fopen and ensuring fclose is called to securely release file resources. Source 4 exemplifies these operations, showing error messages and checks to ensure files are correctly opened and closed, demonstrating best practices in file handling.

Recursive functions in C call themselves to solve a problem in smaller increments, while iterative functions use loops to achieve the same result. When calculating factorials, a recursive function helps in breaking down the problem using the mathematical relationship n! = n*(n-1)!, as demonstrated in Source 4. To ensure correct operation, key considerations include a base case to stop recursion and prevent infinite looping, ensuring each recursive call progresses toward this base case. Recursive functions generally consume more stack memory and can be less efficient than their iterative counterparts.

Dynamic memory allocation in C for an array is done using the malloc or calloc functions, which reserve memory at runtime. The malloc function is commonly used to allocate a block of memory for a specified number of elements. After allocation, it's crucial to check if the memory was successfully allocated by verifying if the pointer returned is not NULL. Proper error handling includes checking the pointer and terminating the program or freeing resources if memory allocation fails, as illustrated in Source 4. In this source, the allocated memory is checked immediately after calling malloc, and a failure message is output if the pointer is NULL.

You might also like