0% found this document useful (0 votes)
9 views3 pages

C Programs for String and Math Operations

Uploaded by

oma91029
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)
9 views3 pages

C Programs for String and Math Operations

Uploaded by

oma91029
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

1] Character Replacement Program

--------------------------------
#include <stdio.h>

void replaceChar(char str[], char oldChar, char newChar) {


int i = 0;
while (str[i] != '\0') {
if (str[i] == oldChar) {
str[i] = newChar;
}
i++;
}
}

int main(int argc, char *argv[]) {


if (argc != 4) {
printf("Usage: %s <string> <oldChar> <newChar>\n", argv[0]);
return 1;
}

char *str = argv[1];


char oldChar = argv[2][0];
char newChar = argv[3][0];

replaceChar(str, oldChar, newChar);

printf("Modified String: %s\n", str);


return 0;
}

2] Sum of Array Elements Using Pointers


---------------------------------------
#include <stdio.h>

int main() {
int n, i, sum = 0;
int *ptr;

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


scanf("%d", &n);

int arr[n];

printf("Enter %d elements: ", n);


for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}

ptr = arr;

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


sum += *(ptr + i);
}
printf("Array elements: ");
for (i = 0; i < n; i++) {
printf("%d ", *(ptr + i));
}

printf("\nSum of array elements: %d\n", sum);


return 0;
}

3] Minimum, Maximum, and Average Finder


---------------------------------------
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[]) {


if (argc != 4) {
printf("Error: Please enter exactly three integers as command-line
arguments.\n");
return 1;
}

int num1 = atoi(argv[1]);


int num2 = atoi(argv[2]);
int num3 = atoi(argv[3]);

int min = (num1 < num2) ? ((num1 < num3) ? num1 : num3) : ((num2 < num3) ? num2 :
num3);
int max = (num1 > num2) ? ((num1 > num3) ? num1 : num3) : ((num2 > num3) ? num2 :
num3);

float avg = (num1 + num2 + num3) / 3.0;

printf("Minimum: %d\n", min);


printf("Maximum: %d\n", max);
printf("Average: %.2f\n", avg);

return 0;
}

4] Power Calculation
---------------------
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main(int argc, char *argv[]) {


if (argc != 3) {
printf("Usage: %s <base> <exponent>\n", argv[0]);
return 1;
}

double base = atof(argv[1]);


double exponent = atof(argv[2]);
double result = pow(base, exponent);
printf("%.2f raised to the power of %.2f is %.2f\n", base, exponent, result);
return 0;
}

You might also like