Wednesday, May 2, 2007

WASE FUNCTIONS 29-04-07

• Functions
• Function definition
• Calling function
• Global variables
• Function parameters
• Call by value
• Functions that return value
• Function prototype
• Assignment :- create a function that returns details of one cd.

/*
* double2.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include

double_it(int n1)
{
return n1 * 2;
}

main()
{
int num1;

printf("Please enter the number: ");
scanf("%d", &num1);

printf("The doubled value is %d\n", double_it(num1));

fflush(stdin);
getchar();
}


/*
* double.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include

double_it(int n1)
{
n1 *= 2;
}

main()
{
int num1;

printf("Please enter the number: ");
scanf("%d", &num1);

double_it(num1);

printf("The doubled value is %d\n", num1);

fflush(stdin);
getchar();
}


/*
* average3.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include

input(int sequence)
{
int num;
char position[10];

switch (sequence)
{
case 1: strcpy(position, "first"); break;
case 2: strcpy(position, "second"); break;
case 3: strcpy(position, "third"); break;
}

printf("Please enter the %s number: ", position);
scanf("%d", &num);

return num;
}

float average3(int n1, int n2, int n3)
{
return (float)(n1 + n2 + n3) / 3;
}

output(float a)
{
printf("The average is %f\n", a);
}

main()
{
int num1, num2, num3;
float ave;

num1 = input(1);
num2 = input(2);
num3 = input(3);

ave = average3(num1, num2, num3);

output(ave);

fflush(stdin);
getchar();
}


/*
* average4.c
*
* Program to demonstrate the use of function prototypes
*
* by Rajesh Kulkarni
*/
#include

float average3(int n1, int n2, int n3);

input(int sequence)
{
int num;
char position[10];

switch (sequence)
{
case 1: strcpy(position, "first"); break;
case 2: strcpy(position, "second"); break;
case 3: strcpy(position, "third"); break;
}

printf("Please enter the %s number: ", position);
scanf("%d", &num);

printf("The average of 4, 3 and 5 is %f\n", average3(4, 3, 5));

return num;
}

float average3(int n1, int n2, int n3)
{
return (float)(n1 + n2 + n3) / 3;
}

output(float a)
{
printf("The average is %f\n", a);
}

main()
{
int num1, num2, num3;
float ave;

num1 = input(1);
num2 = input(2);
num3 = input(3);

ave = average3(num1, num2, num3);

output(ave);

fflush(stdin);
getchar();
}


/*
* average2.c
*
* Program to demonstrate the use of function parameters
*
* by Rajesh Kulkarni
*/
#include

float ave;

average3(int n1, int n2, int n3)
{
ave = (float)(n1 + n2 + n3) / 3;
}

main()
{
int num1, num2, num3;

printf("Please enter the first number: ");
scanf("%d", &num1);
printf("Please enter the second number: ");
scanf("%d", &num2);
printf("Please enter the third number: ");
scanf("%d", &num3);

average3(num1, num2, num3);

printf("The average is %f\n", ave);

fflush(stdin);
getchar();
}


/*
* average.c
*
* Program to demonstrate the use of global variables
*
* by Rajesh Kulkarni
*/
#include

int num1, num2, num3;
float ave;

input()
{
printf("Please enter the first number: ");
scanf("%d", &num1);
printf("Please enter the second number: ");
scanf("%d", &num2);
printf("Please enter the third number: ");
scanf("%d", &num3);
}

average()
{
ave = (float)(num1 + num2 + num3) / 3;
}

output()
{
printf("The average is %f\n", ave);
}

main()
{
input();
average();
output();

fflush(stdin);
getchar();
}


/*
* strlen.c
*
* Program to demonstrate the use of function parameters being passed
* into functions
*
* by Rajesh Kulkarni
*/
#include

int length;

strlength(char str[])
{
for (length = 0; str[length] != '\0'; length++)
; /* do nothing loop */
}

main()
{
char string[100];

printf("Please enter your first name: ");
scanf("%[^\n]", string);

strlength(string);

printf("Length of >>%s<< is %d\n", string, length);

fflush(stdin);
getchar();
}


/*
* strlen2.c
*
* Program to demonstrate the use of function parameters being passed
* into functions
*
* by Rajesh Kulkarni
*/
#include

