Introduction to programming in C Week 1 Answers
Question 1
#include <stdio.h>
int main() {
int hundred, ten, one, price;
scanf("%d %d %d %d", &hundred, &ten, &one, &price);
// Check for non-negative values
if (hundred < 0 || ten < 0 || one < 0 || price < 0) {
printf("0\n");
return 0;
}
// Check if the item is affordable
if (price <= (hundred * 100 + ten * 10 + one)) {
printf("1");
} else {
printf("0");
}
return 0;
}
Question 2
#include <stdio.h>
int main() {
int a, b, c;
// Sample input 1: 9 10 1
// Sample input 2: -4 3 9
// Input three distinct integers
printf(" ");
scanf("%d %d %d", &a, &b, &c);
// Check for distinct integers
if (a == b || a == c || b == c) {
printf("Please enter distinct integers.\n");
return 0;
}
// Determine the second largest number
int secondLargest;
if ((a > b && a < c) || (a < b && a > c))
secondLargest = a;
else if ((b > a && b < c) || (b < a && b > c))
secondLargest = b;
else
secondLargest = c;
// Output the result
printf("%d", secondLargest);
return 0;
}
Question 3
#include <stdio.h>
int main() {
// Input coefficients of the first equation
int a1, b1, c1;
printf(" ");
scanf("%d %d %d", &a1, &b1, &c1);
// Input coefficients of the second equation
int a2, b2, c2;
printf(" ");
scanf("%d %d %d", &a2, &b2, &c2);
// Apply Gaussian elimination method
int factor = a2 / a1;
a2 -= factor * a1;
b2 -= factor * b1;
c2 -= factor * c1;
// Solve for y
int y = c2 / b2;
// Substitute y into the first equation to find x
int x = (c1 - b1 * y) / a1;
// Output the solutions
printf(" %d %d", x, y);
return 0;
}
No comments