0% found this document useful (0 votes)
69 views68 pages

Cs1100lec08 11

This document provides an overview of data types in C including integer types like int, char, and float. It discusses the sizes of these types, how they are represented in memory, and how to properly print values of different types. It also covers topics like number systems, binary representations, character sets, constants, and strings.

Uploaded by

ShellZero
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views68 pages

Cs1100lec08 11

This document provides an overview of data types in C including integer types like int, char, and float. It discusses the sizes of these types, how they are represented in memory, and how to properly print values of different types. It also covers topics like number systems, binary representations, character sets, constants, and strings.

Uploaded by

ShellZero
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 68

CS1100 Computational Engineering

Tutors: Shailesh Vaya [email protected] Anurag Mittal [email protected]

PSK, NSN, DK, TAG CS&E, IIT M

Data, Types, Sizes,Values


int, char, float, double char single byte, capable of holding one character Integer Qualifiers short and long short int 16 bits, long int 32 bits Compiler dependent, based on the underlying hardware int is at least 16 bits, short is at least 16 bits, long is at least 32 bits, and int is no larger than long, and at least as long as short
PSK, NSN, DK, TAG CS&E, IIT M 2

char, signed and unsigned


Qualifier signed or unsigned can be applied to int or char Unsigned numbers are non-negative Signed char holds numbers between 128 and 127. Whether char is signed or unsigned depends on the system. Find out on your system. Print integers between 0 to 255 as characters, and integers between 128 to 127 on your system.
PSK, NSN, DK, TAG CS&E, IIT M 3

Number Systems
Decimal (base 10 uses 10 symbols {0..9})
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13

Unary (base 1)
1, 11, 111, 1111, 11111

Binary (base 2) uses 2 symbols {0,1})


0, 1, 10, 11, 100, 101, 110, 111, 1000, 1001, 1010

Octal (base 8 start with a 0 in C)


0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13 00, 01, 02, 03, 04, 05, 06 C treats them as octal

Hexadecimal(base 16 start with 0x;uses A-F for 10-15)


0, 1, , 9, A, B, C, D, E, F, 10, 11, 19, 1A, 1B,
PSK, NSN, DK, TAG CS&E, IIT M 4

Quick Primer on Binary


Number representation in base n
Take every bit and assign weights in increasing powers of n
most significant least significant

329
102 101 100
3x100 + 2x10 + 9x1 = 329

101
21

22

20

1x4 + 0x2 + 1x1 = 5

For binary representation, the weight is 2

You can represent 2m unique values using m bits


PSK, NSN, DK, TAG CS&E, IIT M 5

Binary, Octal and Hexadecimal


The internal representation of binary, octal, and hexadecimal numbers is similar Octal - 2 7 3 2 5 6 0 6

Binary - 010111011010101110000110 Hexadecimal - 5 13 10 11 8 5 D A B 8 6


Converting back and forth between binary, octal and hexadecimal is very easy
PSK, NSN, DK, TAG CS&E, IIT M 6

m-bits and 2m Unique Numbers


You could technically map a m-bit sequence to any value
Practically useless though

Two useful mappings (with m = 3)


0 7
111 000

0 1
001 010 011

-1
111

000

1
001 010 011

6 110
101

-2 110
101

4 IIT MUnsigned PSK, NSN, DK, TAG CS&E,

100

-3

100

3
7

Signed

-4

Unsigned and Signed Forms


0 7 000 111 001 101 5 100 4 011 1 0 1 -1 000 111 001 -2 110 101 -3 Signed 100 -4 010 2 011 3 010 2 3 Unsigned

6 110

Both have the same internal representation (blue) They have different external representations (red) What is peculiar about the bit patterns of +ve numbers in unsigned form?
PSK, NSN, DK, TAG CS&E, IIT M 8

A funny infinite loop - arithmetic


This program of mine, ran into an infinite loop. I only wanted to find which numbers corresponded to which characters, the significance of signed and unsigned characters, basically relationship between which integers can be printed as characters we recognize. Why did the infinite loop happen, how to avoid it? #include<stdio.h> Print it as a Print it as a main() character decimal number {char c; for(c=-128; c <= 127; c++) printf(%d -- %c \n, c, c); }
PSK, NSN, DK, TAG CS&E, IIT M

Try omitting one parameter

Float and Double