int strlength(char str[])
{
int i;

for (i = 0; str[i] != '\0'; i++)
; /* do nothing loop */
return i;
}

main()
{
char string[100];
int length;

printf("Please enter your first name: ");
scanf("%[^\n]", string);

length = strlength(string);

printf("Length of >>%s<< is %d\n", string, length);

printf("Please enter your last name: ");
fflush(stdin);
scanf("%[^\n]", string);

length = strlength(string);

printf("Length of >>%s<< is %d\n", string, length);

fflush(stdin);
getchar();
}
Functions
Class Test

on 7th February Thursday

5:30 to 6:30 pm
A Problem
 Suppose we are writing a program that displays messages on the screen.
 We want to display rows of =============================== to separate sections of output.
Solution
#include
int main (void)
{
/* produce some output */
/* print banner line */
printf(“==============\n”) ;
/* produce more output */
printf(“==============\n”);
/* produce even more output */
printf(“==============\n”);
/* produce final output */
}

Critique
 Redundant code
 What if we want to change the display
 e.g. to print a blank line before and after each line with =’s ?
 What if we want to print banner lines in some other program?
The Solution: Functions
 Definition: A function is a named code sequence
 A function can be executed by using its name as a statement or expression.
 The function may have parameters - information that can be different each time the function is executed.
 The function may compute and return a value.
Why use functions ?
 Functions provide an abstraction when writing a program - allow low-level details to be packaged.
 Able to package a computation we need to perform at multiple spots within a program.
 Write once, use many times.
 If changes are needed, they only have to be done once, in one place.
Why use functions ?
 Allows the programmer to create a program from smaller, simpler sub-components.
 Many programs are far too large to understand all at once.
 Functions give us a way to break a large program into smaller pieces
 A function should perform a well-defined task.
Common functions
int main (void)
{
. . .
}
More common functions
 Every standard C compiler comes with a set of standard libraries.
 #include
 Tells the compiler you will use the standard IO library
 #include
 C’s standard math library functions:
 sqrt, pow, sin, cos, exp, ...

 isspace, ...

Defining your own functions
 You may define your own functions in your programs
 You define a function by giving its name and writing the code that is executed when the function is called.
High level programming structure
main ()
{
. . .
SetUpBoard ();
do {
redsTurn ();
blacksTurn ();
} while (gamenotover ());
}
Function definition
/* print banner line */
void print_banner (void)
{
printf (“=========”);
printf (“=========\n”);
}
void
/* print banner line */
void print_banner (void)
{
printf (“=========”);
printf (“=========\n”);
}
Calling a function
int main (void)
{
/* produce some output */
. . .
print_banner ();
/* produce more output */
. . .
print_banner ();
/* produce final output */
. . .
print_banner ();
}
Terminology
 main () is the caller
 print_banner() is the callee.
 main() invokes / calls print_banner() 3 times.
 print_banner() is called from main()
Function Control Flow
/* print banner line */
void print_banner (void)
{
printf(“**************\n”);
}
Control Flow
 All C programs
 Start at main () /*no matter where main()is */
 Continue in top-to-bottom order, statement by statement, unless the order is changed by:
 function call
 function return
 if
 loops
Function Type and Value
 A function can return a value.
 Like all values in C, a function return value has a type.
 The function has the type of its returned value.
Calling a function
 A value-returning function is called by including it in an expression.
return
 In a value-returning function (result type is not void) return does two distinct things :
 1. specify the value returned by the execution of the function
 2. terminate that execution of the function.
 In a void function:
 return is optional at the end of the function body.
 return may also be used to terminate execution of the function explicitly.
 No return value should appear following return.

