Wednesday, May 2, 2007

WASE C 25-03-7

BHARAT INSTITUTE OF ENGINEERING AND TECHNOLOGY
C Programming Language
Rajesh Kulkarni

Recommended Text Book
Reference Text Books

Why Learn C?
Feature of C Program
1. Every c program requires a main() function
2. The execution of a function begins at ( and ends t )
3. Programs should written in lowercase and uppercase are used for defining symbolic constants.
4. All the words in a program line must be separated from other by
at least one space or tab or punctuation mark.
5. Every statement must ends with a semi colon.
6. C is a free form language
a=b;
a=b+1; can be written in one line as a=b; a=b+1;

Character Set
The Character set in C are grouped into
1.Letters A,B,C…….Z; a, b, c ……z.
2.Digits 0,1,2……..9.
3.Special characters @,#,$,^………….etc
4.White Spaces

C Tokens (KISSCO)
Smallest individual units in c programming known as Tokens
1.Keywords
2.identifiers
3.Strings
4.Special Symbols
5.Constants
6.Operators
Key words
These are pre defined words have a fixed meanings.
All key words must be written in lower case letters.
Every word in c is either a keyword or identifier

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
Identifiers
 Identifier refers to the names of variables ,functions ,and arrays.
 Upper case and lower case letters are permited,but commonly lowercase letters we used.
 It consists of letters and digits with letter as a first character.
 Underscore also used as first letter

Constants
Constants in C refer to fixed values do not change during the execution of the program.
Integer constant: It refer to a sequence of digits, 0 through 9 preceded
by - or +. Ex: 149, -980, +45.
Real constants: the quantities which are represented by numbers
containing fractional part. Ex:0.78, 2.45.
It is also represented in exponential notation
Ex: the value 4356.78 can represented as 4.35678e3.
Single character constant: It contains a character enclosed within a pair
of single quote marks. Ex: '2' , 'a' .
String constant: It is a sequence of characters enclosed in double quotes.
Ex: "india" , "2*3", "n".
Back slash character constant (Escape sequences):
'\n' for new line
'\t' for horizontal tabulator
'\v ' for vertical tabulator
'\0' Null character.
Constants (Cont.)
Integer Constants
1.Decimal
2.Octal( Leading with 0)
3.HexaDecimal(Leading with 0x/oX)
Embedded spaces ,commas,nondigit characters are not permitted
Data Types
Data type size range
int 2 bytes -32,768 to 32,767
char 1 byte -128 to 128
float 4 bytes 3.4e-38 to 3.4e+38
double 8 bytes -1.7e-308 to1.7e+308
Variables
It is a data name that may be used to store value. Variable name may consist of letters ,digits, underscore(_) characters subject to the following conditions:
 Variable must begin with letter.
 Variable name should not be more than 8 characters.
 Upper case and Lower case are significant.
 Variable name should not be key word.
 White space is not allowed.
Declaration of variables
Declaration tells to the compiler variable name with specifying data type.

a) Primary type : Syntax : data-type variable1,variable2,……..variable n;
Ex : float marks;

b) User defined type : C supports a feature known as type definition that
allows user to define an identifier.
Syntax : typedef data-type identifier;
Ex: typedef int units;
c) Enumerated data type: It contains enumeration constants represented
by identifiers.
Syntax: enum identifier { value 1,value 2,…..value n};
Ex: enum day { Monday, Tuesday,……Sunday};

d) Declaring variable as constant: The value of variable can be made to
remain constant.
syntax: const data-type variable = value;
Ex : const int max = 40;
e) Declaring variable as volatile :The value of variable may be changed
by some external reasons from out side.
Syntax : volatile data-type variable;
Ex : volatile int date ;
Declaration of Storage Classes

Automatic variable: Local variable known to only to the function in which is declared default is auto .
syntax : auto data-type variable;
Ex : auto int number;
Extern variables: Global variable known to all functions in the file. It is used to crossing files.
Syntax: extern data-type variable;
Ex: extern int number;
Static variables: Local variable, which exists and retains its value even after the control is transferred to the calling function.
Syntax : static data-type variable;
Ex : static int x;
Register variables: Local variable, which is stored in the CPU register. It is fast access variable.
Syntax : register data-type variable;
Ex : register int x;

