Wednesday, May 2, 2007

WASE LOOPS 15--4-07

Structured Programming
Rajesh Kulkarni
Loops
 Used to repeat the same instruction(s) over and over again.
Loops
 C provides some flexible ways of deciding how many times to loop, or when to exit a loop.
 for, while, do-while loops.
 Entry controlled loops
 Exit controlled loops
while loops
while (condition)
{
statement(s);
}
Compute 10!
What is 1*2*3*4*5*6*7*8*9*10 (ten factorial) ?
x = 1*2*3*4*5*6*7*8*9*10;
Tracing the loop
# i x i<9?
A ? 1
B 2 1
C 2 1 T
D 2 2
E 3 2
C 3 2 T
D 3 6
E 4 6
C 4 6 T
D 4 24
E 5 24
... ... ...
E 10 362880
C 10 362880 F
G (print 362880)

Double your money
 Suppose your Rs 10000 is earning interest at 1% per month. How many months until you double your money ?

Maximum of inputs
printf (“Enter positive numbers to max, end with -1.0\n”);
max = 0.0;
count = 0;
scanf(“%f”, &next);
while (next != 1.0) {
if (next > max)
max = next;
count++;
scanf(“%f”, &next);
}
printf (“The maximum number is %f\n”, max) ;
Example - factorial
#include
int main()
{
int i, n, fact = 1;
printf("Enter a number\n");
scanf("%d", &n);
i=1; /* this is the counter */
while (i<=n)
{
fact = fact*i;
i++; /* equivalent to i = i+1 */
}
printf("the factorial is %d\n", fact);
return 0;
}
Example – fibonacci series
fibonacci.c
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
Fibonacci – step by step
fib1 = 0;
fib2 = 1;

printf("%d ", fib1);

while (fib2 < lim)
{
printf("%d ", fib2);
fib_next = fib1 + fib2;
fib1 = fib2;
fib2 = fib_next;
}

printf("\n");
getchar
 getchar() gets a single character from the user.
 Requires including stdio.h
 Returns a non-positive number on failure.
 Similar to scanf.


Putchar
 putchar(char) prints out the character inside the brackets.
 Requires including stdio.h
 Similar to printf.

Example – lower-case to upper case.
low2up.c
Low2up – step by step
#include

