Programming Concepts and C Language

102
I semester BE, SJCE Mysor e. 1 Programming Concepts and C Language For I semester BE VTU Slides prepared by Prathima A S

description

Programming Concepts and C Language. For I semester BE VTU Slides prepared by Prathima A S. Introduction to C. Derived from BCPL (Basic Combined Programming Language) in 1972 by Dennis Ritchie at Bell Labs Sample C program main() { /* printing the message */ - PowerPoint PPT Presentation

Transcript of Programming Concepts and C Language

Page 1: Programming Concepts and C Language

I semester BE, SJCE Mysore. 1

Programming Concepts and C Language

For

I semester BE

VTUSlides prepared by Prathima A S

Page 2: Programming Concepts and C Language

I semester BE, SJCE Mysore. 2

Introduction to C

•Derived from BCPL (Basic Combined Programming Language) in 1972 by Dennis Ritchie at Bell Labs

•Sample C programmain()

{

/* printing the message */

printf(“Hello World”);

}

Page 3: Programming Concepts and C Language

I semester BE, SJCE Mysore. 3

• Name of program is main( )

• Execution begins here

• main( ) tells computer where program begins

• Only one main

• { - begin of function

• } – end of function

• /* */ - comment : ignored by compiler.

• printf( ) – standard C function.

• Distinction between uppercase and lowercase

Page 4: Programming Concepts and C Language

I semester BE, SJCE Mysore. 4

Constants, Variables and Data Types

• Character Set :– Letters : A..Z, a..z

– Digits : 0..9

– Special characters : , . : ; ? ’ “ ! | / \ ~ -_ $ % # & ^ * + - < > ( ) { } [ ]

– White space : blank space, horizontal tab, vertical tab,carriage return, new line, form feed.

Page 5: Programming Concepts and C Language

I semester BE, SJCE Mysore. 5

• C tokens : individual units.– Keyword – float, while, for, int,….

– Identifier – main( ) , amount, sum, …

– Constants – -13.5, 500, …

– Strings – “ABC”, “MCA”, …

– Operators – + - * % …

– Special Symbols – [ ] { }…

Page 6: Programming Concepts and C Language

I semester BE, SJCE Mysore. 6

• Keywords• Fixed meaning, cannot be changed• Basic building block• Lowercase• eg. Break, int, do, for,…

• Identifiers• Refers to names of variables, functions,…• User defined names• Uppercase and lowercase

• Constants• Fixed values• Do not changes during execution of program• Numeric constant – Integer (decimal, octal, hexadecimal) and

Real • Character constant :

– Single character constant– String constant– Backslash character constant

Page 7: Programming Concepts and C Language

I semester BE, SJCE Mysore. 7

• Variables– Data name used to store data value

– May take different values at different times during execution

– Chosen by the programmer

– Letters, digits and ‘_’ allowed

• Data Types – Primary data types

– User defined data type

– Derived data type (array, function, structure,..)

– Empty data set

Page 8: Programming Concepts and C Language

I semester BE, SJCE Mysore. 8

• Primary Data Type

– int, float, char, double.

– Extended data type – e.g., long int, short int,…

Type Size (bytes) Range

char or signed char 8 -128 to 127

unsigned char 8 0 to 256

int or signed int 16 -32678 to 32767

unsigned int 16 0 to 65535

short int or signed short int 8 -128 to 127

unsigned short int 8 0 to 255

long int or signed long int 32 -2147483648 to 1247483647

unsigned long int 32 0 to 4294967295

float 32 3.4 E –38 to 3.4 E + 38

double 64 1.7 E –308 to 1.7 E + 308

long double 80 3.4 E –4832 to 1.1 E +4932

Page 9: Programming Concepts and C Language

I semester BE, SJCE Mysore. 9

• Declaration of variables

– General form:Data_type v1,v2,v3,… vn;

– E.g., int base, height ;

float area ;

– Data type keywords-

Char or signed char, unsigned char, signed int or int, unsigned int or unsigned, short int or short or signed short int, long int or signed long int or long, float, double, long double

Page 10: Programming Concepts and C Language

I semester BE, SJCE Mysore. 10

• User defined data type

• Type definition– Define an identifier that would represent an existing data type

– This user defined data type can be used to declare variables

– General Form : typedef type identifier ;• E.g., typedef float marks ;

• marks physics, maths ;

• enum– General form : enum identifier {value1, value2,…. ValueN};

– Variables can be declared as, enum identifier v1,v2,…vN :

– Enumerated variables v1,v2,..vN can have one of the values of value1,value2,..valueN

• E.g., enum flavor {vanilla, pista, chocolate};

• enum flavor icecream, milkshake ;

Page 11: Programming Concepts and C Language

I semester BE, SJCE Mysore. 11

• Storage class– Auto

– Static

– Extern

– Register

• Assigning values to variables– Var_name = constant ;

– C converts type of RHS to type of LHS during assigning.

– Assign a value during declaration also allowed• E.g., int base =10, height = 20 ;

• float marks = 45.50 ;

– Multiple assign operators also allowed.• E.g., a = b = c = 0;

Page 12: Programming Concepts and C Language

I semester BE, SJCE Mysore. 12

• Declaring a variable as constant– const int no_student = 60

• Declaring a variable as volatile– Volatile int date ;

• var may be both volatile and constant– volatile constant int location ;

• Overflow and underflow of data– Value too big or too small for the datatype to hold.

• Declaring Symbolic constants– Constant values assigned to these names at the beginning of the

program– Values automatically substituted at the appropriate places– Defined as-#define NO_STUDENTS 50#define PI 3.1415

Page 13: Programming Concepts and C Language

I semester BE, SJCE Mysore. 13

Operators and Expressions• Operator• Symbol that tells the computer to perform certain

manipulations• Manipulate data and variables• Part of logical expression• Different types of Operators• Arithmetic operators

– + - / * %– Integer arithmetic– Real arithmetic

• Relational operators– < <= > >= == !=– Simple relational expression (only one relational operator)– Evaluates to true ( greater than 0) or false (0)– E.g., a+b >= c-d

Page 14: Programming Concepts and C Language

I semester BE, SJCE Mysore. 14

• Logical operators– && (AND) || (OR) ! (NOT)

– && and || used when more than one condition is to be tested

– Evaluates to 0 or 1

– Truth table

Operand 1 Operand 2 Op1 && op2 Op1 || op2 ! op1

Non-zero Non-zero 1 1 0

Non-zero 0 0 1 0

0 Non-zero 0 0 1

0 0 0 0 1

e.g., - 10 > 5 && !(10 < 9) || 3 <= 4

if(marks >= 60 && marks <= 70) printf(“first class”);

Page 15: Programming Concepts and C Language

I semester BE, SJCE Mysore. 15

• Assignment operator– =

– Short hand assignment operators

– sum = sum + 10 ; can be written as

– sum += 10;

– Similarly we have

– -=, *=, %=, /=,

• Increment and Decrement operators– ++ and – adds and subtracts one from operand

– E.g x++ and ++x will add one to x

– Prefix will increment or decrement operation before obtaining the value of the operand for use in the expression, ie., increment / decrement is done first then assigns the value to RHS.

Page 16: Programming Concepts and C Language

I semester BE, SJCE Mysore. 16

• Conditional operator– Ternary operator pair ? :

– exp1 ? exp2 : exp3

– exp1 evaluated first , if true then exp2 is evaluated else exp3 is evaluated

– E.g.,main()

{

int a,b ,x,y;

a = 10;

b = 20;

x = (a>b) ? (a+b) : (b+5) ; /* x=25*/

y = (a<=b) ? (a+5) : (b+5) ; /* y=15*/

}

Page 17: Programming Concepts and C Language

I semester BE, SJCE Mysore. 17

• Bitwise Operators– Used for

• Testing• Setting• Shifting

– char or int data types only– Operations are applied to individual bits of the operand– Same truth table as logical operators.– Bitwise AND (&)– Bitwise OR (| )– Bitwise NOT (~)– Bitwise EXOR (^)

• E.g., x= 13 ; 0000 0000 0000 1101• y= 25; 0000 0000 0001 1001• x & y = 0000 0000 0000 1001 = 9• x | y = 0000 0000 0001 1101 = 29• x ^ y = 0000 0000 0001 0100 = 20• ~x = 1111 1111 1111 0010

– Bitwise left shift op << no_of bits_to_shift– Bitwise right shift op >> no_of_bits_to_shift

Page 18: Programming Concepts and C Language

I semester BE, SJCE Mysore. 18

• Special operators– Comma ,

• To link related expressions together

• Evaluated from left to right

• The value of the right most expression is the value of the combined expression

• E.g., z = (x=10, y=5, x+y) ;

• Z will be 15

• Can be used if for loops

– Sizeof( ) operator– Compile time operator

– Returns number of byte the operand occupies

– Operand may be variable , m = sizeof(sum);

– constant , m = sizeof(235L);

– data type m= sizeof(long int);

Page 19: Programming Concepts and C Language

I semester BE, SJCE Mysore. 19

• Expressions– Combination of variables, constants and operators arranged as per

the syntax of the language– Precedence of Arithmetic Operators– Left to right evaluation

• High priority * / %• Low priority + -

– E.g., x = 9 – 12/3 + 3 * 2 –1 – First pass (high priority operators are applied)– x = 9 - 4 + 6 –1 – second pass (low priority operators are applied)– x = 10

• Order of evaluation can be changed using parenthesis• E.g., x = 9 – 12 / (3 + 3) * (2 – 1 )

• Parenthesis gets highest priority :• x = 9 – 12 / 6 * 1• 2nd pass x = 9 – 2 • 3rd pass x = 7

Page 20: Programming Concepts and C Language

I semester BE, SJCE Mysore. 20

• Type conversion in Expressions– If constants and variables are of mixed type they are converted to

the same type

– Compiler converts all operands up to the type of the largest operand – type promotion.

– All conversions are done operation by operation.

– The final result converted to the operand on the left of the assignment operator

– During final assignment if –• Float is assigned to int : truncation of fractional part

• Double to float : causes rounding off of digits

• Long int to int : higher order bits are dropped.

– To force a type conversion – casting a value• E.g., b = (double) sum / m;

• a = (int) a + b ;

Page 21: Programming Concepts and C Language

I semester BE, SJCE Mysore. 21

• Precedence of Operators.– Highest priority to lowest priority -

• ( ) [ ] -> .• ! ~ ++ -- - (type) * & sizeof()• * / %• + -• << >>• < <= > >= • == !=• &• ^• |• &&• ||• ?:• += -= *= %= != &= <<= >>=• ,

– In case of &&, if 1st operand is zero the 2nd operand is not evaluated– In case of || if the first operand is 1 the 2nd operand is not evaluated

Page 22: Programming Concepts and C Language

I semester BE, SJCE Mysore. 22

• Mathematical functions– C compiler support basic math functions like cos, sin, sqrt,..

– #include<math.h>

• Functions-– log(x) , acos(x), asin(x), atan(x), cos(x), sin(x), log10(x),

pow(x,y), sqrt(x), csoh(x), sinh(x), tann(x), ceil(x), floor(x), exp(x), fabs(x) , fmad(x,y)

• Redundant parenthesis do not cause errors or slow down the execution of an expression

• Use parenthesis to clarify the exact order of evaluation

Page 23: Programming Concepts and C Language

I semester BE, SJCE Mysore. 23

Decision making and Branching

• To change the order of execution based on certain conditions or repeat a group a statements until certain specified conditions are met

• ANSI C has the following categories of statements– Selection – if, switch

– Iteration – for, do, while

– Jump – continue, break, goto, return

– Label – case, default, (goto) label statement

– Expression – valid expression

– Block – { … } (also called compound statements)

Page 24: Programming Concepts and C Language

I semester BE, SJCE Mysore. 24

• if statement

• 2 way decision statement– simple if statement

if(expression)

{

statement block ;

}

– if .. else statementif(exp)

{

st block 1 ;

}

else

{

St block2;

}

Page 25: Programming Concepts and C Language

I semester BE, SJCE Mysore. 25

• nested if .. else statementif(cond1)

{

if(cond2)

{

st 1;

}

else

{

st 2;

}

}

else

{

st 3;

}

Page 26: Programming Concepts and C Language

I semester BE, SJCE Mysore. 26

• if .. else .. if ladder if(cond1)

st 1;

else if(cond2)

st 2;

else if(cond3)

st 3;

.

.

else if(cond n)

st n ;

else

default st;

Page 27: Programming Concepts and C Language

I semester BE, SJCE Mysore. 27

• switch– Multiple branch selection statement

– Tests the value of an expression against a list of integer or char constants

– When a match is found, then statement associated with that constant is executed.

switch(exp)

{

case const1 : st seq ;

break ;

case const2 : st seq ;

break ;

:

:

default : st seq ;

}

Page 28: Programming Concepts and C Language

I semester BE, SJCE Mysore. 28

• goto statement

• Unconditional branch goto label ;

:

:

label :

• Programs become unreadable

• Label can be before (backward looping) or after (jumping) a goto

• E.g., x=1; /* to print 1 to 100 */

loop1 : printf(“%d”,x);

x++;

if(x<100) goto loop1;

Page 29: Programming Concepts and C Language

I semester BE, SJCE Mysore. 29

Looping

• C supports three loop constructs– for

– while

– do .. while

• The while loop keeps repeating an action until an associated test returns false. This is useful where the programmer does not know in advance how many times the loop will be traversed.

• The do while loops is similar, but the test occurs after the loop body is executed. This ensures that the loop body is run at least once.

• The for loop is frequently used, usually where the loop will be traversed a fixed number of times. It is very flexible, and novice programmers should take care not to abuse the power it offers.

Page 30: Programming Concepts and C Language

I semester BE, SJCE Mysore. 30

• for syntax:for (<exp1>; <exp2>; <exp3>) statement;

<exp1>: initialization, evaluated once.

<exp2>: loop control, zero value means exit.

<exp3>: counter, evaluated at end of body. 

• Design issues:

• Expressions can be statements or statement sequences (separated by commas).

• No explicit loop var.

• Everything can be changed in the loop.

• Pretest.

Page 31: Programming Concepts and C Language

I semester BE, SJCE Mysore. 31

• Example to calculate total of an arraymain( ){ float total = 0.0; int i; for(i = 0; i < count; i++) total += array[i]; }

Page 32: Programming Concepts and C Language

I semester BE, SJCE Mysore. 32

• The while has the form:   while (expression) statement ;

• For example:   int x=3;   main( ) { while (x>0) { printf("x=%d n",x); x--; } }

• ...outputs: •   x=3 x=2 x=1 ...to the screen.

Page 33: Programming Concepts and C Language

I semester BE, SJCE Mysore. 33

• C's do-while statement has the form:   do statement; while (expression);

• For example: int x=3; main( ) { do { printf("x=%d n",x--); } while (x>0); }

• ..outputs:- •   x=3 x=2 x=1 • NOTE: The postfix x-- operator which uses the current

value of x while printing and then decrements x.

Page 34: Programming Concepts and C Language

I semester BE, SJCE Mysore. 34

• break and continue

• C provides two commands to control how we loop: – break -- exit form loop or switch.

– continue -- skip 1 iteration of loop.

• Consider the following example where we read in integer values and process them according to the following conditions. If the value we have read is negative, we wish to print an error message and abandon the loop. If the value read is great than 100, we wish to ignore it and continue to the next value in the data. If the value is zero, we wish to terminate the loop.

•   program next slide

Page 35: Programming Concepts and C Language

I semester BE, SJCE Mysore. 35

while (scanf( ``%d'', &value ) == 1 && value != 0) {   if (value < 0) { printf(``Illegal value n''); break; /* Abandon the loop */ }   if (value > 100) { printf(``Invalid value n''); continue; /* Skip to start loop again */ }   /* Process the value read */ /* guaranteed between 1 and 100 */ ....;   ....; } /* end while value != 0 */

Page 36: Programming Concepts and C Language

I semester BE, SJCE Mysore. 36

Input and Output

• To use these facilities, your program must include these definitions by adding the line This is done by adding the line

• #include <stdio.h> near the start of the program file.

• Character Input / Output

• This is the lowest level of input and output. It provides very precise control, but is usually too fiddly to be useful. Most computers perform buffering of input and output. This means that they'll not start reading any input until the return key is pressed, and they'll not print characters on the terminal until there is a whole line to be printed.

• getchar

• putchar

Page 37: Programming Concepts and C Language

I semester BE, SJCE Mysore. 37

• getchar

• As an example, here is a program to count the number of characters read until an EOF is encountered. EOF can be generated by typing Control - d.

#include <stdio.h> main( ) { int ch, i = 0; while((ch = getchar()) != EOF) i ++; printf("%d\n", i); }

Page 38: Programming Concepts and C Language

I semester BE, SJCE Mysore. 38

• putchar

• putchar puts its character argument on the standard output (usually the screen).

• The following example program converts any typed input into capital letters. To do this it applies the function toupper from the character conversion library ctype.h to each character in turn.

#include <ctype.h> /* For definition of toupper */ #include <stdio.h> /* For definition of getchar, putchar,

EOF */ main( ) { int ch; while((ch = getchar()) != EOF) putchar(toupper(ch)) }

Page 39: Programming Concepts and C Language

I semester BE, SJCE Mysore. 39

• Formatted Input / Output– printf

– Scanf

• The printf function is defined as follows: int printf(char *format, arg list ...) -- prints to stdout the list of arguments according specified format string. Returns number of characters printed.

• The format string has 2 types of object:

• ordinary characters -- these are copied to output.

• conversion specifications -- denoted by % and listed in Table 

Page 40: Programming Concepts and C Language

I semester BE, SJCE Mysore. 40

Format Spec

(%)Type Result

c char single character

i,d int decimal number

o int octal number

x,X int hexadecimal number

lower/uppercase notationu int unsigned int

s char * print string

terminated by  0

f double/float

format -m.ddd...

e,E " Scientific Format

-1.23e002

g,G " e or f whichever

is most compact

% - print % character

Page 41: Programming Concepts and C Language

I semester BE, SJCE Mysore. 41

• Between % and format char we can put: • - (minus sign)

• -- left justify. • integer number

• -- field width. • m.d

• -- m = field width, d = precision of number of digits after decimal point or number of chars from a string.

–So:           printf("%-2.3f n",17.23478); The output on the screen is:           17.235 and:           printf("VAT=17.5%% n"); ...outputs:           VAT=17.5%

Page 42: Programming Concepts and C Language

I semester BE, SJCE Mysore. 42

• scanf •    int scanf(char *format, args....) -- reads from stdin and puts

input in address of variables specified in args list. Returns number of chars read.

• Format control string similar to printf

• Note: The ADDRESS of variable or a pointer to one is required by scanf.

   scanf(``%d'',&i);

• We can just give the name of an array or string to scanf since this corresponds to the start address of the array/string.

 char string[80]; scanf(``%s'',string);

Page 43: Programming Concepts and C Language

I semester BE, SJCE Mysore. 43

• Whole Lines of Input and Output

• Where we are not too interested in the format of our data, or perhaps we cannot predict its format in advance, we can read and write whole lines as character strings. This approach allows us to read in a line of input, and then use various string handling functions to analyse it at our leisure. – gets

– puts

Page 44: Programming Concepts and C Language

I semester BE, SJCE Mysore. 44

• gets

• gets reads a whole line of input into a string until a newline or EOF is encountered. It is critical to ensure that the string is large enough to hold any expected input lines.

• When all input is finished, NULL as defined in stdio.h is returned.

• puts

• puts writes a string to the output, and follows it with a newline character.

• Example: Program which uses gets and puts to double space typed input.

Page 45: Programming Concepts and C Language

I semester BE, SJCE Mysore. 45

#include <stdio.h> main( ) {

char line[256]; /* Define string sufficiently large to store a line of input */ while(gets(line) != NULL) /* Read line */

{ puts(line); /* Print line */ printf("\n"); /* Print blank line */ } }