Value can be assigned to variables using the assignment operator.
Syntax : data-type variable-name =constant;
Ex: int units =123;
Multiple assigning : Ex: x = y= z = max;
Type casting: C allows, if the operation are of different it types the lower type
is converted to the higher type to before operation proceed.
Syntax : (type-name) expression/value;
Ex: x = (int) 7.5 result = 7
Abstract data type: It is a tool which specifies the logical properties of a data type .
Syntax: abstract typedef < integer , integer > RATIONAL

Defining symbolic constants: This is useful when a constant will be used number
of places in a program.
# define symbolic-name value
Ex : #define MAX 100
# define PI 3.14159
Operators
Operator is a symbol that tells the computer to perform certain mathematical or logical manipulations.
Expressions operators along with the variables or operands is said to be expressions.
1.Arithemetic Operators
2.Relational Operators
3.Logical Operators
4.Assignment Operators
5.Increment & Decrement Operators
6.Conditional Operators
7.Bitwise Operators
8.Special Operators
Operators (Cont.)
Operators (cont.)
Special Operators in C
C Special Conditional Expression
Associativity and Precedence Rules
Order of Evaluation




Order of Evaluation
Comments
Good CommentingChapter 11
Introduction to
Programming 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 though
LC-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
• Function

function Heading(Argument list)


• Compound statement

compound statement = { …..}

{ expression statements seperated by semicolon ;}

• Comments anywhere = /*……*/

Structure of a C Program
• Documentation
nesting of comments not allowed

• Definition
symbolic constants

• Link section
links 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
• Numeric
Integer
Real
• Character
Single
String


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 and
variables 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 confuse
or to restate the obvious

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

This is the code that is executed
when 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 and
formatting 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 the
variable 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 are
available 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);
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

WASE CONTROL STMTS 08-04-07

#include
main()
{
printf("hello world\n");
printf("my age is 36\n");
getchar();
}


#include/*output*/
main()
{
int a;
printf("%d",a);
getchar();
}


#include
main()/* any errors*/
{
int 36age;
……
}


#include /* any errors!*/
main()/* any variable, define*/
{
age;
clrscr();
printf("hello world\n");
scanf("%d",age);
printf("the age u entered is %d",age);
fflush(stdin);
getchar();
}



#include
main()
{
int nob,nos,noc,ts,tc;
char name[10];
clrscr();
printf("enter your name:");
scanf("%s",&name);
printf("%s",name);
printf("\thow many brothers u have:",name);
scanf("%d",&nob);
printf("how many sisters u have:");
scanf("%d",&nos);
printf("how many children u have:");
scanf("%d",&noc);
ts=nob+nos;
tc=noc;
printf("total brothers and sisters are %d and total children are %d",ts,tc);
fflush(stdin);
getchar();
}

#include
main()
{
int age;
clrscr();
printf("enter your age:");
scanf("%d",&age);
printf("the age you entered is %d");
fflush(stdin);
getchar();
}



#include
main()
{
printf("hello world\n");
getchar();
}




#include

main

(

)


{

printf(" he llo world\n");
getchar();
}


#include
main()
{
int age;
printf("hello world\n");
age=36;
printf("my age is %d\n",age);
getchar();
}