void compute_and_print_itax ()
{
double income;
scanf (“%f”, &income);
if (income < 50000) {
printf (“Income tax = Nil\n”);
return;
}
if (income < 60000) {
printf (“Income tax = %f\n”, 0.1*(income-50000);
return;
}
if (income < 150000) {
printf (“Income tax = %f\n”, 0.2*(income-60000)+1000);
return ;
}
printf (“Income tax = %f\n”, 0.3*(income-150000)+19000);
}
Function parameters
 It is very often useful if a function can operate on different data values each time it is called. Such values are function (input) parameters.
 The function specifies its inputs as parameters in the function declaration.
Arguments
 The function call must include a matching argument for each parameter.
 When the function is executed, the value of the argument is substituted for the parameter.
Functions
Lecture 10


Function parameters
 It is very often useful if a function can operate on different data values each time it is called. Such values are function (input) parameters.
 The function specifies its inputs as parameters in the function declaration.
Arguments
 The function call must include a matching argument for each parameter.
 When the function is executed, the value of the argument is substituted for the parameter.
Control and data flow
 When a function is called:
 (1) control transfers to the function body
 (2) argument values are copied
 (3) the function executes
 (4) control and return value return to the point of call.
Control and data flow
int main (void)
{
double x, y, z;
y=6.0;
x = area(y/2.0);
. . .
z = area(7.88);
. . .
return (0);
}
Style notes
 Put comments above a function body to specify completely what the function does, including the significance of all the parameters.

Multiple parameters
 a function may have more than one parameter
 arguments must match parameters in number, order and type.
Rules for using functions
 Arguments must match parameters:
 in number
 in order
 in type
 A function can only return one value.
 but it might contain more than one return statement.
 In a function with return type T, the return expression must be of type T.
 A function with return type T can be used anywhere an expression of type T can be used.
Local variables
 A function can define its own local variables.
 The locals have meaning only within the function.
 Each execution of the function uses a new set of locals
 Local variables cease to exist when the function returns
 Parameters are also local.
Local variables
Defining function prototypes
 Functions should be declared before they are used (invoked).
 Instead of writing the complete function, you can use function prototypes to declare a function so that it can be used.
 It is a good programming style to use function prototypes.
Function prototypes
int operate (double x, double y, char op) ;
int operate (double, double, char);
void print_average (double, int);
int get_intput (void);
void print_banner (void);


Local Variables
 Formal parameters and variables declared in a function are local to it.
 cannot be accessed or used by other functions directly
 Allocated (created) on function entry.
 De-allocated (destroyed) on function return.
 Formal parameters initialized by copying value of actual parameter. (“Call by value”)
Call by value
void printDouble (int x) {
printf (“Double of %d “, x);
x *= 2;
printf (“is %d\n”, x) ;
}
void main () {
int num=15;
printDouble (num);
printf (“ num = %d\n”, num);
}Functions
Functions
 a group of declarations and statements that is assigned a name
 effectively, a named statement block
 usually has a value
 a sub-program
 when we write our program we always define a function named main
 inside main we can call other functions
 which can themselves use other functions, and so on…
Example - Square
#include

double square(double a)
{
return a*a;
}

int main(void)
{
double num;

printf("enter a number\n");
scanf("%lf",&num);

printf("square of %g is %g\n",num,square(num));

return 0;
}

Why use functions?
 they can break your problem down into smaller sub-tasks
 easier to solve complex problems
 generalize a repeated set of instructions
 we don’t have to keep writing the same thing over and over
 printf and scanf are good examples…
 they make a program much easier to read and maintain


Characteristics of Functions
return-type name(arg_type1 arg_name1, arg_type2 arg_name2, …)
{
function body;
return value;
}

Return Statement
 Return causes the execution of the function to terminate and returns a value to the calling function
 The type of the value returned must be the same as the return-type defined for the function (or a ‘lower’ type)
 In a function there may be any no of return statements but only one can be executed.
 Return type is optional
 Default return type is int
Exercise
Write a program that gets a positive integer from the user and prints all the prime numbers from 2 up to that integer.
(Use a function that returns 1 if its parameter is prime, 0 otherwise)

Solution




is_prime_func.c
The Great Void
 Sometimes there’s no reason for a function to return a value
 In these cases, the function return type should be ‘void’
 If the ‘return’ keyword is used within such a function it exits the function immediately. No value needs be specified
The Great Void
 Calling ‘return’ in a function returning void is not obligatory
 If the function receives no parameters, the parameter list should be replaced by ‘void’ (or just nothing)
Example
void ShowHelp(void)
{
printf("This function explains what this program does…\n");
printf("Yadayadayada");
/* ... */
}

int main(void)
{
char choice;

printf("Please enter your selection: ");
scanf("%c", &choice);

if (choice==‘h’)
ShowHelp();
else if /* Program continues … */
}


 Calling function: a function which is referring another function is called calling function
 Called function: a function which is referenced by another function is called called function.
 Function call:
 Actual parameters:
 Formal parameters;

Pass-by-value
 Function arguments are passed to the function by copying their values rather than giving the function direct access to the actual variables
 A change to the value of an argument in a function body will not change the value of variables in the calling function
 Example – add_one.c
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}