Note that putchar, printf and puts can be freely used together. So can getchar, scanf and gets.

Page 46: Programming Concepts and C Language

I semester BE, SJCE Mysore. 46

Arrays• An array is a collection of variables of the same type.

Individual array elements are identified by an integer index.

• In C the index begins at zero and is always written inside square brackets.

• We have already met single dimensioned arrays which are declared like this int results[20];

• Arrays can have more dimensions, in which case they might be declared as int results_2d[20][5]; int results_3d[20][5][3];

• Each index has its own set of square brackets.

Page 47: Programming Concepts and C Language

I semester BE, SJCE Mysore. 47

• As an example, here is a simple program to add up all of the integers in a single dimensioned array.

main( ) { int i; int total = 0; for(i = 0; i < size; i++) total += array[i]; printf(“%d”,total); }

Page 48: Programming Concepts and C Language

I semester BE, SJCE Mysore. 48

Strings

• In C Strings are defined as arrays of characters. For example, the following defines a string of 50 characters:

•   char name[50]; • C has no string handling facilities built in and so the

following are all illegal:

•  • char firstname[50],lastname[50],fullname[100];

 

• firstname= "Arnold"; /* Illegal */ lastname= "Schwarznegger"; /* Illegal */ fullname= "Mr"+firstname +lastname; /* Illegal

*/