main()/*any interesting thing!*/
{
int age;
printf(“hello world\n”);
scanf(“%d\n”,age);
printf(“%d”,age);










#include
main()
{
char name[20],str2;
int length;
clrscr();
/* name ="rajesh";*/
strcpy(name,"rajesh");
strcpy(str2,"my name is\t");
strcat(str2,name);
printf(name);
printf("\n%s",str2);
length=strlen(str2);
printf("\n%d",length);
getchar();
}










#include
main()
{
int age,half,years;
clrscr();
printf("enter your age:");
scanf("%d",&age);
fflush(stdin);
half=age/2;
years=age-5;
printf("\nhalf your age is %d",half);
printf("five years ago your age was %d",years);
getchar();
}










#include
main()
{
int x,y,z,p;
clrscr();
x=9;
y=x+6/3; /* divided by happens first result is 11*/
z=x*y+1+2-3*4;/*multiply happens first result is 90*/
printf("%d\t%d\t%d\n",x,y,z);
y=(x+6)/3;
p=15%6;
printf("%d\t%d\n",y,p);
p=(10+5)%12;
printf("%d\n",p);
printf("%d\n",3*17);
getchar();
}







#include
main()
{
int x=415;
double y=3.14159;
int len=1;
char string[30];
clrscr();
strcpy(string,"hello");
printf("12345678901234567890123456789\n");
printf("%s<<<<\n",string);
printf("%10s<<<<\n",string);/*right justified*/
printf("%-10s<<<<\n",string);/*left justified*/
printf("%.3s<<<\n",string);/*maximum number of characters*/
printf("%.*s",len,string);/*maximum characters specified by len */
printf(" \n ");
printf("* *\n");
printf("** **\n");
printf("12345678901234567890123456789\n");
printf("%d<<<<\n",x);
printf("%10d<<<<\n",x);
printf("%-10d<<<<\n",x);
printf("%010d<<<<\n",x);
printf("%.*d<<<<\n",len,x);
printf("%.1d<<<<\n",x);
printf(" \n ");
printf("* *\n");
printf("** **\n");
printf("12345678901234567890123456789\n");
printf("%c<<<<\n",string[0]);
printf("%10c<<<<\n",string[0]);
printf("%-10c<<<<\n",string[0]);
getchar();
}

#include
main()
{
int x;
double y;
char string[100];
clrscr();
printf("enter a word:");
scanf("%s",string);/*no ampersand is used*/
fflush(stdin);
printf("\n the word entered is %s\n",string);
printf("enter many words:");
scanf("%[^\n]",string);
fflush(stdin);
printf("%s\n",string);
getchar();
}


#include
main()
{
int age,magic_age=40;
clrscr();
printf("enter your age:");
scanf("%d",&age);
fflush(stdin);
printf("you are %d years old!\n",age);

if (age > magic_age)
printf("you are very old!\n");
printf("you are %d older than %d\n",age-magic_age,magic_age);
getchar();
}







#include
main()
{
int age;
clrscr();
printf("please enter your age:");
scanf("%d",&age);
fflush(stdin);
if ( age > 30)
printf("you are older than 30\n");
age = age +5;

printf("\n\n=====block within a block====\n\n");

{
int newage;
newage=age+30;
printf("newage is %d\n",newage);
}
getchar();
}

#include
main ()
{
int age,magic_age=40;
clrscr();
printf("enter your age:");
scanf("%d",&age);
fflush(stdin);
printf("your age is %d\n",age);

if (age < magic_age)
printf("you are young\n");
else
if (age > magic_age)
printf("you are old\n");
else
if (age == 40)
printf("perfect!!!\n");
else
printf("invalid age!\n");
getchar();
}



#include
main()
{
int age;
clrscr();
printf("enter age:");
scanf("%d",&age);

if (age <30);/* no error will be shown and wow! will be printed irrespective of whatever you enter*/
printf("wow!");
}













#include
main()
{
int age;
clrscr();
printf("enter age:");
scanf("%d",&age);

if(age <= 1)
printf("kid\n");
else if (age <=18)
printf("youngster\n");
else if (age == 21)
printf("now you are grown up\n");
else if (age == 40)
printf(" you are getting older\n");
else
printf("invalid entry\n");
fflush(stdin);
getchar();
}



#include
main()
{
double x=5000.0,y=0.0025,num=13.4485;
clrscr();
printf("12345678901234567890123456789\n");
printf("%f %f\n",x,y);/* if %d is used output is 0*/
printf("%e %e\n",x,y);
printf("%f\n",num);
printf("%10f\n",num);
printf("%12.5f\n",num);
printf("%.3f\n",num);
getchar();
}








#include
main()
{
int i=12345;
float x=345.678;
clrscr();
printf("12345678901234567890123456789\n");
printf("%3d\n",i);
printf("%5d\n",i);
printf("%8d\n",i);
printf("%3g\n",x);
printf("%10g\n",x);
printf("%13g\n",x);
getchar();
}









#include
main()
{
float x=123.456;
clrscr();
printf("12345678901234567890123456789\n");
printf("%7f\n",x);
printf("%7.3f\n",x);
printf("%7.1f\n");















#include
main()
{
int age;
clrscr();
printf("please enter your age:");
scanf("%d",&age);
printf("\nyou are %d years old\n",age);

switch(age)
{
case 1:

case 2:

case 3:
printf("sorry you can not go to school\n");
break; /*if break is forgotten next stmt will be executed*/

case 5:
printf("you are now in I class\n");
break;

case 15:
printf("you must be in 10th standard now\n");
break;

case 18:
printf("ready to vote!!!\n");
break;

case 21:
printf("ready to get married\n");
break;

case 40:
printf("you have matured\n");
break;

case 58:
printf("you can retire, now!!!\n");
break;

default:
printf("your age is of no importance!\n");
}
fflush(stdin);
getchar();
}



















#include
main()
{
int age;
int very_old = age >=80;
clrscr();
printf("enter your age:");
scanf("%d",&age);

if (very_old)/*if(3+4) will also give the same result*/
printf("you are very old as you are %d years old\n",age);
printf("the value of the variable very_old is %d\n",very_old);
fflush(stdin);
getchar();
}







/*correct the bug*/

main()
{
int x = 1:

if (x = 1);
printf("x equals 1\m")
otherwise
printf("x does not equal 1\m");

fflush(stdio);
getchar(char);
)











#include
main()
{
int x=5;
clrscr();
if(x=1)
printf("one\n");
getchar();
}

Exercise

Wap CD shop database.input the following details and print them again on the screen.

movie,director,number of songs,hit/fail,price.








/*use of got lable*/
main()
{
int age;
char name[41];
int very_old;

printf("Please enter your age: ");
scanf("%d", &age);
printf("You are %d years old\n", age);

if (!(age <= 19 && age >= 13))
goto other;
if (age > 19 || age < 13)
printf("You are not a teenager\n");

up:
if (age == 10 || age == 20 || age == 30 || age > 100)
printf("You have a special age\n");

printf("Please enter your name: ");
scanf("%s", name);

if (!(strcmp(name, "Bruce") != 0 && age != 40))
printf("You not called Bruce and are aged 40.\n");
if (strcmp(name, "Bruce") == 0 || age == 40)
printf("You not called Bruce and are aged 40.\n");

other:
very_old = age > 80;

if (!very_old)
printf("You are not very old\n");
if (very_old == 0)
printf("You are not very old\n");

if (age > 10)
goto up;
fflush(stdin);
getchar();
}


two approaches of programming:

programmer’s perspective
• structured programming
• object oriented programming

end user’s perspective
• sequential
• event driven




. • Assignment operator =
. • Arithmetic operators +, -, *, /, %
. • Relational operators >, >=, <, <=, == , !=
. • Logical operators !, &&, ||
. • Address operator &
. • Increment and Decrement operators ++, -
. • Compound Assignment Operators =, +=, -=, /=, *=, %=
. • sizeof operator


The basic arithmetic operators help us in performing the arithmetic operations.The % (modulo operator) is used to find the reminder of a divide operation eg.


int x=5,y=2;

int z=5/2;

will store 2 in z

int z=5%2

will store 1 in z % operator cannot be applied to float data type. Hence the instruction

5.2 % 2.5

will result in error For comparing if 2 values are equal or not remember to use == and not a single =.

== indicates comparisons and

= indicates assignment operation


eg. int x=5,y=3 x==y
will be considered as an conditional expression that will be evaluated to true(non-zero) for false(zero)
x=y will be considered as an assignment expression which will assign 3 (value of y) to x. x after the instruction will have value 3.



Logical operators available are

! (NOT), && (AND), || (OR) eg.

consider 3 variables x,y,z containing values 1,2,3 respectively


x=1, y=2, z=3

the condition x==1 && y == 3 will evaluate to false
the condition x==1 && z==3 will evaluate to true


the condition x==1 || y==3 will evaluate to true


the condition x==1 || z==3 will evaluate to true

the condition !(x <2 && y==2) will evaluate to false

Classification of Operators:
.(1) Based on the number of operands:
.
.Unary operators ++, -
.
.Binary operators +,-,*,/,%,==,<,>,>=,<=,!=,&&,||
.
.Ternary operators ? :
.
.(2) Based on the operations performed:
.
.Arithmetic operators
.
.Relational operators
.
.Logical operators

• Assign an expression to a variable
Syntax
Variable = Variable or constant or expression
data-type variable = constant
Example:

iNum = 10;


int i = 10;
float f = 13.24;
The statement i = f, will truncate the value .24 from f and i will have a value 13


Type Casting
. • Temporary conversion of one data type into another
. • In some situations, the compiler will automatically convert one data type into another
. • Type casting is an overhead for the compiler
. • Example:

float fResult;
fResult = 7 / 2 ;

The variable fResult will store 3.0 instead of 3.5
To get the ‘float’ value, the expression should be:
fResult = 7.0 / 2; or
fResult = 7 / 2.0; or
fResult = 7.0 / 2.0; or
fResult = (float) 7 / 2; or
fResult = 7 / (float) 2;

Precedence of Arithmetic Operators
Operator Priority
* , / and % Highest
+ and Lowest



Structured Programming
Rajesh Kulkarni
Control Structures: conditional constructs
if statement
if (expression) statement1
if (expression) statement1 else statement2

expression must have an integral type. Zero is false, nonzero is true.
 Notes:
 expression must be parenthesized
Examples
Examples
 Which of the following code is preferred?why?
Examples
/* This program displays the absolute value of a number given by the user */
#include

int main()
{
double num;

printf("Please enter a real number: ");
scanf("%lf", &num);
if (num<0)
num = -num;

printf("The absolute value is %g\n", num);

return 0;
}
if-else statement
condition
True or false
 In C, every expression has a numeric value
 An expression is ‘true’ when its value is non-zero
 If it is zero, it is false
 Therefore, in the following –

if (expression) statement

statement is executed if expression is non zero.
More about operators
 In C, every expression has a numeric value
 When using arithmetical operators (+, -, *, /) this is straightforward
 The value of A+B is the sum of A and B
 And so on…
More about operators
 Expressions with relational operators (<, <=, >, >=, etc.) have values as well (intuitively, we are used to thinking about them as ‘true’ or ‘false’)
 A < B evaluates to zero if A is larger than or equal to B, and some non-zero value if A is smaller than B
 The exact non-zero value varies (and is not important for that matter)
Relational operators
 They are:
 A == B (Note the difference from A = B!!!!!)
 A != B
 A < B
 A > B
 A <= B
 A >= B
 The value of the expression is non-zero if it’s true, zero if it’s false
An example (fragment)
int first, second, min;
/* … */
if (first < second)
{
min = first;
printf ("The first number is smaller than the second.\n");
}
else
{
min = second;
printf ("The second number is smaller than the first\n");
}

printf("The smaller number is equal to %d\n", min);
An example
int a, b;

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

if (a == b)
{
printf("The numbers equal %d\n", a);
printf("The expression a == b is %d\n", a == b);
}
else
{
printf("The numbers are not equal\n");
printf("The expression a == b is %d\n", a == b);
}


The assignment operator =
 The assignment operator is also an operator. Hence, expressions involving it have a numeric value.
 This value equals to whatever appears on the right of the assignment operator
 For example:
 (x = 4) evaluates to 4
 (y = 0) evaluates to 0
A very common mistake
 Very often a programmer might confuse between the equality operator and the assignment operator:
 if (x==4) …
 if (x=4) …
 The second is usually a mistake, but legal in C so the compiler doesn’t warn us about it!
Logical operators
 Allows to evaluate two or more expressions -
 !A – ‘not’ - True when A is not, and vice versa.
 A && B – ‘and’ - True when both A and B are true
 A || B – ‘or’ (inclusive or) - True when either A or B (or both) are true
A silly example
#include

int main(void)
{
int grade;

printf("Please enter your grade: ");
scanf("%d", &grade);

if (grade < 0 || grade > 100)
printf("This is not a valid grade!\n");
else
printf("This is indeed a grade.\n");

return 0;
}
Example
main()
{ int x;
scanf(”%d”,&x);
if(x%2)
{
printf(“ the number %d is ODD\n”,x);
}
else
{
printf(“ the number %d is EVEN\n”,x);
}

}
Example
main()
{ int x,y;
x=10;y=20;
printf(“ %d%d are\n”,x,y);
x=x+y;
y=x-y;
x=x-y;
printf(“ %d%d are\n”,x,y);
}



Dangling else problem
if (exp1) if (exp2) stmta else stmtb
Avoiding the dangling else problem
Null statement
if (exp1)
if (exp2)
stmta
else
;
else
stmtb
else if statements
 if statements distinguish between exactly 2 cases and execute different code in each case
 The else-if construction allows for a multi-way decision


else if statements
if (expression)
statement
else if (expression)
statement
else if (expression)
statement
else
statement
An example
if (grade >= 90)
printf ("A\n");
else if (grade >= 80)
printf ("B\n");
else if (grade >= 70)
printf ("C\n");
else if (grade >= 60)
printf ("D\n");
else
printf ("F\n");
Validating input
 When getting input from the user, it is highly recommended to check whether it is valid.
 If it’s not, you should display an appropriate message and return a non-zero value.
 For example –
if (grade < 0 || grade > 100)
{
printf(“Invalid input!\n”);
return 1;
}
The return keyword
 For now, used to terminate the program and return a value to the operating system
 If the program is successful the return value should be zero; non-zero otherwise
 The exact nature of this keyword will become clear in the future
Exercise
 Input –
 An English letter
 Output –
 If input is a lowercase letter – the corresponding uppercase letter
 If input is an uppercase letter - corresponding lowercase letter
 Note –
 Remember to check for input validity!

Exercise
 Input
 Two integers, A and B
 Output
 Their relation (i.e. displays A==B, AB)
Solution
#include

int main()
{
int A, B;

printf("Enter two Numbers\n");
scanf("%d%d", &A, &B);
if (A == B)
printf("A==B\n");
else if (A > B)
printf("A>B\n");
else
printf("A
return 0;
}

The switch statement
 a multiway conditional statement
 similar to if-else if-else
 allows the selection of an arbitrary number
of choices based on an integer value



The switch statement
 expression must have an integer value
 when the switch statement is executed:
 the expression is evaluated
 if a case matches the value of the expression, the program jumps to the first statement after that case label
 otherwise, the default case is selected
 the default is optional

That grade example again
switch (grade/10) {
case 10:
case 9:
printf ("A\n");
break;
case 8:
printf ("B\n");
break;
case 7:
printf ("C\n");
break;
case 6:
printf ("D\n");
break;
default:
printf ("F\n");
}
Give me a break
 when the switch transfers to the chosen case, it starts executing statements at that point
 it will “fall through” to the next case unless you “break out”
 break causes the program to immediately jump to the next statement after the switch statement


switch
switch (expression) {
case const-expr/: statements
case const-expr/: statements
default : statements
}

switch (digit)
{
case 0:
case 1:
case 2:
case 3:
case 4: printf (“Round down\n”);
break;
case 5:
case 6:
case 7:
case 8:
case 9:printf(“Round up\n”);
}




Exercise
 Write a program that accepts a number between 1 and 100 from the user. If there is a coin of that value in cents, it should display its name. Otherwise, it should report that there is no such coin
 1 = cent, 5 = nickel, 10 = dime, 25 = quarter, 100 = dollar
 Remember to check for the validity of the input!
The ?: operator
 expr1 ? expr2 : expr3
 Nicer way to write:
 (expr1)? expr2 : expr3
 If expr1 is true (non-zero), expr2 is evaluated. Otherwise, expr3 is evaluated

The ?: operator
#include

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

printf("Please enter two numbers: ");
scanf("%d%d", &i, &j);

min = (i < j)? i : j;
printf("The minimum between %d and %d is %d\n", i, j, min);

return 0;
}
Goto Statements
goto label;
………
……..
label : statements;

Goto Statements
 Forward goto: if statement along with the label appear below the goto statement
 Backward goto: if statement along with the label appear above the goto statement

Iteration Constructs
 Iteration constructs repeat a sequence of code in a controlled manner.
 while
 for
 do-while
while loop
while (expression)
statement

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