0% found this document useful (0 votes)
6 views

C Programming Week5

The document provides an introduction to arrays in programming, detailing their structure, declaration, and usage in C. It includes examples of reading numbers into an array, computing their average, and evaluating polynomials. Additionally, it covers data types, constants, enumerated constants, and string handling in C programming.

Uploaded by

ABHISHEK GOUTAM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

C Programming Week5

The document provides an introduction to arrays in programming, detailing their structure, declaration, and usage in C. It includes examples of reading numbers into an array, computing their average, and evaluating polynomials. Additionally, it covers data types, constants, enumerated constants, and string handling in C programming.

Uploaded by

ABHISHEK GOUTAM
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

15/09/17

An Array
• A data structure containing items of same data type
• Declaration: array name, storage reservation
– int marks[7] = {22,15,75,56,10,33,45};
CS1100 • a contiguous group of memory locations
22 0

15 1
Introduction to Programming • named “marks” for holding 7 integer items
75 2
– elements/components - variables
Arrays • marks[0], marks[1], … , marks[6] 56 3

• marks[i], where i is a position/subscript (0≤i≤6) 10 4


Madhu Mutyam
Department of Computer Science and Engineering – the value of marks[2] is 75 33
Indian Institute of Technology Madras 5
– new values can be assigned to elements
45 6
• marks[3] = 36;
Course Material – SD, SB, PSK, NSN, DK, TAG – CS&E, IIT M 1 2
SD, PSK, NSN, DK, TAG – CS&E, IIT M

Example using Arrays Counting Digits in Text (Kenighan & Ritchie, pp. 59)
Read ten numbers into an array and compute their average #include<stdio.h>
An array of ten integers
#include <stdio.h> int main( ){
int main( ){
int numbers[10], sum = 0, i; int c, i, nWhite, nOther, nDigit[10];
float average; nWhite = nOther = 0;
for ( i = 0; i < 10; i++) for(i=0;i<10;i++)
scanf(“%d”, &numbers[i]); nDigit[i]=0;
for ( i = 0; i < 10; i++) while((c = getchar( ))! = EOF){
sum = sum + numbers[i];
switch(c){
average = (float) sum/10;
printf(“The average of numbers is: %f”, average); case ‘0’:case ‘1’:case ‘2’:case ‘3’:case ‘4’:case ‘5’:
return 0; /* should be there in all programs */ case ‘6’:case ‘7’:case ‘8’:case ‘9’: nDigit[c- ‘0’]++;
}
SD, PSK, NSN, DK, TAG – CS&E, IIT M 3 SD, PSK, NSN, DK, TAG – CS&E, IIT M
break; 4

… Counting digits Polynomial Evaluation


case ‘ ’: Evaluate
case ‘\n’: p(x) = anxn + an-1xn-1 + an-2xn-2 + … a1x + a0 at a given x
value.
case ‘\t’: nWhite++; break;
default : nOther++; break; Computing each term and summing up
} n + (n-1) + (n-2) + … + 1 + 0 = n(n+1)/2 multiplications
} and n additions
printf(“Digits: \n”)
for(i=0;i<10;i++) Improved Method:
printf(“%d occurred %d times \n”, i, nDigit[i]); p(x) = a0 + x(a1 + x(a2 + x(a3 + …+ x(an-2 + x(an-1 + xan))…)))
for instance, p(x) = 10x3 + 4x2 + 5x + 2
printf(“White spaces: %d, other: %d\n”, nWhite, = 2 + x(5 + x(4 + 10x))
nOther); n multiplications and n additions – will run faster!
}
SD, PSK, NSN, DK, TAG – CS&E, IIT M 5 SD, PSK, NSN, DK, TAG – CS&E, IIT M 6

1
15/09/17

… Polynomial Evaluation More Exercises