Page 49: Programming Concepts and C Language

I semester BE, SJCE Mysore. 49

• However, there is a special library of string handling routines which we will come across later.

• To print a string we use printf with a special %s control character:

•    printf(“s”,name); • NOTE: We just need to give the name of the string. • In order to allow variable length strings the \0 character is used

to indicate the end of a string. • So we if we have a string, char NAME[50]; and we store the

“DAVE” in it its contents will look like: •

Page 50: Programming Concepts and C Language

I semester BE, SJCE Mysore. 50

• String handling functions– strcat(str1,str2) – concatenates two strings

– strcmp(str1,str2) – compares two strings

– strcpy(str1,str2) – copies str2 to str1

– strlen(str) – returns length of str

• Other string functions like-– strlwr( ), strupr( ), strncat( ), stricmp( ),.. are also defined in

string.h

Page 51: Programming Concepts and C Language

I semester BE, SJCE Mysore. 51

Functions

• C provides functions which are again similar most languages. One difference is that C regards main( ) as function. Also unlike some languages, such as Pascal, C does not have procedures -- it uses functions to service both requirements.

• The form of a function:   returntype fn_name(1, parameterdef2, …)   

{   localvariables   functioncode  

}

Page 52: Programming Concepts and C Language

I semester BE, SJCE Mysore. 52