int main()
{
char c;
char upper_c;

printf(“Enter a string: ");

c = getchar();
Low2up – step by step
#include

int main()
{
char c;
char upper_c;

printf(“Enter a string: ");

c = getchar();
Low2up – step by step
#include

int main()
{
char c;
char upper_c;

printf (“Enter a string: ");

c = getchar();
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Low2up – step by step
while (c != '\n' && c >= 0)
{
if (c >= 'a' && c <= 'z')
upper_c = c - 'a' + 'A';
else
upper_c = c;

/* Print the converted character.*/
putchar(upper_c);

/* Get the next character */
c = getchar();
}
putchar('\n');
Exercise
 Input:
 Two integers – A and B
 Output:
 How many times A contains B
 This is the result of the integer division A/B
 Note:
 Do not use the division operator!

Solution
#include

int main()
{
int a, b, res;

printf("Please enter two numbers.\n");
scanf("%d%d", &a, &b);

res = 0;
while ( (res+1) * b <= a)
res = res + 1;

printf("%d / %d = %d", a, b, res);
return 0;
}


Printing a 2-D Figure
 How would you print the following diagram?
* * * * *
* * * * *
* * * * *
Nested Loops
#define ROWS 3
#define COLS 5
...
row=1;
while (row <= ROWS) {
/* print a row of 5 *’s */
...
row++;
}
do while loops
do {
statement(s)
} while (expression);

 Similar to while loops
 Except the condition is evaluated after the loop body
 The loop body is always executed at least once, even if the expression is never true
Example – waiting for legal input
#include
int main()
{
int i;

printf("Please enter a positive number.\n");
do {

scanf("%d", &i);
if (i <= 0)
printf("Try again.\n");

} while (i<=0);

/* The program continues.... */
return 0;
}

do-while statement
do statement while (expression)

int main () {
char echo ;
do {
scanf (“%c”, &echo);
printf (“%c”,echo);
} while (echo != ‘\n’) ;
}
for loops
for loops are controlled by a counter variable.


for (c = begin; c <= end; c += inc)
{
loop body
}
for loops
 Absent of second expression is treated as true
 for(;;) is infinite.
for loop
for ( expression1; expression2; expression3) statement

expression1 (init) : initialize parameters
expression2 (test): test condition, loop continues if satisfied
expression3 (reinit): used to alter the value of the parameters after each iteration
statement (body): body of the loop
for ( expression1; expression2; expression3) statement
expression1;
while (expression2) {
statement
expression3;
}
Counting in for loops
for (count=1; count <= n; count=count+1) {
printf(“*”);
}

More about for
 Initialization and increment
 Can be comma-separated lists
 Example:
for (int i = 0, j = 0; j + i <= 10; j++, i++)
printf( "%d\n", j + i );
The for Structure: Notes and Observations
 Arithmetic expressions
 Initialization, loop-continuation, and increment can contain arithmetic expressions. If x equals 2 and y equals 10
for ( j = x; j <= 4 * x * y; j += y / x )
is equivalent to
for ( j = 2; j <= 80; j += 5 )
 Notes about the for structure:
 "Increment" may be negative (decrement)
 If the loop continuation condition is initially false
 The body of the for structure is not performed
 Control proceeds with the next statement after the for structure
 Control variable
 Often printed or used inside for body, but not necessary
for loops
 Equivalent to while. Any for loop can be converted to while loop and vice versa
 Some applications are more natural to for, and others to while.
 If we want to perform something for a predefined number of times, better use for.
 If we just wait for something to happen (not after a certain number or iterations), better use while.
2-D Figure
Print
* * * * *
* * * * *
* * * * *

Another 2-D Figure
Print
*
* *
* * *
* * * *
* * * * *

Exercise
Print
* * * * *
* * * *
* * *
* *
*

Exercise : solution
Print
* * * * *
* * * *
* * *
* *
*

Examples : for loop
for (i=0; i<10; i++)
printf (“%d “,i);

output:
0 1 2 3 4 5 6 7 8 9
Nested for Loop
main ()
{
int multiplicand, multiplier;
for (multiplicand=0; multiplicand<10; multiplicand++) {
for (multiplier=0; multiplier<10; multiplier++) {
printf(“%d\t”, multiplier*multilicand);
}
printf(“\n”);
}
}

main ()
{
int sum=0;
int input, inner, outer;

printf(“Input an integer : “);
scanf (“%d”, &input) ;

for (outer=1; outer <= input; outer++)
for (inner=0; inner < outer; inner++)
sum += inner;
printf (“The result is %d\n”, sum) ;
}
The factorial example again, this time using for
Factorial with for – step by step
Factorial with for – step by step
Factorial with for – step by step
Factorial with for – step by step
Factorial with for – step by step
Factorial with for – step by step
Factorial with for – step by step
Factorial with for – step by step
Factorial with for – step by step
Example – fahrenheit-celsius conversion table
/* Print a Fahrenheit-to-Celsius conversion table */

#include
int main ( )
{
int fahr;
double celsius;
int lower = 0, upper = 300;
int step = 20;

for (fahr=lower; fahr<=upper; fahr += step)
{
celsius = 5.0*(fahr -32.0)/9.0;
printf("%d\t%g\n", fahr, celsius);
}
return 0;
}
Nested for loop – rectangle example
/* Print a rectangle of *. The height and width are defined by the user */
#include

int main( )
{
int i, j;
int height, width;

printf("Please enter the two box dimensions: \n");
scanf("%d%d", &height, &width);

for (i = 1; i <= height; i++)
{
for (j = 1; j <= width; j++)
printf("*");

printf("\n");
}
}

Exercise
Write a program that prints an upside-down half triangle of *.
The height of the pyramid is the input.

Solution
#include

int main()
{
int i, j, size;

printf(“Please enter a size:\n”);
scanf(“%d”,&size);
for (i = 1; i <= size; i++)
{
for (j = i; j <= size; j++)
printf("*");

printf("\n");
}

return 0;
}

Exercise
Write a program accepts a number from the user, and prints out all of the prime numbers up to that number.

Solution
#include
int main()
{
int i, j, last;

printf("enter a number\n");
scanf("%d", &last);
for (i = 2; i <= last; i++)
{
for (j = 2 ; j < i; j++)
{
if (i % j == 0)
break;
}
if (j == i)
printf("the number %d is prime\n", i);
}
return 0;
}



Exercise
Change the former program, so that is displays only the largest prime number which is smaller than or equal to the user’s input.

Solution 1
#include
int main()
{
int i, j, last;
int found = 0; /* This indicates if we found the largest prime */

printf("enter a number\n");
scanf("%d", &last);
i = last;
while (!found) /* Loop until we find our guy */
{
for (j = 2 ; j < i; j++)
if (i % j == 0)
break;

if (j == i) /* If this is true then i is prime */
found = 1;
else
i--;
}
printf("The largest prime not larger than %d is %d.\n", last, i);
return 0;
}

Solution 2 (with break)
#include
int main()
{
int i, j, last;
printf("enter a number\n");
scanf("%d", &last);
for (i=last; i>1; i--)
{
for (j = 2 ; j < i; j++)
if (i % j == 0)
break;

if (j == i) /* i is prime. We found our guy */
break;
}
printf("The largest prime not larger than %d is %d.\n", last, i);
return 0;
}

Some Loop Pitfalls
while (sum <= NUM) ;
sum = sum+2;
Doubles and floats
What you expect:
0.000000000000000000
0.200000000000000000
0.400000000000000000
.. .. ..
9.000000000000000000
9.200000000000000000
9.400000000000000000
9.600000000000000000
9.800000000000000000
Use ints as loop counters
int i;
double x;
for (i=0; i<50; i=i+1)
{
x = (double)i/5.0;
printf (“%.18f”, x);
}
Iteration Summary
 General Pattern :
 initialize
 test
 do stuff
 update
 go back to re-test, re-do stuff, re-update, ...
 while and for are equally general in C
 use for when initialize/test/update are simple, especially when counting.
Simple Command Interpreter
 Read in “commands” and execute them.
 Input - single characters
 a - execute command Add by calling Add()
 s - execute command Sub by calling Sub()
 q - quit
 Pseudocode for main loop:
 get next command
 if a, execute command Add()
 if b, execute command Sub()
 if q, signal quit
Command Interpreter
Loop Control
repeat until quit signal
use variable “done” to indicate when done

Command Interpreter program
#define FALSE 0
#define TRUE 1
int main (void)
{
char command;
int done = FALSE;
while (!done) {
printf (“Input command:”);
scanf(“%c”,&command);
Exercise a
 Write a C program which accepts as input a single integer k, then writes a pattern consisting of a single 1 on the first line, two 2s on the 2nd line, three 3s on the 3rd line, until it writes k occurrences of k on the last line.
For example, if the input is 4, the output should be:
1
2 2
3 3 3
4 4 4 4
Exercise b
 Write a C program which accepts as input a single integer k, then generates the following pattern of k lines:
For example, if the input is 5, the output should be:
1
2 2 2
3 3 3 3 3
4 4 4 4 4 4 4
5 5 5 5 5 5 5 5 5
Test if a number is prime
prime = 1;
for (i=2; i{
if (num%i == 0)
prime=0;
}
if (prime == 1)
printf (“%d” is a prime number\n”);

Test if a number is prime
prime = 1;
limit = sqrt ((double)num);
for (i=2; i{
if (num%i == 0) {
prime=0;
break;
}
}
if (prime == 1)
printf (“%d” is a prime number\n”);


The break and continue
 break
 Causes immediate exit from a while, for, do/while or switch structure
 Program execution continues with the first statement after the structure
 Common uses of the break statement
 Escape early from a loop
 Skip the remainder of a switch structure



The break and continue Statements
 continue
 Skips the remaining statements in the body of a while, for or do/while structure
 Proceeds with the next iteration of the loop
 while and do/while
 Loop-continuation test is evaluated immediately after the continue statement is executed
 for
 Increment expression is executed, then the loop-continuation test is evaluated
Break and continue
 These two statements are used in loop control
 “break” exits the innermost current loop (for, while, do-while) and to exit from a switch
Control will be transferred out of the loop
 “continue” starts the next iteration of the loop (for, while, do-while)
 used to bypass the remainder of the current pass through a loop

do {
scanf (“%f”, &x);
if (x<0) {
printf(“Error, neg x”);
break;
}
. . .
/*process non-neg x */
} while (x<=100);

do {
scanf (“%f”, &x);
if (x<0) {
printf(“Neg value forx”);
continue;
}
. . .
/*process non-neg x */
} while (x<=100);
Ex: Write a loop that will calculate the sum of an AP series upto n terms
Sum= a + (a+d) +(a+2d) + . . . + (a+ (n-1)d)

Exercise c
 Write a C program that takes as input a positive integer n, and prints all prime numbers between 2 and n.
Exercise d
 Write a C program that calculates the sum of the first n odd numbers:
1 + 3 + 5 + . . . + 2*n-1
The sine of x can be calculated approximately by summin the first n terms of the infinite series:
sin x = x - x3 /3! + x5 /5! – x7 /7! + . . .
where x is expressed in radians ( radians = 180 degrees).
Write a C program that will read in a value for x and will calculate its sine.
 (i) sum the first n terms
 (ii)continue adding successive terms till the value of the next term becomes smaller (in magnitude) than 10-5




1. Int i=8, j=15, k=4

What is the output for:

2 * ( ( I % 5 ) * ( 4 + ( j – 3 ) / ( k + 2 ) ) )



2. int i= 7, float f=5.5, char c=’w’

(i>=6) && (c = = ‘w’)


(i>=6) || ( c = = ‘v’)


3. i=7, f= 5.5

!(f>5)



4. int a = float b


5. x=2, y=3,z=4

x * = -2 * ( y + z ) / 3

6. int i=7, float f=8.5

(i+f)%4







7. a=5, b= 3, c=8, d=7

b + c / 2 – (d * 4) % a

8. n1=25, n2=5, n3=6, n4=8

r = ( n1 + n2 ) / (n3 + n4 %4)































9. #include

void main()
{
int x = 5;

long int y=0x7ff;

int a=0x6db7,b=0xa726;

clrscr();

printf("%d\t",x);

printf("%d\t",(x<<2));/*left shift*/

printf("%d\t",(x>>2));/*right shift*/

printf("%d\n",(~x));/*one's complement*/

printf("%x\n",(~y));/*one's complement*/

printf("%x\n",a&b);
printf("%x\n",a|b);
printf("%x\n",a^b);
printf("%x\n",a<<6);
printf("%x",a>>6);
getchar();
}






10.
#include
int main()
{
int a=0;
if(a= 0)
printf("hello");
printf("AATT");
return 0;
}

11.
#include
void main()
{
char a[]="hello";
char b[]="hai";
a=b;
printf("%s,%s",a,b);
}

12. #include
void main()
{
char * p = "hello",ch;
ch = *++p;
clrscr();
printf("%c,%s",ch,p);
getchar();
}

13.#include
#define Stringizer(x) printf(#x)
void main()
{
Stringizer(hello);
getchar();
}


14. #include
#include
int main( )
{
char *ptr1,*ptr2;
ptr1 = "Hello AATT";
ptr2 = "Hai";
ptr1= strcat(ptr1,ptr2);
printf("\n Input string %s",ptr1);
return 1;
}

15. int main( )
{ int x=20,y=35;
x=y++ + x++;
y=++y + ++x;
printf("%d %d",x,y);
return 1;
}


16
/*
* database1.c
*
* Program to maintain a database of CDs for a CD shop.
* This is the Course Project for the Structured Programming Course
* This project is for WASE 2006 batch students .
* by Rajesh Kulkarni, 08-04-2007.
*/
#include

main()
{
char movie[61];
char director[61];
int songs; /* number of songs on the CD */
char type; /* used to read in hit/fail info */
int hit; /* boolean - is the movie a hit? */
float price;

printf("Welcome to the CD database.\n\n");

/*
* First, the movie name.
*/
printf("Please enter the details of the CD...\n");
printf("enter the name of the moviemovie? ");
scanf("%[^\n]", movie);

/*
* Next, the director.
*/
printf("enter the name of the director? ");
fflush(stdin);
scanf("%[^\n]", director);

/*
* Next, the number of songs
*/
printf("how many number of songs? ");
fflush(stdin);
scanf("%d", &songs);

/*
* Next, hit/fail.
*/
for (;;)
{
printf("hit or fail (h for hit, f for fail)? ");
fflush(stdin);
scanf("%c", &type);
if (type == 'h' || type == 'f' || type == 'H' || type == 'F')
break;
printf("Error - only 'h' or 'f' are allowed\n");
}
album = type == 'h'; /* if we get here it must be 'h' or 'f' */

/*
* Next, the price
*/
printf("enter the price of the CD? ");
fflush(stdin);
scanf("%f", &price);

/*
* Output the CD details
*/
printf("\nThe CD details you entered are:\n");
printf("============================\n");
printf("movie: %s\n", movie);
printf("director: %s\n", director);
printf("Number of songs: %d\n", songs);
if (hit)
printf("hit\n");
else
printf("fail\n");
printf("Price: %.2f\n", price);
printf("============================\n");

/*
* A user-friendly exit of the program
*/
printf("\nPress ENTER to exit the program: ");
fflush(stdin);
getchar();
}

17. /*
* database2.c
*
* Program to maintain a database of CDs for a CD shop.
* This is the Course Project for the Structured Programming Course
* This project is for WASE 2006 batch students .
* by Rajesh Kulkarni, 15-04-2007.
*/
#include

main()
{
char movie[100];
char director[100];
int songs[100]; /* number of songs on the CD */
char type; /* used to read in hit/single info */
int hit[100]; /* boolean - is the CD an hit? */
float price[100];
int count = 0; /* how many CDs are being tracked */
int i; /* loop counter */

printf("Welcome to the CD database.\n");
printf("You can store information of a maximum of 100 CDs.\n");

/*
* Loop until they no longer wish to enter any more CDs
*/
for (;;) /* forever loops are convenient for this sort of thing */
{
/*
* Ask them if they want to enter another CD
* Any answer other than y or Y will be treated as a NO
*/
printf("\nHave you any more CDs to enter (y/n)? ");
fflush(stdin);
scanf("%c", &type);
if (type != 'y' && type != 'Y')
break;

printf("\n"); /* for neat output */

/*
* First, the movie
*/
printf("Please enter the details of CD %d...\n\n", count+1);
printf("movie? ");
fflush(stdin);
scanf("%[^\n]", movie[count]);

/*
* Next, the director
*/
printf("director? ");
fflush(stdin);
scanf("%[^\n]", director[count]);

/*
* Next, the number of songs
*/
printf("Number of songs? ");
fflush(stdin);
scanf("%d", &songs[count]);

/*
* Next, hit/single
*/
for (;;)
{
printf("hit or fail (h for hit, f for fail)? ");
fflush(stdin);
scanf("%c", &type);
if (type == 'h' || type == 'f')
break;
printf("Error - only 'h' or 'f' are allowed\n");
}
hit[count] = type == 'h'; /* if we get here it must be 'h' or 'f' */

/*
* Next, the price
*/
printf(" price of the CD? ");
fflush(stdin);
scanf("%f", &price[count]);

count = count + 1;

/*
* Check if we have filled up the array
*/
if (count == 100)
{
printf("You have reached the limits of this program\n\n");
break;
}
}

/*
* Output the CD details
*/
for (i = 0; i < count; i = i + 1)
{
printf("\nThe details of CD %d are:\n", i+1);
printf("============================\n");
printf("movie: %s\n", movie[i]);
printf("director: %s\n", director[i]);
printf("Number of songs: %d\n", songs[i]);
if (hit[i])
printf("hit\n");
else
printf("fail\n");
printf("Price: %.2f\n", price[i]);
printf("============================\n");

if (i < count - 1) /* only do this if there are more CDs to see */
{
/*
* A user-friendly way to progress to the next CD
*/
printf("\nPress ENTER to see the next set of details: ");
fflush(stdin);
getchar();
}
}

/*
* A user-friendly exit of the program
*/
printf("\nPress ENTER to exit the program: ");
fflush(stdin);
getchar();
}



18. #include /* what happens*/
main()
{
int i;
for (i=1;i<=10;)
printf("%d\n",i);
}

19. #include
main()
{
if(1)
printf("WASE");
else;
printf("BIET");
}




20. #include
main()
{
int i;
clrscr();
do
printf("%d",i);
while(i<1);
getchar();
}










21. #include
main()
{
int i,j;
clrscr();

for(i=1,j=2;i<=2;i++,j--)
{
printf("%d\t%d\n",i,j);
}
getchar();
}







22.#include
main()
{
int i=1,j=2;
clrscr();

for(;i {
printf("%d",j);
}
getchar();
}








23. #include
main()
{
int i=1;
clrscr();
do
printf("%d",++i);
while(i<1);
getchar();
}
24. #include
main()
{
int a,b,c,d,e;
clrscr();
a=5,b=3,c=8,d=7;
e=b+c/2-(d*4)%a;
printf("%d",e);
getchar();
}

25. #include
main()
{
int n1,n2,n3,n4,r;
clrscr();
n1=25,n2=5,n3=6,n4=8;
r= (n1+n2)/(n3+n4%4);
printf("%d",r);
getchar();
}
26#include /* what happens*/
main()
{
for(i=1;i<=10;i++)
{
printf("%d\n",i);
}
27. #include /*output if input is 5*/
main()
{
int i,n,p;
clrscr();
printf(" enter a number:");
scanf("%d",&n);

for(i=1;i<=n;i++)
{
p=i*n;
printf("\n%d\tx\t%d\t=%d\n",n,i,p);
}
fflush(stdin);
getchar();
}


28.#include
main()
{
int i,j;
clrscr();

for(i=1;i<=5;i++)
{
printf("\n");
for(j=1;j<=i;j++)
{
printf("%d",j);
}
}
getchar();
}

29. #include
main()
{
int i,j;
clrscr();

for( i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
printf("%d",i);
}
printf("\n");
}
getchar();
}




30.#include
main()
{
int i=11,k;
clrscr();
k=i%-2;
printf("%d",k);
getchar();
}
31. #include
main()
{
int j=65;
clrscr();

for(;j<68;)
printf("%c",j++);
getchar();
}


32. #include
main()
{
int a=10;
clrscr();
printf("%f",a);
getchar();
}

33. #include
main()
{
int j=5;
clrscr();
printf("%d\t%d\t%d",j,--j,j++);
getchar();
}



34. #include
main()
{
long n,rev=0;
clrscr();
printf("\nenter a number\n");
scanf("%ld",&n);
while(n!=0)
{
rev=rev*10+n%10;
n=n/10;
}
printf("reverse number is %ld",rev);
fflush(stdin);
getchar();
}


35. #include /*input is 123*/
main()
{
int n,tn,sum,rem;
clrscr();
printf("enter a number\n");
scanf("%d",&n);
sum=0;
tn=n;
while(tn)
{rem=tn%10;
sum=sum+rem;
tn=tn/10;
}
printf("\n%d\t%d",n,sum);
fflush(stdin);
getchar();
}

36. #include
main()
{
int first,second,new;
int count;
clrscr();
first=0;
second=1;
count=2;
printf("\n the output is\n");
printf("\n===================\n");
printf("%d\n%d",first,second);
new = first + second;

while(++count < 10)
{
printf("\n%d",new);
getchar();
first=second;
second=new;
new=first + second;
}}














37. #include
main()
{
int i;
clrscr();
i=0;
while(i<20)
{
i=i+2;
printf("\n the even seris is:");
printf("%d",i);
}
getchar();
}





38. #include
main()
{ int i;
int no,digit,sum;
clrscr();
for(i=1;i<3;i++)
{
sum=0;
no=i;
while(no)
{
digit=no%10;
no=no/10;
sum=sum+digit*digit*digit;
}
if(sum==i)
printf("%d",i);
getchar();
}}

39. #include
main()
{
int i;
clrscr();
for(i=1;i<=100;i++)
{
if(i%9==0) continue;
printf("\t%d",i);
}
getchar();
}








40. #include /* if input is 3*/
main()
{ int x,i,j;
clrscr();
printf("\nenter a number \n");
scanf("%d",&x);
for(i=1;i<=x;i++)
{
for(j=1;j<=i;j++)
{
printf("*");
}
printf("\n");
}
fflush(stdin);
getchar();
}


41. #include
main()
{
int i;
clrscr();
for(i=1;i<=10;i++)
{
if(i>i++)
printf("%d\t",i);
}
getchar();
}







42. #include
#include
main()
{
int i,j;
clrscr();

for(i=1;i<=5;i++)
{
printf("\n");
for(j=1;j<=i;j++)
{
printf("%d",j);

}}
getchar();
}




43.
#include

main()
{
long number;
clrscr();

for (number = 1; number <= 100; number = number + 1)
printf("%i\t", number);

fflush(stdin);
getchar();
}





#include

main()
{
long start; /* the first number */
long count; /* the number of numbers */
long number; /* each number to print */
clrscr();

printf("Please enter a number to start at: ");
scanf("%ld", &start);

printf("Please enter the number of numbers: ");
scanf("%ld", &count);

for (number = start; number < start + count; number = number + 1)
printf("%i\n", number);

fflush(stdin);
getchar();
}




1. 36

2. true

3. false

4. b converted to int

5.


6. invalid

7. 4

8. r=5

9. 4

1

1111 1010

f800

2526 is a&b

a^b is ca91

6dc0 is a<<6


10. AATT

11. error assignment can not be done with arrays.

12. e, ello

13. hello

14. input string Hell AATT hai



15. 57 94

16.

17.

18. infinite loop

19. OUTPUT IS WASEBIET

20. some address

21. /* output is 1 2 2 1*/

22. /* output is 2*/

23. /* output is 2*/

24. /* output is 4*/

25. /* output is 5*/

26. 1..10

27. table of 5

28. 1
12
123
1234
12345
29. 1
22
333
4444
55555

30. 1

31. /*output is ABC*/

32. /*error*/

33. /*output is 5 5 5 associativity si right to left*/

34. /*program that reverses the given number*/

/* program that calculates sum of digits of an integers*/
35.

36. Fibonacci series


37./*generate even series from 1 to 20*/

38.
/*sum of cube of digits*/

39.
prints 1...100 except 9,18..

40.
*
**
***

41. output is 2 4 6 8 10

42. pyramid

43

Tuesday, March 27, 2007

WASE BITS-WIPRO SESSION 9 DT:25-03-07

Chapter 11Introduction toProgramming in C
C: A Middle-Level Language
C by Dennis ritchie at Bell in 1972
• It is a programming language closely associated with unix O.S.
Provides abstraction of underlying hardware
• operations do not depend on instruction set
• example: can write “a = b * c”, even thoughLC-3 doesn’t have a multiply instruction
Provides expressiveness
• use meaningful symbols that convey meaning
• simple expressions for common control patterns (if-then-else)
Enhances code readability
Safeguards against bugs
• can enforce rules or conditions at compile-time or run-time
C…
It is an unambiguous and machine independent definition.

It is a general purpose programming language.

C is not tied to any particular hardware or system.

BCPL and B are type less languages while C is has data types.

C is single-threaded, does not offer multiprogramming, parallel operations, syncronisations, coroutines.
C
5/9 = 0
In C integer division truncates;
Any fractional part is discarded

In C % operator can not be applied on float.

In C % operator can not be applied with real operands.

% operator takes the sign of the I operand.

Mixed mode arithmetic: result is real if one of the operand is real.
C arithmetic
6/7 = 0 -6/-7 = 0
During integer division if both the operands are of same sign the result is truncated towards zero.

If one of them is negative then direction of truncation is implementation dependant. That is

-6/7 = 0 or 1 ( machine dependant)
During modulo division the sign of the result is always the sign of the first operand.
-14%3 = -2 14%-3 = 2 -14%-3 = -2
Features of C
Fast: 32 keywords and built in functions

Robust: built in functions, operators, middle level features

Efficient: data types and operators

Extensible: libraries, functions can be added

Portable: Can be run on any machine

Structured: modules, blocks make testing and debugging easier
C
Comments are used to enhance it’s readability and understanding.

Comments do not effect the execution size and speed.

Comments aid in debugging and testing.

C is a case sensitive language

\n à new line character . It is like enter or carriage return key for typewriter
Structure of a C Program
• Functionfunction Heading(Argument list)
• Compound statementcompound statement = { …..}{ expression statements seperated by semicolon ;}
• Comments anywhere = /*……*/

Structure of a C Program
• Documentationnesting of comments not allowed
• Definition symbolic constants
• Link sectionlinks header files to source.Entire header file loaded.
• Global declaration .
• Function() { declaration part.. Exe part }



Structure…
The program will always begin by executing the main function.

The format of a C Program is

main() function starts
{……
………
………
………} function ends
Constants and Variables
Characters in C are letters, digits, special characters, white spaces

Tokens are smallest individual units of C. There are six tokens: Keywords, Identifiers, strings, special symbols, constants,Operators

Keywords: In ANSI C there are 32 keyword

Identifiers: names of variables, functions and arrays.

Strings: sequence of characters surrounded by double quotes.
keywords
Auto break case char const

char continue default do double

else enum extern float for

goto if int long register

return short signed sizeof static

struct switch typedef union unsigned

void volatile while

Constants and variables
Special symbols: @,#,$,^

Constants: Fixed values that do not change during the execution of the program.
Constants are divided as
• NumericIntegerReal
• CharacterSingleString


Constants and variables
Integers: size is 2 to 4 bytes which is machine dependant.

Integers may be decimal(0..9), octal(0..7), hex(0..15)

Real: Fractional parts represented using mantissa and
exponent form

Single character constant: characters enclosed within a
single quote mark ‘5’, ‘x’

Printf(“%d”,’a’); Printf(“%c”,’a’); Printf(“%c”,97);
Constants and variables
String constants: characters enclosed in double quotes.

Backslash character constants: escape sequences like /n, /t, /f.


Variables
Variables are data names for data types.

They change during the execution of programs.

Variable names start with a letter or underscore.

variable length is 31 characters, usage is 8 characters.

variable name must not be a keyword.

White spaces are not allowed.


Data types
ANSI C supports four classes of data types

• Derived: arrays, functions, structures, pointers.
• User defined: typedef and enum.
• Primary: int, char, float, double.
• Empty data set: void. Itr indicates type returned by functions that generate no values


Data types.. Sizes and ranges
• Charà 1 byte. -128 to 127
• Intà 2 bytes. -32768 to 32767
• Floatà 4 bytes 3.4e-38 to 3.4e+38
• Doubleà 8 bytes. 1.7e-308 to 1.7e+308


Preprocessor directives
#include

#include indicates to the compiler the nature of the library functions being used like printf().

Stdio.h is a header file consisting of library functions like printf() and scanf()

Printf() is a library function used to output information on to the screen.
Scanf() : a library function that accepts input from the k/b.
Preprocessor directives
Preprocessor directives are instructions to the compiler.
They begin with a # sign and can be placed anywhere in a program, but are most often placed at the beginning of a file.

#if #ifdef #ifndef #else #elif #include #define
#undef
#include “ “ OR #include<..>
#define identifier string
#define macroname macro substitution
#define RK “hi I am RK’
Preprocessor Directives
Printf(RK);

#define Yes 1
#define No 0
Printf(“%d %d %d”,Yes,No,Yes+No);

#ifndef HDR
#define HDR
#if
SYSTEM == MSDOS
#define HDR “msdos.h”
….#endif
Data types
Char 1 signed char 1 unsigned char 1

Int 2 signed int 2 unsigned int 2

short int 2 long int 4

Float 4

Double 8 long double 10
Data types

Sizeof() is a special operator which gives the size of the data

sizeof(char) 1

sizeof(int) 2

sizeof(float) 4

sizeof(double) 8

File.cà compileà file.objà linkà file.exe

Int data type occupies how many bytes…

.obj result in syntax errors while .exe result in linker errors.
Compilation vs. Interpretation
Different ways of translating high-level language
Interpretation
• interpreter = program that executes program statements
• generally one line/command at a time
• limited processing
• easy to debug, make changes, view intermediate results
• languages: BASIC, LISP, Perl, Java, Matlab, C-shell
Compilation
• translates statements into machine language
Ø does not execute, but creates executable program
• performs optimization over multiple statements
• change requires recompilation
Ø can be harder to debug, since executed code may be different
• languages: C, C++, Fortran, Pascal
Compilation vs. Interpretation
Consider the following algorithm:
• Get W from the keyboard.
• X = W + W
• Y = X + X
• Z = Y + Y
• Print Z to screen.

If interpreting, how many arithmetic operations occur?

If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single arithmetic operation?
Compiling a C Program
Entire mechanism is usually called the “compiler”
Preprocessor
• macro substitution
• conditional compilation
• “source-level” transformations
Ø output is still C
Compiler
• generates object file
Ø machine instructions
Linker
• combine object files(including libraries)into executable image
Compiler
Source Code Analysis
• “front end”
• parses programs to identify its pieces
Ø variables, expressions, statements, functions, etc.
• depends on language (not on target machine)
Code Generation
• “back end”
• generates machine code from analyzed source
• may optimize machine code to make it run more efficiently
• very dependent on target machine
Symbol Table
• map between symbolic names and items
• like assembler, but more kinds of information
A Simple C Program
#include
#define STOP 0

/* Function: main */
/* Description: counts down from user input to STOP */
main()
{
/* variable declarations */
int counter; /* an integer to hold count values */
int startPoint; /* starting point for countdown */
/* prompt user for input */
printf("Enter a positive number: ");
scanf("%d", &startPoint); /* read into startPoint */
/* count down and print count */
for (counter=startPoint; counter >= STOP; counter--)
printf("%d\n", counter);
}
Preprocessor Directives
#include
• Before compiling, copy contents of header file (stdio.h)into source code.
• Header files typically contain descriptions of functions andvariables needed by the program.
Ø no restrictions -- could be any C source code

#define STOP 0
• Before compiling, replace all instances of the string"STOP" with the string "0"
• Called a macro
• Used for values that won't change during execution,but might change if the program is reused. (Must recompile.)
Comments
Begins with /* and ends with */

Can span multiple lines
Cannot have a comment within a comment
Comments are not recognized within a string
• example: "my/*don't print this*/string"would be printed as: my/*don't print this*/string

As before, use comments to help reader, not to confuseor to restate the obvious

main Function
Every C program must have a function called main().

This is the code that is executedwhen the program is run.

The code for the function lives within brackets:
main()
{
/* code goes here */
}

Variable Declarations
Variables are used as names for data items.
Each variable has a type,which tells the compiler how the data is to be interpreted(and how much space it needs, etc.).

int counter;
int startPoint;

int is a predefined integer type in C.

Input and Output
Variety of I/O functions in C Standard Library.
Must include to use them.

printf("%d\n", counter);
• String contains characters to print andformatting directions for variables.
• This call says to print the variable counter as a decimal integer, followed by a linefeed (\n).

scanf("%d", &startPoint);
• String contains formatting directions for looking at input.
• This call says to read a decimal integer and assign it to thevariable startPoint. (Don't worry about the & yet.)

More About Output
Can print arbitrary expressions, not just variables
printf("%d\n", startPoint - counter);

Print multiple expressions with a single statement
printf("%d %d\n", counter, startPoint - counter);

Different formatting options:
%d decimal integer
%x hexadecimal integer
%c ASCII character
%f floating-point number
Examples
This code:
printf("%d is a prime number.\n", 43);
printf("43 plus 59 in decimal is %d.\n", 43+59);
printf("43 plus 59 in hex is %x.\n", 43+59);
printf("43 plus 59 as a character is %c.\n", 43+59);

produces this output:
43 is a prime number.
43 + 59 in decimal is 102.
43 + 59 in hex is 66.
43 + 59 as a character is f.

Examples of Input
Many of the same formatting characters areavailable for user input.

scanf("%c", &nextChar);
• reads a single character and stores it in nextChar
scanf("%f", &radius);
• reads a floating point number and stores it in radius
scanf("%d %d", &length, &amp;width);
• reads two decimal integers (separated by whitespace), stores the first one in length and the second in width

Must use ampersand (&) for variables being modified.(Explained in Chapter 16.)
Data input and output
Library functions for input and output are getchar, putchar, scanf, printf, gets, puts
• In C there are no keyword to perform i/p and o/p. That is accomplished through library functions.
• Keyboards and printers are treated as files.
• Header file for standard input output is stdio.h

Int a;
Char b;
a = getchar(); b= getchar();putchar(a);putchar(b);
getch()à does not echo character to screen.

Formatted input and output
printf(control string,arg1,arg2…);
printf(“this is %c %s”,”a string”);
%conversion character
%format specifier(c,d,e,f,g,I,o,s,u,x)à %d %e %f %g %i %o

%u %x %D %E %G %O %I %X %U

%field width format specifier printf(“%10f”,num);

%field width.precision format code printf(“%12.5”,num);
ALGORITHM

Program design: At this stage define a problem and its solution.
problem specification: the program must be thoroughly understand the problem and the input output and special processing specification represent the most important information collection during this phase.
Solution: The solution method is to be developed.

Using planning tools: The solution method is described step by step when solution method had been outlined. It must be represent by using algorithm notations or flow charts symbols.

Coding: It is relatively easier to convert the algorithm into a program in a computer language i.e. C,C++.
ALGORITHM
Compiling: Translate the program into machine code. typing errors(syntax errors) are found quickly at the time of compiling the program most C implementations will generate diagnostic messages when syntax errors are detected during compilation.
Executing: Running the program the run time errors may occur during the execution of programs even though it is free from syntax errors.
Syntactic & Run time errors generally produce error messages when program executed. These are easy to find and can be corrected. The logical error which is very difficult to detect. These are existence of logically incorrect instructions. These errors can be know only after output is executed.
ALGORITHM
Testing and validation: Once program is written , a program must be tested and then validated. The program always must guarantee to produce correct results. In above stages a), b),c) are purely manual process. remaining all
stages related its computer.
ALGORITHM:
A method of representing the step by step logical procedure for solving program in natural language is algorithm
FLOWCHART
There is another way to write the steps involved in any process ,this is by making use of various symbols . The symbols form a diagram that represents the steps in a pictorial fashion similar to an algorithm. This is also very easy to understand such a diagram is flow chart.
Flowcharts help us understand the logic of an operation easily. They are good communication devices and also helps in algorithm maintenance.
The most common symbols using drawing flow charts are given below:
FLOWCHART SYMBOLS
..\cds lab theory pavan sir's.DOC
Some examples c1.doc
#include

main()

{
clrscr();
printf("%d\n",43);
printf("%d\n",43+59);
printf("%x\n",102);
printf("%o\n",102);
}



#include
int m; /* global variable*/
main()
{
int i; /*local variable*/
float b;
f1();
}
f1()
{
int i; /*local variable*/
}

/* one i does not affect another i */


typedef int a;

typedef float b;

a x,y,z;

b p,q,r;


#include
main()
{
int a=10;
float x=3.142;
clrscr();
printf("%f\n",a);
printf("%d\n",sizeof(x));
printf("%d\n",sizeof(double));
}

#include
main()
{
int x=10;
char y;
clrscr();
y=(x==10?'A':'B');
printf("%d\n",y);
}


#include
main()
{
float i=10.0,k;
clrscr();
k=i%2;
printf("%d\n",k);
}

#include
main()
{ clrscr();
printf("%d",sizeof('8'));
}


include
main()
{
int i=32769;
clrscr();
printf("%d\n",i);
}


#include
main()
{
int i=10,j=20,k;
clrscr();
k=(i>j?30:40);
printf("%d",k);
}
PROGRAM DEVELOPMENT STAGES:

a) Program design: At this stage define a problem and its solution.
problem specification: the program must be thoroughly understand the problem and the input output and special processing specification represent the most important information collection during this phase.
Solution: The solution method is to be developed.
b) Using planning tools: The solution method is described step by step when solution method had been outlined. It must be represent by using algorithm notations or flow charts symbols.
c) Coding: It is relatively easier to convert the algorithm into a program in a computer language i.e. C,C++.
d) Compiling: Translate the program into machine code. typing errors(syntax errors) are found quickly at the time of compiling the program most C implementations will generate diagnostic messages when syntax errors are detected during compilation.
e) Executing: Running the program the run time errors may occur during the execution of programs even though it is free from syntax errors.
Syntactic & Run time errors generally produce error messages when program executed. These are easy to find and can be corrected. The logical error which is very difficult to detect. These are existence of logically incorrect instructions. These errors can be know only after output is executed.
f) Testing and validation: Once program is written , a program must be tested and then validated. The program always must guarantee to produce correct results. In above stages a), b),c) are purely manual process. remaining all
stages related its computer.
ALGORITHM:
A method of representing the step by step logical procedure for solving program in natural language is algorithm.