#include <stdio.h> • Sort an array of numbers into ascending order.
main( ){
int coeff[20], n, x, value, i; /*max. no. of coeff ’s is 20*/ – Write the output into another array
scanf(“%d%d”, &n, &x); /*read degree and evaluation point*/ – Assuming that arrays are expensive, use only one
for(i = 0; i <= n; i++) array: read in the values into an array, sort in place,
scanf(“%d”, &coeff[i]); /* read in the coefficients */ and print out the array.
/* a0, a1, … , an */
value = coeff[n]; /* an */
• Matrix Sorting – The input is a matrix. Identify a
for(i = (n-1); i >= 0; i--) /* evaluate p(x) */ sequence of column interchanges such that in the
value = x*value + coeff[i]; resulting matrix the rows are all sorted in
printf(“The value of p(x) at x = %d is %d\n”, x, value); ascending order. Can every matrix be sorted?
}

SD, PSK, NSN, DK, TAG – CS&E, IIT M 7 SD, PSK, NSN, DK, TAG – CS&E, IIT M 8

Data, Types, Sizes, Values The Char, Signed and Unsigned Types
• int, char, float, double • Qualifier signed or unsigned can be applied to int
• char – one byte, capable of holding one character or char
• int – an integer, different kinds exist! • Unsigned numbers are non-negative
– Integer Qualifiers – short and long • Signed char holds numbers between –128 and 127
– short int – 16 bits, long int – 32 bits (Typical) – Whether char is signed or unsigned depends on the
– Size is compiler dependant system. Find out on your system.
• based on the underlying hardware – Print integers between 0 to 255 as characters, (and also
– int is at least 16 bits, short is at least 16 bits, long is at integers between –128 to 127) on your system.
least 32 bits
– int is no larger than long and at least as long as short
SD, PSK, NSN, DK, TAG – CS&E, IIT M 9 SD, PSK, NSN, DK, TAG – CS&E, IIT M 10

Number Systems Binary, Octal and Hexadecimal


• Decimal (base 10 – uses 10 symbols {0..9}) • The internal representation of binary, octal, and
– 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 … hexadecimal numbers is similar
• Unary (base 1)
– 0, 00, 000, 0000, 00000 …
Octal - 2 7 3 2 5 6 0 6
• 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)
Binary - 010111011010101110000110
– 0, 1, 2, 3, 4, 5, 6, 7, 10, 11, 12, 13…
– 00, 01, 02, 03, 04, 05, 06 … C treats them as octal 5 13 10 11 8 6
• Hexadecimal (base 16 – start with 0x) Hexadecimal - 5 D A B 8 6
– 0, 1, …, 9, A, B, C, D, E, F, 10, 11, … 19, 1A, 1B, …
SD, PSK, NSN, DK, TAG – CS&E, IIT M 11 SD, PSK, NSN, DK, TAG – CS&E, IIT M 12

2
15/09/17

A Funny Infinite Loop - Arithmetic Float and Double


• This program of mine, ran into an infinite loop. I only • Two types, one for single-precision arithmetic,
wanted to find which numbers corresponded to which and the other for double precision arithmetic
characters, the significance of signed and unsigned
characters, basically relationship between which integers • Long double is used for extended-precision
can be printed as characters we recognize. Why did the arithmetic
infinite loop happen, how to avoid it? • The size of floating pointing objects are
implementation defined
#include<stdio.h>
main( ){ Print it as a Print it as a
decimal number character
char c;
for(c=-128; c <= 127; c++) printf(“%d -- %c \n”, c, c);
} PSK, NSN, DK, TAG – CS&E, IIT M
SD,
Try omitting one parameter…
13 SD, PSK, NSN, DK, TAG – CS&E, IIT M 14

Variable Initialization Constants