• Let us look at an example to find the average of two integers:

 float findaverage(float a, float b) { float average;   average=(a+b)/2; return(average); }  

• We would call the function as follows:   main() { float a=5,b=15,result;   result=findaverage(a,b); printf("average=%f n",result); }  

• Note: The return statement passes the result back to the main program.

Page 53: Programming Concepts and C Language

I semester BE, SJCE Mysore. 53

• void functions • The void function provide a way of emulating PASCAL

type procedures. • If you do not want to return a value you must use the

return type void and miss out the return statement:  void squares( ) { int loop;   for (loop=1;loop<10;loop++); printf("%d n",loop*loop); }   main( )   { squares( ); }

• NOTE: We must have ( ) even for no parameters unlike some languages.

Page 54: Programming Concepts and C Language

I semester BE, SJCE Mysore. 54

• Functions and Arrays

• Single dimensional arrays can be passed to functions as follows:-

  float findaverage(int size,float list[])   { int i; float sum=0.0;   for (i=0;i<size;i++) sum+=list[i]; return(sum/size); }

• Here the declaration  float list[] tells C that list is an array of float. Note we do not specify the dimension of the array when it is a parameter of a function.

• Multi-dimensional arrays can be passed to functions as follows:

Page 55: Programming Concepts and C Language