FLOWCHART:
There is another way to write the steps involved in any process ,this is by making use of various symbols . The symbols form a diagram that represents the steps in a pictorial fashion similar to an algorithm. This is also very easy to understand such a diagram is flow chart.
Flowcharts help us understand the logic of an operation easily. They are good communication devices and also helps in algorithm maintenance.
The most common symbols using drawing flow charts are given below:









FLOWCHART SYMBOLS:



Oval Terminal start/stop/begin/end

Making data available for
Input/ processing(Input) or
Parallelogram Output recording of the process


Document Print out Show data output in the
Form of document


Any processing to be done
A process changes or
Rectangle Process moves data. An
assignment
Operation.

Decision or switching type
Diamond Decision of operations.


Used to connect different
Circle Connector parts of flowchart.


Joins two symbols and
Arrow Flow also represents flow of
Execution.


Bracket with Annotation Descriptive comments or
Broken line explanation.



Double sided Predefined Modules or subroutines
Rectangle process specified elsewhere.

Sunday, February 18, 2007

WASE BITS-WIPRO SESSION6 DT:18-02-07

VENUE : WIPRO
AUDIENCE : 2006 BATCH

Chapter 11Introduction toProgramming in C
C: A Middle-Level Language
C by Dennis ritchie at Bell in 1972
• It is a programming language closely associated with unix O.S.
Provides abstraction of underlying hardware
• operations do not depend on instruction set
• example: can write “a = b * c”, even thoughLC-3 doesn’t have a multiply instruction
Provides expressiveness
• use meaningful symbols that convey meaning
• simple expressions for common control patterns (if-then-else)
Enhances code readability
Safeguards against bugs
• can enforce rules or conditions at compile-time or run-time
C…
It is an unambiguous and machine independent definition.