• Variables may be initialized either at the time of • At run time, each variable holds a value, which
declaration changes from time to time
– Example: #define MAXLINE 200 • Constant has a value that does not change
char esc = ‘\\’; • 1234 is of type int
int i = 0;
• 123456789L is a long constant
int limit = MAXLINE + 1;
float eps = 1.0e-5
• 123456789ul is an unsigned long constant
• Or they may be assigned values by assignment • 123.4 is a floating point constant, so is 1e-2
statements in the program which denotes .01. Their type is double.
• Otherwise they contain some random values • If suffixed by an f, or by l, the type is float or
15
long double, respectively 16
SD, PSK, NSN, DK, TAG – CS&E, IIT M SD, PSK, NSN, DK, TAG – CS&E, IIT M

Character Constants … Characters – escape sequences


• …are integers, written as one character within
single quotes. Example – ‘a’, ‘x’, ‘1’, ‘2’ etc. \a alert (bell) \\ backslash
• Value of a character constant is the numeric value \b backspace \? question mark
of the character in the machine’s character set.
\f formfeed \’ single quote
– For example, ‘1’ has the value 49 in the ASCII
character set \n newline \” double quote
• Character constants can participate in arithmetic \r carriage return \0oo octal number
– What does ‘1’+ ‘2’ hold? (not ‘3’!) \t horizontal tab \xhh hexadecimal
• Understand this distinction \v vertical tab
– Character arithmetic is used mainly for comparisons
SD, PSK, NSN, DK, TAG – CS&E, IIT M 17 SD, PSK, NSN, DK, TAG – CS&E, IIT M
Non-printable characters 18

3
15/09/17

Constants Expressions Enumerated Constants By default enum