I semester BE, SJCE Mysore. 55

•  void printtable(int xsize,int ysize,    float table[][5])  

• { • int x,y;   • for (x=0;x<xsize;x++) • { • for (y=0;y<ysize;y++) • printf(" t%f",table[x][y]); • printf(" n");• }• } • Here float table[][5] tells C that table is an array of dimension N 5 of

float. Note we must specify the second (and subsequent) dimension of the array BUT not the first dimension.

Page 56: Programming Concepts and C Language

I semester BE, SJCE Mysore. 56

•Function Prototyping •Before you use a function C must have knowledge about the type it returns and the parameter types the function expects. •The ANSI standard of C introduced a new (better) way of doing this than previous versions of C. (Note: All new versions of C now adhere to the ANSI standard.) •The importance of prototyping is twofold.

•It allows the C compiler to check the syntax of function calls. •It makes for more structured and therefore easier to read code.

•It is usual (and therefore good) practice to prototype all functions at the start of the program, although this is not strictly necessary. •To declare a function prototype simply state the type the function returns, the function name and in brackets list the type of parameters in the order they appear in the function definition.

Page 57: Programming Concepts and C Language

I semester BE, SJCE Mysore. 57

Structures

• A structure is a collection of variables under a single name. These variables can be of different types, and each has a name which is used to select it from the structure. A structure is a convenient way of grouping several pieces of related information together.

• A structure can be defined as a new named type, thus extending the number of available types. It can use other structures, arrays or pointers as some of its members, though this can get complicated unless you are careful.

Page 58: Programming Concepts and C Language

I semester BE, SJCE Mysore. 58

• For example:   struct gun { char name[50]; int magazinesize; float calibre; };  

struct gun arnies;

• defines a new structure gun and makes arnies an instance of it.

Page 59: Programming Concepts and C Language

I semester BE, SJCE Mysore. 59

• Variables can also be declared between the } and ; of a struct declaration, i.e.:

  struct gun { char name[50]; int magazinesize; float calibre; } arnies;

• struct's can be pre-initialised at declaration:

  struct gun arnies={"Uzi",30,7};

• which gives arnie a 7mm. Uzi with 30 rounds of ammunition.

• To access a member (or field) of a struct, C provides the . operator. For example, to give arnie more rounds of ammunition:

   arnies.magazineSize=100;

Page 60: Programming Concepts and C Language

I semester BE, SJCE Mysore. 60

• Defining New Data Types

• typedef can also be used with structures. The following creates a new type agun which is of type struct gun and can be initialised as usual:

  typedef struct gun { char name[50]; int magazinesize; float calibre; } agun;  

agun arnies={"Uzi",30,7};

• agun is the new data type. arnies is a variable of type agun

which is a structure.

Page 61: Programming Concepts and C Language

I semester BE, SJCE Mysore. 61

• C also allows arrays of structures:   typedef struct gun { char name[50]; int magazinesize; float calibre; } agun;   agun arniesguns[1000];

• This gives arniesguns a 1000 guns. This may be used in the following way:

          arniesguns[50].calibre=100;

• gives Arnie's gun number 50 a calibre of 100mm, and:           itscalibre=arniesguns[0].calibre;

• assigns the calibre of Arnie's first gun to itscalibre.

Page 62: Programming Concepts and C Language

I semester BE, SJCE Mysore. 62

Unions

• A union is a variable which may hold (at different times) objects of different sizes and types. C uses the union statement to create unions, for example:

 union number { short shortnumber; long longnumber; double floatnumber; } anumber

• defines a union called number and an instance of it called anumber. number is a union tag and acts in the same way as a tag for a structure.

• Members can be accessed in the following way:           printf("%ld n",anumber.longnumber);

• This clearly displays the value of longnumber.

Page 63: Programming Concepts and C Language

I semester BE, SJCE Mysore. 63

• When the C compiler is allocating memory for unions it will always reserve enough room for the largest member (in the above example this is 8 bytes for the double).

• In order that the program can keep track of the type of union variable being used at a given time it is common to have a structure (with union embedded in it) and a variable which flags the union type:

• An example is:

Page 64: Programming Concepts and C Language

I semester BE, SJCE Mysore. 64

typedef struct { int maxpassengers; } jet;   typedef struct { int liftcapacity; } helicopter;   typedef struct { int maxpayload; } cargoplane;   typedef union { jet jetu; helicopter helicopteru; cargoplane cargoplaneu; } aircraft;   typedef struct { aircrafttype kind; int speed; aircraft description; } an_aircraft;

Page 65: Programming Concepts and C Language

I semester BE, SJCE Mysore. 65

• This example defines a base union aircraft which may either be jet, helicopter, or cargoplane.

• In the an_aircraft structure there is a kind member which indicates which structure is being held at the time.

Page 66: Programming Concepts and C Language

I semester BE, SJCE Mysore. 66

Pointers

• A pointer is a variable which contains the address in memory of another variable. We can have a pointer to any variable type.

• The unary or monadic operator & gives the “address of a variable”.

• The indirection or dereference operator * gives the “contents of an object pointed to by a pointer”.

• To declare a pointer to a variable do:    int *pointer;

• NOTE: We must associate a pointer to a particular type: You can't assign the address of a short int to a long int, for instance.

Page 67: Programming Concepts and C Language

I semester BE, SJCE Mysore. 67

• Consider the effect of the following code:    int x = 1, y = 2; int *ip;   ip = &x;   y = *ip;   x = ip;   *ip = 3;

• It is worth considering what is going on at the machine level in memory to fully understand how pointer work. Consider Fig(next slide). Assume for the sake of this discussion that variable x resides at memory location 100, y at 200 and ip at 1000. Note A pointer is a variable and thus its values need to be stored somewhere. It is the nature of the pointers value that is new

Page 68: Programming Concepts and C Language

I semester BE, SJCE Mysore. 68

Fig. Pointer, Variables and Memory Now the assignments x = 1 and y = 2 obviously load these values into the variables. ip is declared to be a pointer to an integer and is assigned to the address of x (&x). So ip gets loaded with the value 100.

Page 69: Programming Concepts and C Language

I semester BE, SJCE Mysore. 69

•Next y gets assigned to the contents of ip. In this example ip currently points to memory location 100 -- the location of x. So y gets assigned to the values of x -- which is 1.

•We have already seen that C is not too fussy about assigning values of different type. Thus it is perfectly legal (although not all that common) to assign the current value of ip to x. The value of ip at this instant is 100.

•Finally we can assign a value to the contents of a pointer (*ip).

Page 70: Programming Concepts and C Language

I semester BE, SJCE Mysore. 70

• IMPORTANT: When a pointer is declared it does not point anywhere. You must set it to point somewhere before you use it.

• So ...    int *ip;   *ip = 100;

• will generate an error (program crash!!).

• The correct use is:    int *ip; int x;   ip = &x; *ip = 100;

• We can do integer arithmetic on a pointer:

Page 71: Programming Concepts and C Language

I semester BE, SJCE Mysore. 71

float *flp, *flq; *flp = *flp + 10; ++*flp;   (*flp)++;   flq = flp;

• NOTE: A pointer to any variable type is an address in memory -- which is an integer address. A pointer is definitely NOT an integer.

• The reason we associate a pointer to a data type is so that it knows how many bytes the data is stored in. When we increment a pointer we increase the pointer by one ``block'' memory.

• So for a character pointer ++ch_ptr adds 1 byte to the address.

• For an integer or float ++ip or ++flp adds 4 bytes to the address

Page 72: Programming Concepts and C Language

I semester BE, SJCE Mysore. 72

• Consider a float variable (fl) and a pointer to a float (flp) as shown in Fig.

• Fig. Pointer Arithmetic Assume that flp points to fl then if we increment the pointer ( ++flp) it moves to the position shown 4 bytes on. If on the other hand we added 2 to the pointer then it moves 2 float positions i.e 8 bytes as shown in the Figure.

Page 73: Programming Concepts and C Language

I semester BE, SJCE Mysore. 73

• Pointer and Functions • Let us now examine the close relationship between pointers

and C's other major parts. We will start with functions. • When C passes arguments to functions it passes them by

value. • There are many cases when we may want to alter a passed

argument in the function and receive the new value back once to function has finished. Other languages do this (e.g. var parameters in PASCAL). C uses pointers explicitly to do this. Other languages mask the fact that pointers also underpin the implementation of this.

• The best way to study this is to look at an example where we must be able to receive changed parameters.

• Let us try and write a function to swap variables around?

Page 74: Programming Concepts and C Language

I semester BE, SJCE Mysore. 74

• The usual function call:

    swap(a, b)   WON'T WORK.

• Pointers provide the solution: Pass the address of the variables to the functions and access address of function.

• Thus our function call in our program would look like this:

    swap(&a, &b)

• The Code to swap is fairly straightforward: •     void swap(int *px, int *py)      

{ int temp;   temp = *px; /* contents of pointer */   *px = *py; *py = temp; }

Page 75: Programming Concepts and C Language

I semester BE, SJCE Mysore. 75

• We can return pointer from functions. A common example is when passing back structures. e.g.:

typedef struct {float x,y,z;} COORD;   main( )     {  COORD p1, *coord_fn(); /* declare fn to return ptr of COORD type */   .... p1 = *coord_fn(...); /* assign contents of address returned */ .... }    COORD *coord_fn(...)     {  COORD p;   ..... p = ....; /* assign structure values */   return &p; /* return address of p */ }

• Here we return a pointer whose contents are immediately unwrapped into a variable. We must do this straight away as the variable we pointed to was local to a function that has now finished. This means that the address space is free and can be overwritten. It will not have been overwritten straight after the function ha squit though so this is perfectly safe.