It is a general purpose programming language.

C is not tied to any particular hardware or system.

BCPL and B are type less languages while C is has data types.

C is single-threaded, does not offer multiprogramming, parallel operations, syncronisations, coroutines.
C
5/9 = 0
In C integer division truncates;
Any fractional part is discarded

In C % operator can not be applied on float.

In C % operator can not be applied with real operands.

% operator takes the sign of the I operand.

Mixed mode arithmetic: result is real if one of the operand is real.
C arithmetic
6/7 = 0 -6/-7 = 0
During integer division if both the operands are of same sign the result is truncated towards zero.

If one of them is negative then direction of truncation is implementation dependant. That is

-6/7 = 0 or 1 ( machine dependant)
During modulo division the sign of the result is always the sign of the first operand.
-14%3 = -2 14%-3 = 2 -14%-3 = -2
Features of C
Fast: 32 keywords and built in functions

Robust: built in functions, operators, middle level features

Efficient: data types and operators

Extensible: libraries, functions can be added

Portable: Can be run on any machine

Structured: modules, blocks make testing and debugging easier
C
Comments are used to enhance it’s readability and understanding.

Comments do not effect the execution size and speed.

Comments aid in debugging and testing.

C is a case sensitive language

\n à new line character . It is like enter or carriage return key for typewriter
Structure of a C Program
• Functionfunction Heading(Argument list)
• Compound statementcompound statement = { …..}{ expression statements seperated by semicolon ;}
• Comments anywhere = /*……*/