Two types, one for single-precision arithmetic, and the other for double precision arithmetic Long double is used for extended-precision arithmetic. The size of floating pointing objects are implementation defined.

PSK, NSN, DK, TAG CS&E, IIT M

10

Variable Initialization
Variables may be initialized either at the time of declaration, for example, #define MAXLINE 200 char esc = \\; int i =0; int limit = MAXLINE + 1; float eps = 1.0e-5 Or they may be assigned values by assignment statements in the program Otherwise they contain some random values

PSK, NSN, DK, TAG CS&E, IIT M

11

Constants
At run time, each variable holds a value, which changes from time to time Constant has a value that does not change 1234 is of type int 123456789L is a long constant 123456789ul is an unsigned long constant 123.4 is a floating point constant, so is 1e-2 which denotes .01. Their type is double. If suffixed by an f, or by l, the type is float or long double, respectively
PSK, NSN, DK, TAG CS&E, IIT M 12

Character Constants
are integers, written as one character within single quotes. Example a, x, 1, 2 etc. The value of a character constant is the numeric value of the character in the machines character set. For example, 1 has the value 49 in the ASCII character set. That is, number 49, interpreted as a character code stands for 1 Character constants can participate in arithmetic. What does 1+2 hold? (not 3!) Understand this distinction. Character arithmetic is used mainly for comparisons.
PSK, NSN, DK, TAG CS&E, IIT M 13

ASCII Table

PSK, NSN, DK, TAG CS&E, IIT M

14

Characters escape sequences


\a \b \f \n \r \t \v alert (bell) backspace formfeed newline carriage return horizontal tab vertical tab \\ backslash \? question mark \ single quote \ double quote \ooo octal number Ex: \101 is 'A' \xhh hexadecimal Ex: 41 is 'A'
Non-printable characters
15

PSK, NSN, DK, TAG CS&E, IIT M

More Constants
Constant numbers, Constant characters, and now Constant Expressions Expressions all of whose operands are constants. These can be evaluated at compile time. Examples: #define NUM_ROWS 100 #define NUM_COLS 100 #define NUM_ELTS NUM_ROWS * NUM_COLS #define is preprocessor directive. Recall: #include

PSK, NSN, DK, TAG CS&E, IIT M

16

Enumerated Constants
enum boolean {No, Yes}

By default enum values begin with 0

defines two constants No = 0, and Yes = 1.

enum months {jan = 1, feb, march, april, may, jun, jul, aug, sep, oct, nov, dec}
when a value is explicitly specified (jan=1) then it starts counting from there

enum escapes {BELL = \a, BACKSPACE = \b, TAB = \t, NEWLINE =\n}
more than one constant can be specified explicitly
PSK, NSN, DK, TAG CS&E, IIT M 17

Enum and #define


Better than #define, the constant values are generated for us.
Values from 0 on wards unless specified Not all values need to be specified If some values are not specified, they are obtained by increments from the last specified value Variables of enum type may be declared, but the compilers need not check that what you store is a valid value for enumeration

PSK, NSN, DK, TAG CS&E, IIT M

18

Declaring Constants
The qualifier const applied to a declaration specifies that the value will not be changed. const int J = 25; /* J is a constant through out the program */ Response to modifying J depends on the system. Typically, a warning message is issued while compilation. const char MESG[] = how are you?; The character array MESG is declared as a constant which will store how are you?
PSK, NSN, DK, TAG CS&E, IIT M 19

Constants cannot change values


const numStudents = 180; numStudents = numStudents + 1; /* Incorrect */ const numGirls = 40; const numBoys = 40; const numStudents = numGirls + numBoys;

PSK, NSN, DK, TAG CS&E, IIT M

20

CS1100 Lecture 9
Tutors: Shailesh Vaya [email protected] Anurag Mittal [email protected]

PSK, NSN, DK, TAG CS&E, IIT M

21

Strings
A string is a array of characters terminated by the null character, \0. A string is written in double quotes. Example: This is a string. This is rejected by the C Compiler Anything within single quotes gets a number associated with it empty string Exercise: understand the difference between x and x.
PSK, NSN, DK, TAG CS&E, IIT M 22

32 bit numbers
Internally: 4,294,967,296 (232) different permutations that 32 bits can represent Signed 32 bit integers vary from -2,147,483,648 to 2,147,483,647 -231 to 231-1 Unsigned 32 bit integers vary from 0 to 4,294,967,295 0 to 232-1

