Assignment C Programming Help
FIRST TASK
Solution
Task1.c
#include
#include
voidAddOne(char * input, char * output) {
int i = strlen(input) – 1;
strcpy(output,input);
while (i >= 0 && input[i] == ‘9’) output[i–] = ‘0’;
if (i < 0) {
strcpy(output+1,output);
output[0] = ‘1’;
}
else output[i] +=1;
}
int main() {
char output[100];
AddOne(“12345”,output);
printf(“Result = %s\n”,output);
AddOne(“9999999999999”,output);
printf(“Result = %s\n”,output);
AddOne(“1999999999999”,output);
printf(“Result = %s\n”,output);
return 0;
}
Task2.c
#include
#include
int max(int values[], int N) {
int i, max = values[0];
for(i=1; i
if (max < values[i]) max = values[i];
}
return max;
}
void histogram(char * result,int * values, intnumValues) {
int i, j, h;
h = max(values,numValues);
strcpy(result,””);
for (i=0; i<(h+2); i++) {
if (i==0 || i==h+1) {
for (j=0; j<(numValues+2); j++){
strcat(result,”*”);
}
if (i != h+1) strcat(result,”\n”);
}
else
for (j=0; j<(numValues+3); j++){
if (j==0 || j==numValues+1) strcat(result,”*”);
else if (j==numValues+2) strcat(result,”\n”);
else {
if (values[j-1] >= h-(i-1)) strcat(result,”X”);
elsestrcat(result,” “);
}
}
}
}
int main() {
int values1[10] = {1,0,3,1,2,4,5,6,2,2};
int values2[3] = {1,0,1};
char formatted[200];
char example[200] = “*****\n*X X*\n*****”;
histogram(formatted,values1, 10);
printf(“%s\n\n”,formatted);
histogram(formatted,values2,3);
printf(“%s\n”,formatted);
if (strcmp(example,formatted) == 0) printf(“This matches EXACTLY and is correct”);
return 0;
}
Task3.c
#include
intpureGold (intcols, int rows, int map[cols][rows], int i, int j) {
int x = i, y = j;
for (y = j-1; y <= j+1; y++)
for (x = i-1; x <= i+1; x++)
if (y<0 || y>=rows || x<0 || x>=cols || map[x][y] != 9) return 0;
return 1;
}
voidGoldRush(int *results, int rows, intcols, int map[cols][rows], int bonus) {
int i, j, gold = 0, puregold = 0;
for (i=0; i
for (j=0; j
if (map[i][j] == 9) {
gold++;
if (pureGold(cols, rows, map, i, j)) puregold++;
}
}
results[0] = gold;
results[1] = puregold;
}
int main() {
int map[15][15] = {{1,0,0,0,0,0,0,0,0,0,0,0,0,9,9},
{2,4,2,0,0,0,0,0,0,0,0,0,0,9,0},
{2,3,0,0,0,9,9,9,0,0,0,1,0,0,0},
{0,0,3,0,0,9,9,9,9,4,0,2,0,0,0},
{0,0,3,0,0,9,9,9,9,4,9,9,9,0,0},
{0,0,0,4,0,9,9,9,0,0,9,9,9,0,0},
{0,0,0,6,9,0,0,0,0,0,9,9,9,1,2},
{0,9,9,9,0,0,0,1,0,0,0,0,0,0,2},
{0,9,9,9,8,0,0,1,0,0,0,0,0,0,0},
{0,8,0,6,0,0,0,1,0,0,9,0,0,0,0},
{0,0,0,0,0,7,0,2,0,0,0,9,9,0,0},
{0,0,0,0,6,7,7,2,0,0,0,0,9,9,0},
{0,0,0,0,0,8,0,2,0,5,0,0,9,0,0},
{0,0,0,0,0,8,0,2,3,6,5,4,0,0,0},
{0,0,0,0,0,0,0,2,0,0,0,2,0,0,0}
};
int results[2];
GoldRush(results, 15, 15, map, 0);
printf(“Searching for gold!\n”);
printf(” Total gold = %d\n”,results[0]);
printf(” Pure gold = %d\n”,results[1]);
return 0;
}