Structure of a C Program
• Documentationnesting of comments not allowed
• Definition symbolic constants
• Link sectionlinks header files to source.Entire header file loaded.
• Global declaration .
• Function() { declaration part.. Exe part }



Structure…
The program will always begin by executing the main function.

The format of a C Program is

main() function starts
{……
………
………
………} function ends
Constants and Variables
Characters in C are letters, digits, special characters, white spaces

Tokens are smallest individual units of C. There are six tokens Keywords, Identifiers, strings, special, constants..

Keywords: In ANSI C there are 32 keyword

Identifiers: names of variables, functions and arrays.

Strings: sequence of characters surrounded by double quotes.
Constants and variables
Special symbols:

Constants: Fixed values that do not change during the execution of the program.
Constants are divided as
• NumericIntegerReal
• CharacterSingleString


Constants and variables
Integers: size is 2 to 4 bytes which is machine dependant.

Integers may be decimal(0..9), octal(0..7), hex(0..15)

Real: Fractional parts represented using mantissa and
exponent form

Single character constant: characters enclosed within a
single quote mark ‘5’, ‘x’

Printf(“%d”,’a’); Printf(“%c”,’a’); Printf(“%c”,97);
Constants and variables
String constants: characters enclosed in double quotes.

Backslash character constants: escape sequences like /n, /t, /f.