Page 76: Programming Concepts and C Language

I semester BE, SJCE Mysore. 76

• Pointers and Arrays

• Pointers and arrays are very closely linked in C.

• Hint: think of array elements arranged in consecutive memory locations.

• Consider the following:  int a[10], x; int *pa;   pa = &a[0]; /* pa pointer to address of a[0] */   x = *pa; /* x = contents of pa (a[0] in this case) */

Page 77: Programming Concepts and C Language

I semester BE, SJCE Mysore. 77

• To get somewhere in the array (Fig) using a pointer we could do:

   pa + i a[i]

• WARNING: There is no bound checking of arrays and pointers so you can easily go beyond array memory and overwrite other things.

• C however is much more subtle in its link between arrays and pointers.

• For example we can just type

   pa = a;

• instead of    pa = &a[0] and    a[i] can be written as *(a + i).

i.e. &a[i] a + i.

Page 78: Programming Concepts and C Language

I semester BE, SJCE Mysore. 78

We also express pointer addressing like this:

  pa[i] = *(pa + i).

However pointers and arrays are different: •A pointer is a variable. We can do pa = a and pa++. •An Array is not a variable. a = pa and a++ ARE ILLEGAL.

Page 79: Programming Concepts and C Language

I semester BE, SJCE Mysore. 79

Files

• C File Handling - File Pointers

• C communicates with files using a new datatype called a file pointer. This type is defined within stdio.h, and written as FILE *. A file pointer called output_file is declared in a statement like

FILE *output_file;

Page 80: Programming Concepts and C Language

I semester BE, SJCE Mysore. 80

• Opening a file pointer using fopen

• Your program must open a file before it can access it. This is done using the fopen function, which returns the required file pointer. If the file cannot be opened for any reason then the value NULL will be returned. You will usually use fopen as follows

if ((output_file = fopen("output_file", "w")) == NULL) fprintf(stderr, "Cannot open %s\n", "output_file");

• fopen takes two arguments, both are strings, the first is the name of the file to be opened, the second is an access

character, which is usually one of:

Page 81: Programming Concepts and C Language

I semester BE, SJCE Mysore. 81

• Closing a file using fclose

• The fclose command can be used to disconnect a file pointer from a file. This is usually done so that the pointer can be used to access a different file. Systems have a limit on the number of files which can be open simultaneously, so it is a good idea to close a file when you have finished using it.

• This would be done using a statement like fclose(output_file);

• If files are still open when a program exits, the system will close them for you. However it is usually better to close

the files properly.

Page 82: Programming Concepts and C Language

I semester BE, SJCE Mysore. 82

• Input and Output using file pointers

• Having opened a file pointer, you will wish to use it for either input or output. C supplies a set of functions to allow you to do this. All are very similar to input and

output functions that you have already met.

Page 83: Programming Concepts and C Language

I semester BE, SJCE Mysore. 83

• Character Input and Output with Files

• This is done using equivalents of getchar and putchar which are called getc and putc. Each takes an extra argument, which identifies the file pointer to be used for

input or output.

•Formatted Input Output with File Pointers

•Similarly there are equivalents to the functions printf and scanf which read or write data to files. These are called fprintf and fscanf. You have already seen fprintf being used to write data to stderr.

•The functions are used in the same way, except that the fprintf and fscanf take the file pointer as an additional first argument.

Page 84: Programming Concepts and C Language

I semester BE, SJCE Mysore. 84

• Formatted Input Output with Strings

• These are the third set of the printf and scanf families. They are called sprintf and sscanf.

• sprintf

• puts formatted data into a string which must have sufficient space allocated to hold it. This can be done by declaring it as an array of char. The data is formatted according to a control string of the same form as that for printf.

• sscanf

• takes data from a string and stores it in other variables as specified by the control string. This is done in the same way that scanf reads input data into variables. sscanf is very useful for converting strings into numeric v values.

Page 85: Programming Concepts and C Language

I semester BE, SJCE Mysore. 85

• Whole Line Input and Output using File Pointers

• Predictably, equivalents to gets and puts exist called fgets and fputs. The programmer should be careful in using them, since they are incompatible with gets and puts. gets requires the programmer to specify the maximum number of characters to be read. fgets and fputs retain the trailing newline character on the line they read or write, wheras gets and puts discard the newline.

• When transferring data from files to standard input / output channels, the simplest way to avoid incompatibility with the newline is to use fgets and fputs for files and standard channels too.

• For Example, read a line from the keyboard using fgets(data_string, 80, stdin);

• and write a line to the screen using fputs(data_string, stdout);

Page 86: Programming Concepts and C Language

I semester BE, SJCE Mysore. 86

• EOF, The End of File Marker• EOF is a character which indicates the end of a

file. It is returned by read commands of the getc and scanf families when they try to read beyond the end of a file.

Page 87: Programming Concepts and C Language

I semester BE, SJCE Mysore. 87

Computer Concept • Basic functional unit of a digital computer

– Central Processing Unit (CPU)

– Arithmetic and Logical Unit (ALU)

• Control Unit (CU)

• Memory Unit

• Input Unit

• Output Unit

• Von Neumann model is shown in the next slide

• He introduced the stored program concept where the data and program are stored in same memory

• Modern computers are said to have van Neumann architecture

Page 88: Programming Concepts and C Language

I semester BE, SJCE Mysore. 88

Memory Unit

ALUInput Unit Output Unit

Control Unit

Von Neumann model

Page 89: Programming Concepts and C Language

I semester BE, SJCE Mysore. 89

• Control unit– Fetch and execute cycle

• Main memory – Used for temporary storage during computation

– Fast access

– Random access