PSK, NSN, DK, TAG CS&E, IIT M

23

Recall Signed/Unsigned
0 7 111 6 5 110 101 100 4 000 1 001 010 011 3 Unsigned -3 Signed 2 -2 -1 111 110 101 100 -4 0 000 1 001 010 011 3 2

m bit internal representation am-1am-2 ... a2a1a0 Signed Interpretation = -[2(m-1)*am-1]+2(m-2)*am-2+...+2(2)*a2+2(1)*a1+2(0)*a0 Unsigned Interpretation = +...+2(2)*a2+2(1)*a1+2(0)*a0 2
PSK, NSN, DK, TAG CS&E, IIT M

2(m-1)*am-1+2(m-2)*am24

Overflow in integers
#include <stdio.h> int main() { int i = 2147483647; unsigned int j = 4294967295; printf("%d %d %d\n", i, i+1, i+2); printf("%u %u %u\n", j, j+1, j+2); } Here is the result for some system: 2147483647 -2147483648 -2147483647 4294967295 0 1
PSK, NSN, DK, TAG CS&E, IIT M 25

Printing directives
#include <stdio.h> int main() { unsigned int un = 3000000000; /* system with 32-bit int */ printf("un = %u and not %d\n", un, un); return 0; } un = 3000000000 and not -1294967296
Both have the same internal representation
PSK, NSN, DK, TAG CS&E, IIT M 26

Printing directives
#include <stdio.h> int main() { short end = 200; /* and 16-bit short */ printf("end = %hd and %d\n", end, end); return 0; }
short decimal

end = 200 and 200

Printing a short decimal as a normal int is okay


PSK, NSN, DK, TAG CS&E, IIT M 27

Printing directives
#include <stdio.h> int main() { long big = 65537; printf("big = %ld and not %hd\n", big, big); return 0; } big = 65537 and not 1
When the value 65537 is written in binary format as a 32-bit number, it looks like 00000000000000010000000000000001. Using the %hd specifier persuaded printf() to look at just the last 16 bits; therefore, it displayed the value as 1.
PSK, NSN, DK, TAG CS&E, IIT M 28

Printing directives
#include <stdio.h> int main() { long long verybig = 12345678908642; printf("verybig= %lld and not %ld\n", verybig, verybig); 64 bits Truncated 32 bits return 0; } verybig= 12345678908642 and not 1942899938

PSK, NSN, DK, TAG CS&E, IIT M

29

Assignment and Arithmetic Rules


Basic data types, numbers and characters can be assigned to their corresponding variables. Example: char c = a; char no = 1; int j = 25; Arrays can be initialised when declared: char mesg[] = hello; is a valid declaration int numbers[5] = {0,1,2,3,4}; is a valid declaration But an assignment to an array in the program is a syntax error.
30

PSK, NSN, DK, TAG CS&E, IIT M

Functions to handle strings


String is a non-basic data type
Constructed data type require functions to handle regular datatypes have operators in C directly

Typical functions on strings are:


Length of a string Are two strings equal? Does a given pattern occur as a substring? Concatenate two strings and return the result

These are exercises to gain programming knowledge. But use standard functions provided with string.h
PSK, NSN, DK, TAG CS&E, IIT M 31

Recap
Variables Assignments relational operators (comparisons) Selection and repetition constructs: control structures Data types and their limitations Arrays arrayname[n], single dimensional array Arrayname[m][n] 2D array, arrayname[i] [j] gives the element in the i-th row and j-th coloumn 32

PSK, NSN, DK, TAG CS&E, IIT M

Logical Operators
Recall relational operators {<=, <, >, >=} to compare values && and ||
Called boolean and, boolean or Expressions involving these as operations take boolean values, and their operands also take boolean values. Called truth values also.

E1 && E2 is true if and only if both E1 and E2 are true E1 || E2 is true if and only if either E1 or E2 or both are Precedence of && is higher than ||, and both are lower than relational or equality operators

PSK, NSN, DK, TAG CS&E, IIT M

33

How to use these in a program


They are used when composite conditions are to be tested in decision statements.
for(i=0; i < lim 1 && (c = getchar()) != \n && c !=EOF; i++) s[i] = c;