Variables
Variables are data names for data types.

They change during the execution of programs.

Variable names start with a letter or underscore.

variable length is 31 characters, usage is 8 characters.

variable name must not be a keyword.

White spaces are not allowed.


Data types
ANSI C supports four clesses of data types

• Derived: arrays, functions, structures, pointers.
• User defined: typedef and enum.
• Primary: int, char, float, double.
• Empty data set: void. Itr indicates type returned by functions that generate no values


Data types.. Sizes and ranges
• Charà 1 byte. -128 to 127
• Intà 2 bytes. -32768 to 32767
• Floatà 4 bytes 3.4e-38 to 3.4e+38
• Doubleà 8 bytes. 1.7e-308 to 1.7e+308


Preprocessor directives
#include

#include indicates to the compiler the nature of the library functions being used like printf().

Stdio.h is a header file consisting of library functions like printf() and scanf()

Printf() is a library function used to output information on to the screen.
Scanf() : a library function that accepts input from the k/b.
Preprocessor directives
Preprocessor directives are instructions to the compiler.
They begin with a # sign and can be placed anywhere in a program, but are most often placed at the beginning of a file.

#if #ifdef #ifndef #else #elif #include #define
#undef
#include “ “ OR #include<..>
#define identifier string
#define macroname macro substitution
#define RK “hi I am RK’
Preprocessor Directives
Printf(RK);

#define Yes 1
#define No 0
Printf(“%d %d %d”,Yes,No,Yes+No);

#ifndef HDR
#define HDR
#if
SYSTEM == MSDOS
#define HDR “msdos.h”
….#endif
Data types
Char 1 signed char 1 unsigned char 1

Int 2 signed int 2 unsigned int 2

short int 2 long int 4

Float 4

Double 8 long double 10
Data types

Sizeof() is a special operator which gives the size of the data

sizeof(char) 1

sizeof(int) 2

sizeof(float) 4

sizeof(double) 8

File.cà compileà file.objà linkà file.exe

Int data type occupies how many bytes…

.obj result in syntax errors while .exe result in linker errors.
Compilation vs. Interpretation
Different ways of translating high-level language
Interpretation
• interpreter = program that executes program statements
• generally one line/command at a time
• limited processing
• easy to debug, make changes, view intermediate results
• languages: BASIC, LISP, Perl, Java, Matlab, C-shell
Compilation
• translates statements into machine language
Ø does not execute, but creates executable program
• performs optimization over multiple statements
• change requires recompilation
Ø can be harder to debug, since executed code may be different
• languages: C, C++, Fortran, Pascal
Compilation vs. Interpretation
Consider the following algorithm:
• Get W from the keyboard.
• X = W + W
• Y = X + X
• Z = Y + Y
• Print Z to screen.

If interpreting, how many arithmetic operations occur?

If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single arithmetic operation?
Compiling a C Program
Entire mechanism is usually called the “compiler”
Preprocessor
• macro substitution
• conditional compilation
• “source-level” transformations
Ø output is still C
Compiler
• generates object file
Ø machine instructions
Linker
• combine object files(including libraries)into executable image
Compiler
Source Code Analysis
• “front end”
• parses programs to identify its pieces
Ø variables, expressions, statements, functions, etc.
• depends on language (not on target machine)
Code Generation
• “back end”
• generates machine code from analyzed source
• may optimize machine code to make it run more efficiently
• very dependent on target machine
Symbol Table
• map between symbolic names and items
• like assembler, but more kinds of information
A Simple C Program
#include
#define STOP 0

/* Function: main */
/* Description: counts down from user input to STOP */
main()
{
/* variable declarations */
int counter; /* an integer to hold count values */
int startPoint; /* starting point for countdown */
/* prompt user for input */
printf("Enter a positive number: ");
scanf("%d", &startPoint); /* read into startPoint */
/* count down and print count */
for (counter=startPoint; counter >= STOP; counter--)
printf("%d\n", counter);
}
Preprocessor Directives
#include
• Before compiling, copy contents of header file (stdio.h)into source code.
• Header files typically contain descriptions of functions andvariables needed by the program.
Ø no restrictions -- could be any C source code

#define STOP 0
• Before compiling, replace all instances of the string"STOP" with the string "0"
• Called a macro
• Used for values that won't change during execution,but might change if the program is reused. (Must recompile.)
Comments
Begins with /* and ends with */

Can span multiple lines
Cannot have a comment within a comment
Comments are not recognized within a string
• example: "my/*don't print this*/string"would be printed as: my/*don't print this*/string

As before, use comments to help reader, not to confuseor to restate the obvious

main Function
Every C program must have a function called main().

This is the code that is executedwhen the program is run.

The code for the function lives within brackets:
main()
{
/* code goes here */
}

Variable Declarations
Variables are used as names for data items.
Each variable has a type,which tells the compiler how the data is to be interpreted(and how much space it needs, etc.).

int counter;
int startPoint;

int is a predefined integer type in C.

Input and Output
Variety of I/O functions in C Standard Library.
Must include to use them.

printf("%d\n", counter);
• String contains characters to print andformatting directions for variables.
• This call says to print the variable counter as a decimal integer, followed by a linefeed (\n).