values begin with 0
• Expressions all of whose operands are constants • enum boolean {No, Yes};
• These can be evaluated at compile time – defines two constants No = 0, and Yes = 1.
• Examples: • enum months {jan = 1, feb, march, april, may,
#define NUM_ROWS 100 jun, jul, aug, sep, oct, nov, dec};
#define NUM_COLS 100 – when a value is explicitly specified (jan=1) then it
starts counting from there
#define NUM_ELTS NUM_ROWS*NUM_COLS
• enum escapes {BELL = ‘\a’, BACKSPACE =
• #define is preprocessor directive (recall #include)
‘\b’, TAB = ‘\t’, NEWLINE =‘\n’};
– more than one value can be specified

SD, PSK, NSN, DK, TAG – CS&E, IIT M 19 SD, PSK, NSN, DK, TAG – CS&E, IIT M 20

enum and #define Declaring Constants


• Better than #define, the constant values are • The qualifier const applied to a declaration
generated for us specifies that the value will not be changed.
– Values from 0 onwards unless specified – Example: const int J = 25; /* J is a constant through
– Not all values need to be specified out the program */
– If some values are not specified, they are obtained by • Response to modifying J depends on the system.
increments from the last specified value Typically, a warning message is issued while
• Variables of enum type may be declared compilation.
– but the compilers need not check that what you store – Example: const char MESG[] = “how are you?”;
is a valid value for enumeration – The character array MESG is declared as a constant
which will store “how are you?”

SD, PSK, NSN, DK, TAG – CS&E, IIT M 21 SD, PSK, NSN, DK, TAG – CS&E, IIT M 22

Strings Functions to Handle Strings


• A string is a array of characters terminated by the • Strings
null character, ‘\0’ – a non basic data type, a constructed data type
• A string is written in double quotes – we require functions to handle them
– Example: “This is a string” • Typical functions are:
• “ ” – empty string – Length of a string; string comparison; string
concatenation, etc.
• Anything within single quotes gets a number
associated with it • Standard functions are provided with string.h
– strlen( ); strcmp( ); strcpy( ); strncpy( ); strcat( );
• ‘This is rejected by the C Compiler’
strncat( );
• Exercise: understand the difference between ‘x’
and “x”
SD, PSK, NSN, DK, TAG – CS&E, IIT M 23 SD, PSK, NSN, DK, TAG – CS&E, IIT M 24

4
15/09/17

32-bit Numbers Overflow in Integers…


• Internally: 4,294,967,296 different (232) #include <stdio.h>
permutations that 32 bits can represent main( ) 231 - 1
{
• Signed 32 bit integers vary from int i = 2147483647; 232 - 1
-2,147,483,648 to 2,147,483,647 unsigned int j = 4294967295;
-231 to 231-1 printf("%d %d %d\n", i, i+1, i+2);
• Unsigned 32 bit integers vary from printf("%u %u %u\n", j, j+1, j+2);
0 to 4,294,967,295 }
0 to 232-1
Here is the result for some system:
2147483647 -2147483648 -2147483647
4294967295 0 1
SD, PSK, NSN, DK, TAG – CS&E, IIT M 25 SD, PSK, NSN, DK, TAG – CS&E, IIT M 26

Printing Directives Printing Directives


#include <stdio.h> #include <stdio.h>
main( ){ main( ){
unsigned int un = 3000000000; short end = 200; /* and 16-bit short */
/* system with 32-bit int */ printf("end = %hd and %d\n", end, end);
printf("un = %u and not %d\n", un, un); return 0;
return 0; } short decimal

} end = 200 and 200


un = 3000000000 and not -1294967296

Both have the same internal Printing a short decimal as a


normal int is okay
SD, PSK, NSN, DK, TAG – CS&E, IIT representation
M 27 SD, PSK, NSN, DK, TAG – CS&E, IIT M 28

Printing Directives Assignment and Arithmetic Rules


#include <stdio.h> • Basic data types, numbers, and characters can be
main( ){ assigned to their corresponding variables
long big = 65537; – Example: char c = ‘a’; char no = ‘1’; int j = 25;

printf("big = %ld and not %hd\n", big, big); • Arrays can be initialised when declared:
– char mesg[] = “hello”; //is a valid declaration
return 0;
– int numbers[5] = {0,1,2,3,4}; //is a valid declaration
}
• But an assignment to an array in the program is a
big = 65537 and not 1 syntax error
When the value 65537 (216 + 1) 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;
SD, PSK, NSN, DK, TAG – CS&E, 29 30
therefore,
IIT M it displayed the value as 1. SD, PSK, NSN, DK, TAG – CS&E, IIT M

5
15/09/17

Recap Logical Operators


• Variables • Recall relational operators {<=, <, >, >=} to
• Assignments compare values
• Relational operators (comparisons) • Boolean AND ( && ) and Boolean OR ( || )
• Selection and repetition constructs: control – Expressions involving these as operations take Boolean
values, and their operands also take Boolean values
structures
• Called truth values also
• Data types and their limitations – E1&&E2 is true if and only if both E1 and E2 are true
• Arrays : arrayName[n], single dimensional array – E1||E2 is true if and only if either E1 or E2 or both are
– arrayName[m][n] – 2D array • Precedence of && is higher than ||, and both are
– arrayName[i][j] gives the element in the i-th row and lower than relational or equality operators
j-th column
SD, PSK, NSN, DK, TAG – CS&E, IIT M 31 SD, PSK, NSN, DK, TAG – CS&E, IIT M 32

How to use these in a program Operators


• They are used when composite conditions are to • Increment operator: effect is to increment value of
be tested in decision statements a variable
for(i=0;i < lim–1&&(c=getchar())!=‘\n’&&c!=EOF;i++) • x = j++ //x gets the value of j, and then j is incremented
s[i] = c; • x = ++j //j is incremented first, then assigned to x
• The loop is executed as long as all the test • Decrement operators – decrements values
conditions are true • x = j-- //x gets the value of j, then j is decremented by 1
• The loop is exited when any test condition • x = --j //j is first decremented, and then assigned to x
becomes false • Assignment operator short cut
– For example when an <Enter> is read from keyboard • E1 op= E2 is equivalent to the assignment E1 = E1op E2
• x -= 5; same as: x = x – 5;
SD, PSK, NSN, DK, TAG – CS&E, IIT M 33 SD, PSK, NSN, DK, TAG – CS&E, IIT M 34

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

SD, PSK, NSN, DK, TAG – CS&E, IIT M 35

You might also like