The loop is executed as long as all the test conditions are true The loop is exited when any test condition becomes false
For example when an <Enter> is read from keyboard

PSK, NSN, DK, TAG CS&E, IIT M

34

Exercise
Write a program which will exit when a certain number of occurences of any keystroke is read.
You need arrays Loops Loops with logical operations and so on.

PSK, NSN, DK, TAG CS&E, IIT M

35

Operators
Increment operator : effect is to increment value of a variable
x = j++ // x gets the value of j, and then j is incremented x = ++j // j is incremented first, then assigned to x

Decrement operators decrements values


x = j-- //x gets the value of j, then j is decremented by 1 x = --j //j is first decremented, and then assigned to x

Assignment operator short cut


E1 op= E2 is equivalent to the assignment E1 = E1 op E2 x -= 5; same as: x = x - 5; Once you learn it, your code is concise Matter of taste
36

PSK, NSN, DK, TAG CS&E, IIT M

CS110 Lecture 10
Tutors: Shailesh Vaya [email protected] Anurag Mittal [email protected]

PSK, NSN, DK, TAG CS&E, IIT M

37

Functions = outsourcing
Break large computing tasks into small ones Helps you to build on what others have done
You and others write functions When you want to build a program, find out how to use the function and use it.

Use standard functions provided by the library.


You are hidden from the implementation Example you dont have to worry about how pow(m,n) is implemented

As engineers from different disciplines you will use and develop different set of functions
PSK, NSN, DK, TAG CS&E, IIT M 38

Modular Programming
Subprograms functions in C, C++, procedures and functions in Pascal facilitate modular programming Overall task is divided into modules Each module - a collection of subprograms a subprogram may be invoked at several points A commonly used computation hiding the implementation incorporating changes 39 PSK, NSN, DK, TAG CS&E, IIT M

Example of function sets


String manipulation Mathematical Finite Element Method
Used in structural analysis by Mechanical, Civil, Aero, etc. for stress calculations etc.

Most function libraries cost a lot


Business opportunity identify functions that are useful to your area of study, create libraries.

Functions for use in different software.


Say, functions for web services
PSK, NSN, DK, TAG CS&E, IIT M 40

Power Function
#include <stdio.h> function prototype int power (int, int); -- Computes the nth main () { power of base. for ( int i = 0; i < 20; i ++ ) printf(%d %d %d\n, i, power(3,i), power(-4,i); } int power (int base, int n) { int i, p = 1; Invocation with arguments for ( i = 1; i <= n ; i ++) A block p = p base; return p; }
PSK, NSN, DK, TAG CS&E, IIT M 41

Recursive Function Example


int power (int num, int exp) { int p; if (exp = = 1) return num; p = power(num, exp/2); if (exp % 2 = = 0) return p*p; else return p*p*num; }
The base case exp = 1 Guarantees termination

36*36*3 = 729*729*3 = 1594323 power (3, 13) 33*33 = 27*27 = 729 power (3, 6) 31*31*3 = 27 power(3,3) = 3 power(3,1)
PSK, NSN, DK, TAG CS&E, IIT M 42

Factorial (n)
n! = 1 * 2 * 3 * .... * (n-2) * (n-1) * n Iterative version int fact(int n) { int i; int result; result = 1; for (i = 1; i <= n; i++) result = result * i; return result; }
PSK, NSN, DK, TAG CS&E, IIT M

In practice int may not be enough!

43

Factorial(n) recursive program


n! = n (n-1)! int fact(int n) { if (n == 1) return(1); return(n * fact(n - 1)); } Shorter, simpler to understand Uses fewer variables Machine has to do more work running this one!
PSK, NSN, DK, TAG CS&E, IIT M 44

Basics
Function is a part of your program.
It cannot be a part of any other function main() is a function: it is the main function. Execution starts there or the control flow starts there From there it can flow from one function to another, return after a computation with some values, probably, and then flow on.

Transfer of control is affected by calling a function


With a function call, we pass some parameters These parameters are used within the function A value is computed The value is returned to the function which initiated the call The calling function can ignore the value returned It could use it in some other computation A function could call itself, these are called recursive function calls
45

PSK, NSN, DK, TAG CS&E, IIT M

Add functions to your Program


A program was a set of variables, and assignments to variables Now add function to it.
Set of variables Some functions including main() Communicating values to each other Computing and returning values for each other