scanf("%d", &startPoint);
• String contains formatting directions for looking at input.
• This call says to read a decimal integer and assign it to thevariable startPoint. (Don't worry about the & yet.)

More About Output
Can print arbitrary expressions, not just variables
printf("%d\n", startPoint - counter);

Print multiple expressions with a single statement
printf("%d %d\n", counter, startPoint - counter);

Different formatting options:
%d decimal integer
%x hexadecimal integer
%c ASCII character
%f floating-point number
Examples
This code:
printf("%d is a prime number.\n", 43);
printf("43 plus 59 in decimal is %d.\n", 43+59);
printf("43 plus 59 in hex is %x.\n", 43+59);
printf("43 plus 59 as a character is %c.\n", 43+59);

produces this output:
43 is a prime number.
43 + 59 in decimal is 102.
43 + 59 in hex is 66.
43 + 59 as a character is f.

Examples of Input
Many of the same formatting characters areavailable for user input.

scanf("%c", &nextChar);
• reads a single character and stores it in nextChar
scanf("%f", &radius);
• reads a floating point number and stores it in radius
scanf("%d %d", &length, &width);
• reads two decimal integers (separated by whitespace), stores the first one in length and the second in width

Must use ampersand (&) for variables being modified.(Explained in Chapter 16.)
Data input and output
Library functions for input and output are getchar, putchar, scanf, printf, gets, puts
• In C there are no keyword to perform i/p and o/p. That is accomplished through library functions.
• Keyboards and printers are treated as files.
• Header file for standard input output is stdio.h

Int a;
Char b;
a = getchar(); b= getchar();putchar(a);putchar(b);
getch()à does not echo character to screen.

Formatted input and output
printf(control string,arg1,arg2…);
printf(“this is %c %s”,”a string”);
%conversion character
%format specifier(c,d,e,f,g,I,o,s,u,x)à %d %e %f %g %i %o

%u %x %D %E %G %O %I %X %U

%field width format specifier printf(“%10f”,num);

%field width.precision format code printf(“%12.5”,num);

Sunday, February 11, 2007

WASE BITS-WIPRO SESSION 5 DT:11-02-07

Audience: wase 2006 batch
venue : wipro gachibowli
resources : Patt Patel ppts

Session 5The LC-3 Program
types

Type of operands : Addresses, numbers, characters, logical data

Type of of operations:
A. Data Transfer: Move, load, store
B. Arithmetic: Add, Subtract
C. Logical: AND, OR, NOT
D. Transfer of Control: JUMP, RET, HALT
E. I/O: Input
F. Conversion: Convert
Addressing Modes
• Immediate
• Direct
• Indirect
• Register
• Register Indirect
• Displacement
• Stack

An addressing mode specifies how to calculate the effective memory address of an operand by using information held in registers and/or constants contained within a machine instruction or elsewhere.
Addressing Modes
• Immediate add reg1 reg2 constant reg1 := reg2 + constant;
MOV AX, 0005H

Operand is present in the register. Immediate addressing is used to declare constants or variables
Addressing modes

b. Direct

load reg, address

MOVE AX, [5000H]à effective address

Disadvantage is limited address space.
Addressing Modes

c. Indirect

MOV AX, [BX]
POINTERS

d. register
MOV BX, AX
e. register Indirect : MOV AX, [BX]
f. displacement : MOV AX, 50H[BX]
g. stack addressing:
LC-3 Overview: Instruction Set
Opcodes
• 15 opcodes
• Operate instructions: ADD, AND, NOT
• Data movement instructions: LD, LDI, LDR, LEA, ST, STR, STI
• Control instructions: BR, JSR/JSRR, JMP, RTI, TRAP
• some opcodes set/clear condition codes, based on result:
Ø N = negative, Z = zero, P = positive (> 0)
Data Types
• 16-bit 2’s complement integer
Addressing Modes
• How is the location of an operand specified?
• non-memory addresses: immediate, register
• memory addresses: PC-relative, indirect, base+offset
Operate Instructions
Only three operations: ADD, AND, NOT

Source and destination operands are registers
• These instructions do not reference memory.
• ADD and AND can use “immediate” mode,where one operand is hard-wired into the instruction.

Will show dataflow diagram with each instruction.
• illustrates when and where data moves to accomplish the desired operation

NOT (Register)
ADD/AND (Register)
ADD/AND (Immediate)
Data Movement Instructions
Load -- read data from memory to register
• LD: PC-relative mode
• LDR: base+offset mode
• LDI: indirect mode

Store -- write data from register to memory
• ST: PC-relative mode
• STR: base+offset mode
• STI: indirect mode

Load effective address -- compute address, save in register
• LEA: immediate mode
• does not access memory
LD (PC-Relative)
LDI (Indirect)
LDR (Base+Offset)
LEA (Immediate)
Control Instructions
Used to alter the sequence of instructions(by changing the Program Counter)

Conditional Branch
• branch is taken if a specified condition is true
Ø signed offset is added to PC to yield new PC
• else, the branch is not taken
Ø PC is not changed, points to the next sequential instruction
Unconditional Branch (or Jump)
• always changes the PC
TRAP
• changes PC to the address of an OS “service routine”
• routine will return control to the next instruction (after TRAP)
Condition Codes
LC-3 has three condition code registers: N -- negative Z -- zero P -- positive (greater than zero)

Set by any instruction that writes a value to a register(ADD, AND, NOT, LD, LDR, LDI, LEA)

Exactly one will be set at all times
• Based on the last instruction that altered a register
Branch Instruction
Branch specifies one or more condition codes.
If the set bit is specified, the branch is taken.
• PC-relative addressing:target address is made by adding signed offset (IR[8:0])to current PC.
• Note: PC has already been incremented by FETCH stage.
• Note: Target must be within 256 words of BR instruction.

If the branch is not taken,the next sequential instruction is executed.
BR (PC-Relative)
TRAP
Calls a service routine, identified by 8-bit “trap vector.”





When routine is done, PC is set to the instruction following TRAP.
(We’ll talk about how this works later.)

Another Example
Count the occurrences of a character in a file
• Program begins at location x3000
• Read character from keyboard
• Load each character from a “file”
Ø File is a sequence of memory locations
Ø Starting address of file is stored in the memory locationimmediately after the program
• If file character equals input character, increment counter
• End of file is indicated by a special ASCII value: EOT (x04)
• At the end, print the number of characters and halt(assume there will be less than 10 occurrences of the character)

A special character used to indicate the end of a sequenceis often called a sentinel.
• Useful when you don’t know ahead of time how many timesto execute a loop.
Flow Chart
Char Count in Assembly Language (1 of 3)
;
; Program to count occurrences of a character in a file.
; Character to be input from the keyboard.
; Result to be displayed on the monitor.
; Program only works if no more than 9 occurrences are found.
;
;
; Initialization
;
.ORIG x3000
AND R2, R2, #0 ; R2 is counter, initially 0
LD R3, PTR ; R3 is pointer to characters
GETC ; R0 gets character input
LDR R1, R3, #0 ; R1 gets first character
;
; Test character for end of file
;
TEST ADD R4, R1, #-4 ; Test for EOT (ASCII x04)
BRz OUTPUT ; If done, prepare the output
Char Count in Assembly Language (2 of 3)
;
; Test character for match. If a match, increment count.
;
NOT R1, R1
ADD R1, R1, R0 ; If match, R1 = xFFFF
NOT R1, R1 ; If match, R1 = x0000
BRnp GETCHAR ; If no match, do not increment
ADD R2, R2, #1
;
; Get next character from file.
;
GETCHAR ADD R3, R3, #1 ; Point to next character.
LDR R1, R3, #0 ; R1 gets next char to test
BRnzp TEST
;
; Output the count.
;
OUTPUT LD R0, ASCII ; Load the ASCII template
ADD R0, R0, R2 ; Covert binary count to ASCII
OUT ; ASCII code in R0 is displayed.
HALT ; Halt machine

Program (1 of 2)
Program (2 of 2)
Problem solving
Problem solving
clarifying description of the problem, analyzing causes, identifying alternatives, assessing each alternative, choosing one, implementing it, and evaluating whether the problem was solved or not.

•Define the problem
•Analyze the problem
•Isolate the task knowledge to solve the problem
•Choose the best problem solving technique

Problem solving
•What is the input
•What should be the output
•Procedure to convert the input to output
•Logic
•Understand the syntax of the tool being used
•The procedure should have a good control strategy


Problem solving techniques
Stepwise refinement
Starting from the requirements, at each step one constructs a more concrete description of the system and verifies it against the specification constructed in the previous step until one arrives at the implementation.

Programming is different from coding.

Programming is a sequence of design decisions concerning the decomposition of tasks into subtasks and of data into data structures.


Stepwise refinement

it is a software development technique that imposes a hierarchical structure on the design of the program. It starts out by defining the solution at the highest level of functionality and breaking it down further and further into small routines that can be easily documented and coded.

It is also called as top down programming

Techniques that impose a logical structure on the writing of a program. Large routines are broken down into smaller, modular routines .
constructs
• Sequential
• Conditional
• Iterative


Back to number system
Converting binary fraction to decimal fraction

1) 0.1101 =

= 1 x 2-1 + 1 x 2-2 + 0 x 2-3 + 1 X 2-4

=1/2 + ¼ + 0 + 1/16

= 0.8125

2) 1101.1010 = ?
NUMBER SYSTEM
CONVERTING DECIMAL FRACTION TO BINARY FRACTION

• 0.8125 =
FRACTION FR X 2 REM INTEGER
0.8125 1.625 0.625 1 MSB
0.625 1.25 0.25 1
0.25 0.50 0.50 0
0.50 1.00 0.00 1LSB



2) 0.635= ?

3) 12.625 = ?
4. Floating Point Numbers
Exponential Notation
• The following are equivalent representations of 1,234
Parts of a Floating Point Number
-0.9876 x 10-3
IEEE 754 Standard
• Most common standard for representing floating point numbers
• Single precision: 32 bits, consisting of...
• Sign bit (1 bit)
• Exponent (8 bits)
• Mantissa (23 bits)
• Double precision: 64 bits, consisting of…
• Sign bit (1 bit)
• Exponent (11 bits)
• Mantissa (52 bits)

Single Precision Format
Normalization
• The mantissa is normalized
• Has an implied decimal place on left
• Has an implied “1” on left of the decimal place
• E.g.,
• Mantissa ®
• Represents…
Excess Notation
• To include +ve and –ve exponents, “excess” notation is used
• Single precision: excess 127
• Double precision: excess 1023
• The value of the exponent stored is larger than the actual exponent
• E.g., excess 127,
• Exponent ®
• Represents…
Example
• Single precision
Hexadecimal
• It is convenient and common to represent the original floating point number in hexadecimal
• The preceding example…

Converting from Floating Point
• E.g., What decimal value is represented by the following 32-bit floating point number?






Converting to Floating Point
• E.g., Express 36.562510 as a 32-bit floating point number (in hexadecimal)


• Step 2
• Normalize

• Step 3
• Determine S, E, and M

• Step 4
• Put S, E, and M together to form 32-bit binary result

• Step 5
• Express in hexadecimal
Chapter 11Introduction toProgramming in C
C: A High-Level Language
Gives symbolic names to values
• don’t need to know which register or memory location
Provides abstraction of underlying hardware
• operations do not depend on instruction set
• example: can write “a = b * c”, even thoughLC-3 doesn’t have a multiply instruction
Provides expressiveness
• use meaningful symbols that convey meaning
• simple expressions for common control patterns (if-then-else)
Enhances code readability
Safeguards against bugs
• can enforce rules or conditions at compile-time or run-time
Compilation vs. Interpretation
Different ways of translating high-level language
Interpretation
• interpreter = program that executes program statements
• generally one line/command at a time
• limited processing
• easy to debug, make changes, view intermediate results
• languages: BASIC, LISP, Perl, Java, Matlab, C-shell
Compilation
• translates statements into machine language
Ø does not execute, but creates executable program
• performs optimization over multiple statements
• change requires recompilation
Ø can be harder to debug, since executed code may be different
• languages: C, C++, Fortran, Pascal
Compilation vs. Interpretation
Consider the following algorithm:
• Get W from the keyboard.
• X = W + W
• Y = X + X
• Z = Y + Y
• Print Z to screen.

If interpreting, how many arithmetic operations occur?

If compiling, we can analyze the entire program and possibly reduce the number of operations. Can we simplify the above algorithm to use a single arithmetic operation?
Compiling a C Program
Entire mechanism is usually called the “compiler”
Preprocessor
• macro substitution
• conditional compilation
• “source-level” transformations
Ø output is still C
Compiler
• generates object file
Ø machine instructions
Linker
• combine object files(including libraries)into executable image
Compiler
Source Code Analysis
• “front end”
• parses programs to identify its pieces
Ø variables, expressions, statements, functions, etc.
• depends on language (not on target machine)
Code Generation
• “back end”
• generates machine code from analyzed source
• may optimize machine code to make it run more efficiently
• very dependent on target machine
Symbol Table
• map between symbolic names and items
• like assembler, but more kinds of information
A Simple C Program
#include
#define STOP 0

