Assignment 1 start - // Print both out to prove that it...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
// Arup Guha // 5/27/09 - COP 3502 // An example very similar with respect to the beginning of assignment #1. // The key difference is that here, everything is done in main. (This is not // a trivial difference.) / #include <stdio.h> #include <stdlib.h> #include <string.h> # int main() { char numOne[201]; char numTwo[201]; // read in input from user. printf("enter first number\n"); scanf("%s", numOne); printf("enter second number\n"); scanf("%s", numTwo); printf("You entered %s and %s\n", numOne, numTwo); // create two integer pointers, which will point to our int arrays // that store the number. int *digitsOne; int *digitsTwo; // Allocate space for first int digitsOne = (int*)(malloc(sizeof(int)*strlen(numOne))); int i; // convert each char to an int and store this digit. for (i=0; i<strlen(numOne); i++) digitsOne[i] = (int)(numOne[i]); // Do the same for the second operand. digitsTwo = (int*)(malloc(sizeof(int)*strlen(numTwo))); for (i=0; i<strlen(numTwo); i++) digitsTwo[i] = (int)(numTwo[i]);
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Background image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: // Print both out to prove that it worked. for (i=0; i&lt;strlen(numOne); i++) printf(&quot;%d &quot;, digitsOne[i]); printf(&quot;\n&quot;); for (i=0; i&lt;strlen(numTwo); i++) printf(&quot;%d &quot;, digitsTwo[i]); printf(&quot;\n&quot;); // Store addition answer here. int* digitsThree; int max = strlen(numOne); if (strlen(numTwo) &gt; max) max = strlen(numTwo); // Allocating enough space (minus carry) for the answer. digitsThree = (int*)(malloc(sizeof(int)*max)); // Add up each digit one by one. (Not the exact correct way to add. for (i=0; i&lt;max; i++) { int sum = 0; // Avoid array out of bounds errors. if (i &lt; strlen(numOne)) sum += digitsOne[i]; if (i &lt; strlen(numTwo)) sum += digitsTwo[i]; digitsThree[i] = sum; } // Print out answer. for (i=0; i&lt;max; i++) printf(&quot;%d &quot;, digitsThree[i]); printf(&quot;\n&quot;); // Free all dynamically allocated memory. free(digitsOne); free(digitsTwo); free(digitsThree); system(&quot;PAUSE&quot;); return 0; }...
View Full Document

This document was uploaded on 07/12/2009.

Page1 / 2

Assignment 1 start - // Print both out to prove that it...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online