– Moderate capacity

– Volatality

Page 90: Programming Concepts and C Language

I semester BE, SJCE Mysore. 90

• Storage devices– Primary

• RAM

• ROM

– Secondary• Magnetic tapes

• Magnetic drums

• Hard disk

• Floppy disk

• CD-ROMs

• RAM– Both read and write

– Also called Dynamic RAM (DRAM)

Page 91: Programming Concepts and C Language

I semester BE, SJCE Mysore. 91

• ROM– Only read, no write

– Contents are determined when chips are manufactured

– Non volatile

– Important ROM chip – BIOS (Basic Input Output System)• Performs Power On Self Test (POST)

• Finds OS and loads it (boots it)

• Ensures software programs have easy access to computer’s specific features.

– PROM (programmable ROM)

– EPROM (erasable programmable ROM)

– EEPROM (electrically erasable programmable ROM)

Page 92: Programming Concepts and C Language

I semester BE, SJCE Mysore. 92

• Secondary storage – Non volatile

– Long term storage of programs

– Can be removed from computer system and stored separately

– Greater storage capacity for lower cost per bit than main memory

– But access is over a thousand times slower than for item stored in main memory

– Therefore programs are transferred to main memory before processing

Page 93: Programming Concepts and C Language

I semester BE, SJCE Mysore. 93

• Hard disk– Multiple platters

– Held together by a spindle

– Each platter has a read/write head

– Each platter is divided into tracks and sectors

– Platters spin at a speed of 3,600 to 7,200 rpm

– Read/write head moves from hub to edge upto 50 times a second

– Sector has fixed number of bytes – 256 or 512 bytes

• Floppy disk– Similar to hard disk, but single platter

– Slower spinning speed

– Less capacity

– Slower access time

Page 94: Programming Concepts and C Language

I semester BE, SJCE Mysore. 94

• CD– CDs are coated with aluminum to reflect light and imprinted with

a series of pits and flat areas.

– Reading these pits or flats denote 0's or 1's, the building blocks of binary language which the computer uses.

– A thin laser beam reads the pits or the flats while the disk is spinning.

– Light reflects from the flat surfaces, not the pits.

– So a photo detector reads what is reflected and sends the 0's and 1's to the CPU.

– This is simply binary code, and is how the CPU interprets data.

Page 95: Programming Concepts and C Language

I semester BE, SJCE Mysore. 95

• Input devices– Keyboard

– Mouse

– Scanner

• Keyboard– Sends the ASCII code of the key pressed to the computer

• Mouse– It is a transducer which coverts movement into voltage

To A/D converter

x,y variable resistors Push button

Mouse

Page 96: Programming Concepts and C Language

I semester BE, SJCE Mysore. 96

• Scanner– Used to digitize photographs

– Uses technique called dithering i.e., a process which separates the dots which form the image so that extra white space can be seen between the dots

– E.g., photoelectric scanners are used to read barcodes, recognize the marks and convert them to electrical signals which are sent to the computer for processing.

Page 97: Programming Concepts and C Language

I semester BE, SJCE Mysore. 97

• Output devices– Cathode Ray Tube (CRT)

– Printers

– Plotters

• CRT

Electron gunControl electrode

Focusing electrode

Deflection yolk

Phosphorous coated screen

Page 98: Programming Concepts and C Language

I semester BE, SJCE Mysore. 98

• Computer languages– Machine language– Assembly language– High level language

• Machine language– Consists of strings of 0 s and 1 s

• Assembly language– Uses mnemonic codes– An assembler is needed to translate assembly language to machine

language– E.g., for mnemonics – ADD, LOAD, MOV,…

• High level language– Hides internal details of computer operation– Easier to learn – Require less time to write– Better documentation– Easier maintenance, more user friendly– Easily portable,..

Page 99: Programming Concepts and C Language

I semester BE, SJCE Mysore. 99

• Some example of high level languages are-– COBOL, FORTRAN, BASIC, PASCAL, ADA, LISP, C, C++,

JAVA,…

• Compiler – is a program which translates source code of high level language into machine language called object program.

• Another software called – linker is often used to combine the object program with the subroutine calls.

• Interpreters – do not translate source codes as object codes for permanent storage, instead interpreter carries out the operation of each source program statement by converting into machine level form as and when needed during the processing of data

Page 100: Programming Concepts and C Language

I semester BE, SJCE Mysore. 100

• Computer software• System software

– Controlling general operation of the system– E.g., Operating System, Device Drivers, translators,…

• Application software– Developed for definite applications– E.g., application packages like payroll preparations, spread sheet,….

• Operating System– Layer between user and hardware– Functions of O.S.

• Program Loading• Operating System Macros• Control of peripherals• Data management• Concurrency• User friendly• Security• Processes and Interrupts,…

– E.g., DOS, UNIX, WINDOWS,…

Page 101: Programming Concepts and C Language

I semester BE, SJCE Mysore. 101

• Some DOS commands

• DIR – list directories

• COPY CON – create a file

• COPY – copy one file

• TYPE – display contents of file

• CLS – clears the screen

• DEL – deletes a file

• CD – change directory

• MD – make directory

• RD – remove directory

• PRINT – print file

Page 102: Programming Concepts and C Language

I semester BE, SJCE Mysore. 102

• Networking of computers– A network is a telecommunication and data transfer system that

allows a number of independent computers to communicate over a variety of media.

– A network makes it possible to share peripherals, files, programs, and computer capabilities.

– Computer network is the interconnection of various autonomous computers which may be quite far off geographically as to share the resources effectively.

– A network can be a local area network (LAN) , a metropolitan are network (MAN) , a wide area network (WAN).

– Interconnection of all these networks forms the Internet