/* Function: main */
/* Description: counts down from user input to STOP */
main()
{
/* variable declarations */
int counter; /* an integer to hold count values */
int startPoint; /* starting point for countdown */
/* prompt user for input */
printf("Enter a positive number: ");
scanf("%d", &startPoint); /* read into startPoint */
/* count down and print count */
for (counter=startPoint; counter >= STOP; counter--)
printf("%d\n", counter);
}
Preprocessor Directives
#include
• Before compiling, copy contents of header file (stdio.h)into source code.
• Header files typically contain descriptions of functions andvariables needed by the program.
Ø no restrictions -- could be any C source code

#define STOP 0
• Before compiling, replace all instances of the string"STOP" with the string "0"
• Called a macro
• Used for values that won't change during execution,but might change if the program is reused. (Must recompile.)
Comments
Begins with /* and ends with */

Can span multiple lines
Cannot have a comment within a comment
Comments are not recognized within a string
• example: "my/*don't print this*/string"would be printed as: my/*don't print this*/string

As before, use comments to help reader, not to confuseor to restate the obvious

main Function
Every C program must have a function called main().

This is the code that is executedwhen the program is run.

The code for the function lives within brackets:
main()
{
/* code goes here */
}

Variable Declarations
Variables are used as names for data items.
Each variable has a type,which tells the compiler how the data is to be interpreted(and how much space it needs, etc.).

int counter;
int startPoint;

int is a predefined integer type in C.

Input and Output
Variety of I/O functions in C Standard Library.
Must include to use them.

printf("%d\n", counter);
• String contains characters to print andformatting directions for variables.
• This call says to print the variable counter as a decimal integer, followed by a linefeed (\n).

scanf("%d", &startPoint);
• String contains formatting directions for looking at input.
• This call says to read a decimal integer and assign it to thevariable startPoint. (Don't worry about the & yet.)

More About Output
Can print arbitrary expressions, not just variables
printf("%d\n", startPoint - counter);

Print multiple expressions with a single statement
printf("%d %d\n", counter, startPoint - counter);

Different formatting options:
%d decimal integer
%x hexadecimal integer
%c ASCII character
%f floating-point number
Examples
This code:
printf("%d is a prime number.\n", 43);
printf("43 plus 59 in decimal is %d.\n", 43+59);
printf("43 plus 59 in hex is %x.\n", 43+59);
printf("43 plus 59 as a character is %c.\n", 43+59);

produces this output:
43 is a prime number.
43 + 59 in decimal is 102.
43 + 59 in hex is 66.
43 + 59 as a character is f.

Examples of Input
Many of the same formatting characters areavailable for user input.

scanf("%c", &nextChar);
• reads a single character and stores it in nextChar
scanf("%f", &radius);
• reads a floating point number and stores it in radius
scanf("%d %d", &length, &width);
• reads two decimal integers (separated by whitespace), stores the first one in length and the second in width

Must use ampersand (&) for variables being modified.(Explained in Chapter 16.)
Compiling and Linking
Various compilers available
• cc, gcc
• includes preprocessor, compiler, and linker

Lots and lots of options!
• level of optimization, debugging
• preprocessor, linker options
• intermediate files -- object (.o), assembler (.s), preprocessor (.i), etc.

Remaining Chapters
A more detailed look at many C features.
• Variables and declarations
• Operators
• Control Structures
• Functions
• Data Structures
• I/O

Emphasis on how C is converted to
LC-3 assembly language.

Also see C Reference in Appendix D.
Chapter 6Programming
Solving Problems using a Computer
Methodologies for creating computer programsthat perform a desired function.

Problem Solving
• How do we figure out what to tell the computer to do?
• Convert problem statement into algorithm,using stepwise refinement.
• Convert algorithm into LC-3 machine instructions.
Debugging
• How do we figure out why it didn’t work?
• Examining registers and memory, setting breakpoints, etc.
Stepwise Refinement
Also known as systematic decomposition.

Start with problem statement:
“We wish to count the number of occurrences of a characterin a file. The character in question is to be input fromthe keyboard; the result is to be displayed on the monitor.”

Decompose task into a few simpler subtasks.

Decompose each subtask into smaller subtasks,and these into even smaller subtasks, etc....until you get to the machine instruction level.
Problem Statement
Because problem statements are written in English,they are sometimes ambiguous and/or incomplete.
• Where is “file” located? How big is it, or how do I knowwhen I’ve reached the end?
• How should final count be printed? A decimal number?
• If the character is a letter, should I count bothupper-case and lower-case occurrences?

How do you resolve these issues?
• Ask the person who wants the problem solved, or
• Make a decision and document it.
Three Basic Constructs
There are three basic ways to decompose a task:
Sequential
Do Subtask 1 to completion,then do Subtask 2 to completion, etc.
Conditional
If condition is true, do Subtask 1;else, do Subtask 2.
Iterative
Do Subtask over and over, as long as the test condition is true.
Problem Solving Skills
Learn to convert problem statementinto step-by-step description of subtasks.
• Like a puzzle, or a “word problem” from grammar school math.
Ø What is the starting state of the system?
Ø What is the desired ending state?
Ø How do we move from one state to another?
• Recognize English words that correlate to three basic constructs:
Ø “do A then do B” Þ sequential
Ø “if G, then do H” Þ conditional
Ø “for each X, do Y” Þ iterative
Ø “do Z until W” Þ iterative
LC-3 Control Instructions
How do we use LC-3 instructions to encodethe three basic constructs?

Sequential
• Instructions naturally flow from one to the next,so no special instruction needed to gofrom one sequential subtask to the next.

Conditional and Iterative
• Create code that converts condition into N, Z, or P.Example: Condition: “Is R0 = R1?” Code: Subtract R1 from R0; if equal, Z bit will be set.
• Then use BR instruction to transfer control to the proper subtask.
Code for Conditional
Code for Iteration
Example: Counting Characters
Refining B
Refining B1
Refining B2 and B3
The Last Step: LC-3 Instructions
Use comments to separate into modules and to document your code.
Debugging
You’ve written your program and it doesn’t work.
Now what?

What do you do when you’re lost in a city?
• Drive around randomly and hope you find it?
PReturn to a known point and look at a map?

In debugging, the equivalent to looking at a mapis tracing your program.
• Examine the sequence of instructions being executed.
• Keep track of results being produced.
• Compare result from each instruction to the expected result.
Debugging Operations
Any debugging environment should provide means to:
• Display values in memory and registers.
• Deposit values in memory and registers.
• Execute instruction sequence in a program.
• Stop execution when desired.

Different programming levels offer different tools.
• High-level languages (C, Java, ...)usually have source-code debugging tools.
• For debugging at the machine instruction level:
Ø simulators
Ø operating system “monitor” tools
Ø in-circuit emulators (ICE)
– plug-in hardware replacements that give instruction-level control
LC-3 Simulator
Types of Errors
Syntax Errors
• You made a typing error that resulted in an illegal operation.
• Not usually an issue with machine language,because almost any bit pattern corresponds tosome legal instruction.
• In high-level languages, these are often caught during thetranslation from language to machine code.
Logic Errors
• Your program is legal, but wrong, so the results don’t match the problem statement.
• Trace the program to see what’s really happening anddetermine how to get the proper behavior.
Data Errors
• Input data is different than what you expected.
• Test the program with a wide variety of inputs.
Tracing the Program
Execute the program one piece at a time,examining register and memory to see results at each step.
Single-Stepping
• Execute one instruction at a time.
• Tedious, but useful to help you verify each step of your program.
Breakpoints
• Tell the simulator to stop executing when it reachesa specific instruction.
• Check overall results at specific points in the program.
Ø Lets you quickly execute sequences to get ahigh-level overview of the execution behavior.
Ø Quickly execute sequences that your believe are correct.
Watchpoints
• Tell the simulator to stop when a register or memory location changes or when it equals a specific value.
• Useful when you don’t know where or when a value is changed.
Example 1: Multiply
This program is supposed to multiply the two unsignedintegers in R4 and R5.
Debugging the Multiply Program
Example 2: Summing an Array of Numbers
This program is supposed to sum the numbersstored in 10 locations beginning with x3100,leaving the result in R1.
Debugging the Summing Program
Running the the data below yields R1 = x0024,but the sum should be x8135. What happened?
Example 3: Looking for a 5
This program is supposed to setR0=1 if there’s a 5 in one ten memory locations, starting at x3100.
Else, it should set R0 to 0.
Debugging the Fives Program
Running the program with a 5 in location x3108results in R0 = 0, not R0 = 1. What happened?
Example 4: Finding First 1 in a Word
This program is supposed to return (in R1) the bit position of the first 1 in a word. The address of the word is in location x3009 (just past the end of the program). If thereare no ones, R1 should be set to –1.
Debugging the First-One Program
Program works most of the time, but if data is zero,it never seems to HALT.
Debugging: Lessons Learned
Trace program to see what’s going on.
• Breakpoints, single-stepping

When tracing, make sure to notice what’s really happening, not what you think should happen.
• In summing program, it would be easy to not noticethat address x3107 was loaded instead of x3100.

Test your program using a variety of input data.
• In Examples 3 and 4, the program works for many data sets.
• Be sure to test extreme cases (all ones, no ones, ...).