Instead of one long program, we now write structured program composed of functions
46

PSK, NSN, DK, TAG CS&E, IIT M

Features
C program -- a collection of functions
function main ( ) - mandatory - program starts here.

C is not a block structured language


a function can not be defined inside another function only variables can be defined in functions / blocks

Variables can be defined outside of all functions


global variables - accessible to all functions a means of sharing data between functions - caution

Recursion is possible
a function can call itself - directly or indirectly
PSK, NSN, DK, TAG CS&E, IIT M 47

Function template
Return-type function-name(argument declarations) { declaration and statements return expression; }

PSK, NSN, DK, TAG CS&E, IIT M

48

Function Definition in C
return-type function-name (argument declarations) { variable/constant declarations and statements } No function declarations here! Arguments or parameters: the means of giving input to the function type and name of arguments are declared names are formal - local to the function the Matching number and type Return Value: for giving the output value of arguments
return ( expression ); -- optional

Invoking a function: funct-name(param1,param2, PSK, NSN, DK, TAG CS&E, IIT M ,paramn)

49

Function Prototype
defines
the number of parameters, type of each parameter, type of the return value of a function

used by the compiler to check the usage


prevents execution-time errors

function prototype of power function


int power ( int, int ); no need for naming the parameters

function prototypes - given in the beginning


PSK, NSN, DK, TAG CS&E, IIT M 50

More on Functions
To write a program
You could create one file with all the functions You could/are encouraged to identify the different modules and write the functions for each module in a different file Each module will have a separate associated header file with the variable declaration global to that module You could compile each module separately and a .o file will be created You can then cc the differnet .o files and get an a.out file This helps you to debug each module separately

PSK, NSN, DK, TAG CS&E, IIT M

51

Running with less memory


Functions
Provided to break up our problem into more basic units Control flow flows from function to function, saving the current context, changing contexts, then returning.. Helps the program to run with lesser memory, but slightly slower than a monolithic program without functions

The issue now with data associated with other functions. Typically functions communicate using the arguments and return values
PSK, NSN, DK, TAG CS&E, IIT M 52

Call by Value
In C, function arguments are passed by value
values of the arguments given to the called function in temporary variables rather than the originals the modifications to the parameter variables do not affect the variables in the calling function

Call by reference
variables are passed by reference
subject to modification by the function

achieved by passing the address of variables

PSK, NSN, DK, TAG CS&E, IIT M

53

Call by Value - an example


main( ) { Function prototype int p = 1, q = 2, r = 3, s; int test(int, int, int); Function call ; s = test (p, q, r); /* s is assigned 9 */ } /* p,q,r dont change, only their copies do */ int test( int a, int b, int c){ a ++; b ++; c ++; return (a + b + c); }
PSK, NSN, DK, TAG CS&E, IIT M

Function definition

54

Call by Reference
#include <stdio.h> void quoRem(int, int, int*, int*); /*pointers*/ main(){ Passing int x, y, quo, rem; addresses scanf(%d%d, &x, &y); quoRem(x, y, &quo, &rem); printf(%d %d, quo , rem); Does not return } anything void quoRem(int num, int den, int* quoAdr, int* remAdr){ *quoAdr = num / den; *remAdr = num % den; }
PSK, NSN, DK, TAG CS&E, IIT M

55

Pending computations
In this recursive version the calling version still has pending work after it gets the return value. (fact 4) 4 * (fact 3) It needs to save 3 * (fact 2) some values for future use 2 * (fact 1) 1 2*1 =2 3*2 = 6
PSK, NSN, DK, TAG CS&E, IIT M

int fact(int n) { if (n == 1) return 1; return n * fact(n - 1); }

56

Tail recursion
int fact(n) { return fact_aux(n, 1); }
Auxiliary variable

int fact_aux(int n, int result) { if (n == 1) return result; return fact_aux(n - 1, n * result); }


PSK, NSN, DK, TAG CS&E, IIT M

The recursive call is in the return statement. The function simply returns what it gets from the call it makes. The calling version does not have to save any values!
57

CS110 Lecture 11
Tutors: Shailesh Vaya [email protected] Anurag Mittal [email protected]

PSK, NSN, DK, TAG CS&E, IIT M

58

Multi-dimensional Arrays
Arrays with two or more dimensions can be defined B[2][4][3]
A[4][3] 0 1 0 1 2 3
PSK, NSN, DK, TAG CS&E, IIT M