int main(void)
{
int a=34,b=1;

a = add_one(b);

printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}

int main(void)
{
int a=34,b=1;

a = add_one(b);

printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}

int main(void)
{
int a=34,b=1;

a = add_one(b);

printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}

int main(void)
{
int a=34,b=1;

a = add_one(b);

printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}

int main(void)
{
int a=34,b=1;

a = add_one(b);

printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}

int main(void)
{
int a=34,b=1;

a = add_one(b);

printf("a = %d, b = %d\n", a, b);
return 0;
}
add_one – step by step
int add_one(int b)
{
b=b+1;
return b;
}

int main(void)
{
int a=34,b=1;

a = add_one(b);

printf("a = %d, b = %d\n", a, b);
return 0;
}
Riddle me this
#include

int factorial(int n)
{
int fact = 1;

while (n>1)
{
fact *= n;
n--;
}

return fact;
}


Scope of variables
 A variable declared within a function is unrelated to variables declared elsewhere, even if they have the same name
 A function cannot access variables that are declared in other functions
 Example – scope.c

Call –by- Reference
Wrong way to do it
int add_one(int b)
{
a=b+1;
}

int main(void)
{
int a=34,b=1;

add_one(b);

printf("a = %d, b = %d\n", a, b);
return 0;
}
Function Declaration
 Most software projects in C are composed of more than one file
 We want to be able to define the function in one file, and to use it in all files
Function Declaration
 For this reason, the function must be declared in every file in which it’s called, before it’s called for the first time
 the declaration contains:
Function Declaration
#include

int factorial(int a); /* Function Declaration! */

int main(void){
int num;

printf("enter a number\n");
scanf("%d", &num);

printf("%d != %d\n", num, factorial(num));

return 0;
}

int factorial(int a){
int i, b = 1;
for(i = 1; I <= a; i++)
b = b*i;
return b;
}

Function Declaration
 stdio.h actually contains a large set of function declarations
 The #include directive tells the compiler to insert these declarations into the file, so that these functions could be called
The math library
 A collection of mathematical functions
 Need to include the header file math.h (#include )
 Use functions of the library, e.g.
double s,p;
s = sqrt(p);
 Declared in math.h :
double sqrt (double x);

The math library
 sin(x), cos(x), tan(x)
 x is given in radians
 asin(x), acos(x), atan(x)
 log(x)
 sqrt(x)
 pow(x,y) – raise x to the yth power.
 ceil(x), floor(x) …and more
Exercise

Write a function that uses the formula



in order to approximate . The function should accept
an argument n which determines the number of terms in
the formula. It should return the approximation of .

Write a program that gets an integer n from the user,
and approximate  using n terms of the above formula.


Solution




pi.c
Exercise

Modify the previous function that approximates
. The function should accept an argument
specifying the desired accuracy, and keep
adding terms until the contribution of the next
term drops below this level.

Write a program that gets a (small) double
epsilon from the user, and approximates 
within this function.
Solution




pi_eps.c
The debugger
 Some programs may compile correctly, yet not produce the desirable results.
 These programs are valid and correct C programs, yet not the programs we meant to write!
 The debugger can be used to follow the program step by step and may help detecting bugs in an already compiled program.
The debugger’s common features
 Setting breakpoints (a point where the execution stops): bring the cursor to desired line and press the palm icon or F9. A dark red dot appears near the line.
 Executing a debugged run: Build->start debug->go or F5. The program will run and stop at the first breakpoint.
The debugger’s common features (cont.)
 Stopping at a specific line: Bringing the cursor to the line and press ctrl+F10, or Build->start debug->go to cursor. The program will stop at that point.
 Stepping to the next line – F10.
 Entering a function – F11.
 Seeing variable values – quickwatch and/or debug window at the bottom.
 The yellow arrow indicates our whereabouts at any given moment.

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);