2 0 1 2 3

1
59

Matrix Operations
An m-by-n matrix: M: m rows and n columns Rows : 1, 2, , m and Columns : 1, 2, , n
M(i,j) : element in ith row, jth column, 1 i m, 1 j n Array indexes in C start with 0. We could use (m+1) (n+1) array and ignore cells (0,i), (j,0); Programs can use natural convention - easier to understand. Our example later ignores 1st row and column.

Functions:
matRead (a,int,int); matWrite(a,int,int); matInit(a,v); matAdd(a,b,c,int,int); matMult(a,b,c,int,int,int);
PSK, NSN, DK, TAG CS&E, IIT M 60

Using Matrix Operations


main(){ int a[11][11], b[11][11], c[11][11]; / * max size 10 by 10 */ int aRows, aCols, bRows, bCols, cRows, cCols; scanf("%d%d", &aRows, &aCols); matRead(a,aRows, aCols); scanf("%d%d", &bRows, &bCols); matRead(b,bRows,bCols); initMat(c, 0); matMult(a, b, c, aRows, aCols, bCols); cRows = aRows; cCols = bCols; matWrite(c, cRows, cCols); }

Remember bRows=aCols

PSK, NSN, DK, TAG CS&E, IIT M

61

Reading and Writing a Matrix


void matRead(int mat[ ][11], int rows, int cols){ for(int i = 1; i <= rows; i++) For the compiler to figure for(int j = 1; j <= cols; j++) out the address of mat[i] scanf("%d", &mat[i][j]); [j], the first dimension } value is not necessary.
(Why?)

void matWrite(int mat[][11], int rows, int cols){ for(int i = 1; i <= rows; i++){ for(int j = 1; j <= cols; j++) /* print a row */ printf("%d ", mat[i][j]); /* notice missing \n */ printf("\n"); /* print a newline at the end a row */ } }
PSK, NSN, DK, TAG CS&E, IIT M 62

Matrix multiplication
Multiply two numbers N

N
PSK, NSN, DK, TAG CS&E, IIT M

Sum of N products

63

Matrix Multiplication
void matMult(int mat1[ ][11], int mat2[ ][11], int mat3[ ][10], int m, int n, int p){ for(int i =1; i <= m; i++) for(int j = 1; j <= p; j++) for(int k = 1; k <= n; k++) mat3[i][j] += mat1[i][k]*mat2[k][j]; } Remember it was initialized to zero in the
main program. It could have been done in this function as well probably a better idea.
PSK, NSN, DK, TAG CS&E, IIT M 64

scanf and getchar


getchar() reads and returns one character scanf formatted input, stores in variable
scanf returns an integer = number of inputs it managed to convert successfully
printf ("Input 2 numbers: "); if (scanf("%d%d", &i, &j) == 2) printf ("You entered %d and %d\n", i, j); else printf ("You failed to enter 2 numbers\n");

from <http://cprogramming.com>
PSK, NSN, DK, TAG CS&E, IIT M 65

Input buffer
Your input line is first stored in a buffer. If you are reading a number with scanf (%d) and enter 1235ZZZ, scanf will read 1235 into the variable and leave ZZZ in the buffer. The next read statement will get ZZZ and may ignore the actual input! One may need to write a statement to clear the buffer while (getchar() != '\n'); This reads and ignores input till the end of line.
PSK, NSN, DK, TAG CS&E, IIT M 66

Code to insist on one number only


#include <stdio.h> int main(void) { exit if one int temp; number printf ("Input your number: "); while (scanf("%d", &temp) != 1) { clear buffer before while (getchar() != '\n'); reading again printf ("Try again: "); } printf ("You entered %d\n", temp); return(0); }
PSK, NSN, DK, TAG CS&E, IIT M 67

Hailstone numbers
A Hailstone Sequence is generated by a simple algorithm. Start with an integer N. If N is even, the next number in the sequence is N / 2. If N is odd, the next number in the sequence is (3 * N) + 1. 7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1, ... repeats 12, 6, 3, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1 . 909, 2726, 1364, 682, 341, 1024, 512, 256, 128, 64, 32, 16, 8, 4, 2, 1, 4, 2, 1
PSK, NSN, DK, TAG CS&E, IIT M 68

You might also like