Download pdf - C programming

Transcript
Page 1: C programming

C FOR ENGINEERS R.G.Salokhe

FOR OTHER BOOKS WRITTEN BY ME PLEASE VISIT http://www.geocities.com/arutacomp/ or mail me on [email protected] The books available are 1] AutoCAD 2007 – The third dimension 2] Visual Basic 6 – from bottom to top 3] MS-ACCESS Thank you. Rajendra Salokhe

Page 2: C programming

C FOR ENGINEERS R.G.Salokhe

The C language was created, designed and written by Dennis Ritchie in 1972 at Bell Laboratories. C was designed to run under UNIX operating system on the DEC, PDP11 computer. Features of C :- a) Portability :- The best feature for which C gained popularity is the portability of code. The C language programs could be run on variety of computers with a little or no change in the source code. Which means the C language code can be used under various operating systems. b) Efficiency :- The C language is efficient in two ways I) The source code is very compact ii) Memory Management through C is very efficient. c) Modularity :- C allows separately compiled modules which can be linked together. The programs can be written in well structured manner. C is a language of functions. Various modules are written as functions. d) Pointer Operations :- C is very powerful in pointer operations. Pointers can be set to various data types as well as to funtions, structures etc. Arrays can be manipulated with the help of pointers. e) Flexible level :- C programs can be written with the features of high level languages as well as that of low level languages. C thus fits in between the two. C is not a ‘strongly typed’ language. There are no bounds to number of array elements. f) Case Sensitivity :- C is case sensitive. Which means the upper case and lower case characters are treated differently in variable names, function names etc. ANSI C :- ANSI stands for American National Standard Institute. The ANSI set a standard for C language in 1990. This was for the various compiler developers to use this standard. However many compilers are not strictly adhering to the ANSI standard. Structure of C Programs :- Since C is a language of functions, let us understand what a function means; A function is an entity which accepts some input, processes the same and gives the output. The type of function is determined by its output. The function can be used as its output. >>> >>>

input Function output

Page 3: C programming

C FOR ENGINEERS R.G.Salokhe

4 2 Numeric Numeric Input Output 4 input to function gives 2 as output. The function 4 can be used as value 2. e.g. 6 X 4 = 12. Here 4 is used as 2. 30 SINE 1/2 degrees number Let us look at the structure of a C program; /*PROG1.C */ Comment # include < stdio.h > Header main ( ) Function Main { Body of Main starts ; Null statement } Main ( ) ends We have written the program name as comments. The comments, spaces, tabs, newline characters are ignored by the C Compiler. At this stage we will keep aside the discussion on header file. just remember that ‘ stdio ‘ stands for standard input output.

Page 4: C programming

C FOR ENGINEERS R.G.Salokhe

Every set of C programs should have one main ( ) function. This is called the driving function. The program execution starts at ‘ { ‘, the opening brace of the main function body and ends at the ‘ } ‘ closing brace. We have included a null statement, a statement which does not mean anything in the body of the main ( ) function. Every statement in C ends with a ‘ ; ‘ ( semicolon ). The above prgram will run but would not produce any results. Let us slightly modify the program; /* PROG2.C */ # include < stdio.h > main ( ) { printf ( "Hello friends! " ) ; } Output - Hello friends! printf ( ) is another function available in the C library and declared in the stdio.h file. Thus whichever functions we use, we have to include corresponding header files into our programs. /* PROG3.C */ # include < stdio.h > main ( ) { printf ( " Hello friends ! \ n " ) printf ( " How are you ? \ n " ) ; } Output - Hello friends! How are you? The \ ( backslash ) causes escape from the normal printing process and \n causes the computer to skip one line while printing. Other escape sequences are ; \b backspace \t tab

Page 5: C programming

C FOR ENGINEERS R.G.Salokhe

\f form feed \’ single quote \r carriage return \0 null C character set :- C uses the following character set; a) Alphabets upper case ( A to Z ) b) Alphabets lower case ( a to z ) c) Decimal digits ( 0 to 9 ) d) Other characters; comma ( , ), semicolon ( ; ), period ( . ) querry ( ? ), exclaimation ( ! ), colon ( : ), plus ( + ), minus ( - ), asterisk ( * ), slash ( / ), backslash ( \ ), vertical bar ( | ), single quote ( ‘ ), double quote ( “ ),tild ( ~ ) , right parantheses ( ( ), left paranthese ( ) ), right bracket ( [ ),left bracket ( ] ), right brace ( { ), left brace ( } ), right angle bracket ( < ), left angle bracket ( > ), equal sign ( = ), ampersand ( & ), percent sign ( % ), pound sign ( # ) caret ( ^ ), under score ( _ ). Variable Names :- As a very basic concept we can say that a variable is an entity whose value changes. We use a lot of variables in Algebra. When we say a = 5 ; a is a variable and we are assigning the value of 5 to a. Coming to a better concept a variable is the name assigned to the address of a cell in the memory.

Memory cell

Name a Address 2529 Value 5

When you say

Page 6: C programming

C FOR ENGINEERS R.G.Salokhe

a = 6 ; Then the value 5 vanishes and the value of 6 is put into the cell. a = a + 6 ; is a wrong algebric equation but it is a valid computer equation as it means add 6 to the present value of a and assign the resulting value to a. Thus a becomes 12. a + 5 = 6 ; / * wrong * / The above equation is wrong for the computer as you can not add anything to the name. We have used a as a variable name. We can use any name for the variable within the following rules. 1) The variable name can not have a space, comma or characters like ( #,?,&,$,!,| ) - why use funny characters? 2) The name uses underscore, alphabet and numeric characters only. e.g. _ total BASIC D_A etc. 3) The language reserved words or key words can not be used as variable names. e.g. double, int,auto etc. 4) The first character of name can not be a digit. The variable name can be 31 characters long. Data Types :- Larger the value, larger is the space required in memory to store the number. If you are using a variable whose value varies between 0 and 255 then there is no need to allocate more space in memory for storing this number. The data types are created for efficient use of the memory. How much memory is alloted for the various types depends on the machine. Character Data Types :-

Page 7: C programming

C FOR ENGINEERS R.G.Salokhe

The basic data types is the character variable. Character variable occupies 1 byte of the memory. 1 byte comprises of 8 bits and the maximum value of 8 bit binary number is 255. 1 byte = 8 bits 27 26 25 24 23 22 21 20

128+ 64 +32 +16 + 8 + 4 + 2 + 0 = 255 If the character is unsigned then it can store values from 0 to 255. In other words we can say that total values that can be stored in 8 bits is 28 or 256. / * PROG4.C * / # include < stdio.h > main ( ) { char a ; a is declared to be of character type. a = ‘ A ‘ ; printf ( " A = %c ", a ) ; } output - A = A Variable a is declared as character type and then assigned a value 'A' which is a character constant. A character enclosed in single quotes makes a character constant. Type char and unsigned char are equivalent. signed char can store values from -128 to 127 ( 128 + 127 + 1 for zero = 256 ) C has a unique feature by which numeric values can be mixed with characters or characters can be treated as numbers. / * PROG5.C * /

Page 8: C programming

C FOR ENGINEERS R.G.Salokhe

# include < stdio.h > main ( ) { char a ; a is declared as character. a = 65 ; a is assigned a numeric value printf ( " Decimal value of a is %d \n ,"a ) ; printf ( " Character value of a is %c \n,"a) ; } output - Decimal value of a is 65 Character value of a is A The ASCII value of A is 65. B is 66 etc. Thus A can mean 65 or B can mean 66. ASCII value of lower case a is 97 and that of b is 98 etc. This feature can be used to convert upper case letters into lower case and vice versa. / * PROG6.C * / # include < stdio.h > main ( ) { char a, b ; a = 'A' print f ( " value of a is % c\ n", a ) ; a = a +32; Adding 32 to character converts upper case to lower case. printf ( " now a is %c " , a ) ; } output - value of a is A now a is a Initially we have assigned upper case A to variable a. Later we have added 32 to variable a. Now the value stored in variable a is lower case a. We have used char type in above examples. However the char type can be declared in three ways;

Page 9: C programming

C FOR ENGINEERS R.G.Salokhe

char signed char

unsigned char Simply mentioning char declares the variable to be of signed char type ( However for some compilers it is unsigned char.) The range for char varies from -128 to 127 and for unsigned char it is 0 to 255, total 256 numbers. The characters have a space of 1 byte or 8 bits available. The first bit is taken up by the sign sign maximum number you can store in 7 bits is 127. and the maximum number that can be stored in the remaining 7 bits is 127. So how can you store the number -128 ? It is something called as 2’S compliment method ; 1 0 0 0 0 0 0 0 -128 1 0 0 0 0 0 0 1 -127 1 0 0 0 0 0 1 0 -126 Integer Type :- Integer variables store a value which are whole numbers i.e. a number with or without sign but no fractional part and hence are declared as; int i; Integers have the following range ;

Page 10: C programming

C FOR ENGINEERS R.G.Salokhe

Declaration Bytes Range

short int 2 -32768 to 32767

signed short int 2 -32768 to 32767

unsigned short int 2 0 to 65535

int 2 -32768 to 32767

signed int 2 -32768 to 32767

unsigned int 2 0 to 65535

long int 4 -2147483648 to 2147483647

unsigned long int 4 0 to 4294967295

signed long int 4 -2147483648 to 2147483647

a) The int word may be ommitted in all the cases except where you want to declare the variable as int only. eg. int i; long i ; unsigned long i ; b) int and signed int are same. long and signed long are same. / * PROG7.C * / # include < stdio.h > main ( ) { int i; i=5; printf ( " Value of i is = %d\n", i); i=6; printf ( " Value of i is = %d\n", i);

Page 11: C programming

C FOR ENGINEERS R.G.Salokhe

} output - Value of i is = 5 Value of i is = 6 For printing long int an ‘ ld ‘ format is used in the printf eg. long i; printf ( “%ld “ , i); Floating Point Type :- Floating point variables store a number which has fractional part. Thus the floating number is divided into two parts; 1) Mantissa :- The digits are stored in the Mantissa part. The number of digits of accuracy is decided by the Mantissa part. 2) Exponent :- The exponent part decides the 10s power the Mantissa is to be raised to and thus the range of the number. / * PROG8.C * / main( ) { float f ; f = 3.142 ; printf ( " %f " , f ) ; } output - 3.142000 6 digits are printed. For more accuracy the floating point numbers can also be declared as double or long double. Modifier L is used in printf to denote long double as; printf ( “ %Lf “ , f ) ;

Declaration Precision digits Bytes Range

float 7

4

3.4 X 10-38 to 3.4 X 10+38

Page 12: C programming

C FOR ENGINEERS R.G.Salokhe

double

15

8

1.7 X 10-308 to 1.7 X 10+308

long double

19

10

3.4 X 10-4932 to 3.4 X 10+4932

What if you exceed the limit :- If you exceed the limit of the variable you would not get an error message. Instead value of the variable is reset in the rotational manner. If you declare i to be a character then the values stored in i will range from -128 to 127. If you assign a value of +128 to i then i becomes -127. Value of 129 will make i equal to -127 and so on. Let us solve a question from Mumbai University paper, / *PROG9.C * / main ( ) { int i = 320 ; char j ; j = i ; printf ( " %c " , j ) ; } output - @ j can take a maximum value of 127, after 127 it will become -128. we have to go on substracting 128 from 320 till we get a feasible value.

320 - 128

----------- 192 - 128

----------- 64

since 64 falls in the range of j, the character a whose ASCII value is 64 will be printed. Instead of i = 320 if you make it 321 then the value of j will be 65 and A will be printed.

Page 13: C programming

C FOR ENGINEERS R.G.Salokhe

/* PROG10.C */ main() { int i=32; i=i*(i/3)*100+800; printf( "%d",i); } Output :- -32736 Here again i/3 will be 10 because i is integer and it can not store fractional part. We are trying to assign a new value which is 32*10*100+800 = 32800 to i. This is out of range of the integer. -32768+32800 = 32 -32768+32 = -32736 You must have observed that assigning float value to integer truncates the fractional part. If you change the program as /* PROG11.C */ main() { int i=32; long j; j=i*(i/3)*100+800 printf (" %d",j); } Output :- -32736 You may think that because j is of long type it will hold the value 32800, but before the value is assigned to j, the right hand side evaluates to an integer value which is -32736. Try the following to get the correct result. j=i*(i/3)*100+800l; Constants :-

Page 14: C programming

C FOR ENGINEERS R.G.Salokhe

We deal with the constant since our childhood. Constant is an entity whose value does not change. All the numbers are constants. However we have to have diffrent types in constant as that of variables for efficient management of memory. Named Constants :- Named constant will have a name like variable but the value of the named constant would not change as

float PI=3.142; Here you declare PI as floating type variable but you are not supposed to change the value of PI. However you may accidently change the value of PI. To avoid this you can use const key word in the declaration as

const float PI= 3.142; Now the compiler itself would not allow you to change the value of PI and you can use PI into any expression as;

c=2*PI*j; Symbolic or substitution constants :- For using symbolic constant the have to use a preprocessor directive called # define eg. #define PI 3.142 When you compile the C program the preprocessor gets an instruction from the above statement to substitue PI with 3.142. Whereever it finds PI written in the program the same is substituted by 3.142. PI is not a variable name. PI is not a variable it cannot be used as the variable .

Page 15: C programming

C FOR ENGINEERS R.G.Salokhe

/* PROG12.C */ #define PI 3.142 main() { float c; int r; r=15; c=2*PI*r; ( 3.142 is substitued in place of PI. ) printf( "%f ",c); } Integer Constants :- Numbers without fractional parts constitued integers.eg. i=5 ; here 5 is an integer constant. Long integers can have l suffix.eg. long int i; i=1234567 l; Floating Point Constants :- Are numbers with fractional part. eg. 79.462 123E-3 equivalent to 123*10-3 Long double floating point constants can have L suffix as d= 12345.32L; You can also suffix f to floating point constants as f=79.46f; Character Constants :- The characters constants are enclosed in the single inverted comma or single quotation mark. eg.

'A' , 'b' , '1' etc. You can have only one character inside the quotation mark.

char ch; ch='A';

Page 16: C programming

C FOR ENGINEERS R.G.Salokhe

Charater constants also represent the type int . The value then is the ASCII value of the character. eg. ASCII value of A is 65, that of B is 66 etc. and thus A also means 65. char ch; ch='A'; ch=ch+1; printf(“ %c”,ch); will print 'B' Non printable characters :- We have used '\n' character in printf. This is a non printable charater and represents new line. Thus when we write printf (" Hello \n"); ( new line character to skip one line . ) printf(" Hi"); 'Hello' is printed on first line and 'Hi' is printed on the next line. If \n is not there the printout will be HelloHi; The use of \ before a printable character to print non- printable character is also called escape sequence. The escape sequences available are.

character description Hexadecimal Value '\n' New line / Line feed '\x0a' '\t' Tabs '\x09' '\r' Carriage Return '\x0d' '\v' Vertical Tabs '\x0b' '\f' Form feed / Page Eject '\x0c' '\b' Back space '\x08' '\a' Bell '\x07' '\' Single quote '\x27' '\" Double quote '\x22' '\0' String terminating null

'\x0'

/* PROG13.C */ main()

Page 17: C programming

C FOR ENGINEERS R.G.Salokhe

{ char ch,ch1; ch='\a'; ch1='\n'; printf (" %c",ch); printf ("Hello"); printf ("%c",ch1); printf ("\x0a Hello "); "\x0a can be used in place of \n printf ("\x07 Hello "); "\x07 bell } Output :- * bell * Hello Hello *bell* Hello String Constants Or String Literals :- String is a array of characters. ( We will discuss about this later ). The characters enclosed in double quotes represent a srting. The string may or may not contain any characters. " " - empty string "Hello" are the examples of strings. If we want a double quotes and back slash in the string then we have to put a back slash before this as. "\" Hello \" " "\\ Hello " The string is automatically terminated with the null \0 character. This is always the last character of the string. The string "Hello" is actually stored in memory as; H E L L O \0 /* PROG 14.C */ main( ) { char ch[]= "Hello"; ( ch declared as array of characters ) printf ("%s",ch); } Output :- Hello Octal Constants :- Octal constants use digits from 0 to 7 like the decimal constants which use digits from

Page 18: C programming

C FOR ENGINEERS R.G.Salokhe

0 to 9 83 82 81 80 512 64 8 1

1 7 =8+7 = 15 in decimal

7 4 56+4 = 60

Octal constants are written with starting 0. as 017 , 074 etc. Hexadecimal constants :- Hexadecimal constants use digits from 0 to 15 and thus powers of 16. The numbers after 9 are represented with A,B,C,D,E,F. A=10, B=11, C=12, D=13, E=14, F=15 162 161 160

256 16 1 1 7 = 16+7 = 23 in decimal 3 F = 48+15= 63 in decimal Declaring And Defining The Variables :- Before you use any variables it is required to be declared so that the compiler knows that you are going to use the variable in the program. It also knows the type of variable and the memory required to be allocated for that variable. This way you can avoid duplicate variable names and also errors in spelling the variable name. eg.if you declare int day-of-week ; and later on say day-of-wek=5; The compiler will point out the error, since there is a spelling difference in the variable declared and the variable you are trying to use. In some interpreter languages another variable day-of-wek will be created causing errors and mishaps to the logic of the program.

Page 19: C programming

C FOR ENGINEERS R.G.Salokhe

Defining the variables means setting aside memory for the variables. Since the statements so far used by us also set aside memory for the variable we are doing the job of declaring and defining at the same time. When you declare int i; We are informing the compiler that we are going to use a variable name called i , i is going to be of integer type and a memory of 2 bytes should be alloted to i . The size of memory alloted depends on the type and machine. The variables is required to be decleared before use. The declarations are made at the beginning of the block.

examples : int i=0;

int i,j; float x; i=j=0;

int i=5, j=2 ;

char name[ ] = "Ajay"

Enumerated Constants And Variables :- Enumerated Variables are like integer variables but they are associated with named constants and their values can vary within a limit only. eg.

enum color ( Yellow, Cyan, Magenta ); here color is the tag name and it can be used to declare a variable of enum type . Yellow, Cyan, and Magenta are named constants and their values will be; Yellow = 0; Cyan =1; Magenta =2 and so on if you have more names in the bracket. \*PROG15.C * \ main ( ) { enum color (yellow, cyan, Magenta); enum color Y,C,M ; Y=Yellow ; C=Cyan;

Page 20: C programming

C FOR ENGINEERS R.G.Salokhe

M=Magenta; printf ("%d \n",Y); printf ("%d \n" ,C); printf ("%d \n" ,M); } Output :- 0 1 2 Since Y, C and M are declared of enum color type their values can vary only from 0 to 2. ‘Yellow ‘ means 0, ‘Cyan’ means 1, Magenta means 2 and thus;

Y=Yellow; will store 0 in y You can however assign a different value to Yellow or Cyan or Magenta in the declaration. The subsequent values will also change. eg.

enum color ( Yellow =5, Cyan, Magenta ); in this case Yellow will have a value of 5, Cyan will have a value of 6 and Magenta will have value of 7. You can have enum color ( Yellow, Cyan =8, Magenta ); In this case Yellow will be 0 ,Cyan will be 8 and Magenta will be 9.

======= **** =======

Page 21: C programming

C FOR ENGINEERS R.G.Salokhe

Input Output Functions:- Formatted output printf( ):- We have so far used the printf( ) function to output information on the screen. Let us discuss the printf( ) function in a little detail. The printf( ) function is a formatted output function. You have to specify the format in which you want the output. The format is specified in double quotes.

printf ("value of A=%d \n",A); Function Format Optional argument string Escape sequence Conversion specification for the argument The simplest form of printf( ) will be without any arguments as ;

printf( "Mumbai is a great city");

The conversion specification:- The conversion specification follows with % sign. The number of conversion specifications depend on the number of arguments. The conversion specification will have the following format;

%[flag][width][precision][modifier][type]

All the fields shown in the brackets are optional. The following types may be used;

d or i - decimal u - unsigned o - octal x or X - hexadecimal f - fixed floating point e or E - exponential g or G - shortesh of f and e c - character s - string p - pointer

The following flags may be used;

Page 22: C programming

C FOR ENGINEERS R.G.Salokhe

- Left justify the number + Leading + sign for d,i,f,e,E,g or G type space Positive values with leading space for d,i,f,e,E,g,G types only. The width fields specifies the minimum width in which the number should be printed. However if the width of the number to be printed exceeds the specified width then the specified width is ignored. The width may be specified with leading 0 so that 0 are printed leading the number. The Precision field decides the number of digits to be printed after the decimal point. If no precision is specified then the default width is 6. Though integer numbers do not have a fractional field the precision may be specifed. In that case the precision decides the maximum number of digits to print. For g or G type the precision specifies the maximum number of digits to be printed after the decimal point. For s type the precision decides the number of characters to be printed. \* PROG16 .C *\ main( ) { int i=1234; printf (" %d \n ",i); printf (" %-5d \n ",i); /* negatative flag */ printf (" %5d \n ",i); printf (" %3d \n" ,i); /* width less than number */ printf (" %+d \n",i); printf (" %d \n ",i); /* space before type */ printf (" %05d \n",i); printf (" %.5d \n ",i); /* precision specification */ printf (" % 5.2d \n ",i); } Output :- 1234 left justified 1234 left justified 1234 +1234 01234 01234 1234 \* PROG17.C*\

Page 23: C programming

C FOR ENGINEERS R.G.Salokhe

main( ) { float f =3.142 ; printf (" %f \n ",f); printf (" %e \n ",f); printf (" %.2f \n ",f); printf (" %.2e \n ",f); printf (" %6.2f \n ",f); } Output :- 3.142000 3.142000e+00 3.14 4.14e+00 3.14 the 6.2 width means total width of 6 including decimal points and fractional digits.

1 3 . 1 4 Do not try use wrong type specification for the values. It will give wrong results, as float i =3.5; printf ( "%d \n ",i); integer float type type or int i = 7.2; printf ( "%f \n ", i); float integer type type The assignment int i = 7.2 ; is however correct. That case the value of i will be 7. Formatted input scanf()

Page 24: C programming

C FOR ENGINEERS R.G.Salokhe

You must be starting for a function which can accept values from the key board. scanf( ) is the function used for this purpose. scanf( ) is a little tricky function in the sence that it requires the address of the variable in its parameters. why ? we will learn when we learn the functions. Let us see what the address means. So far we have learned that every variable declared will have a name, a value and a type. The further parameter the variable will have will be the address in the memory where the variable is stored.

NAME VALUE i 35

TYPE ADDRESS int 4099

VARIABLE

The address of any variable is representated by &i. /* PROG18.C*/ main( ) { int i = 35; printf(" %d \n ",&i); } Output :- 4099 you may get a diffrent answer. This is the address where value of i is stored. The simplest form of scanf( ) will be \*PROG19.C*\ main( ) { int i ; printf(" Type a number "); scanf(" %d ", &i); printf( " \n You typed %d ",i); } Input / Output Type a number 35 You typed 35

Page 25: C programming

C FOR ENGINEERS R.G.Salokhe

You can input two values at a time \*PROG20.C*\ main( ) { float i,j ; printf(" Type two values "); scanf(" %f %f ", &i,&j ); printf(" \n Sum is %f ", i+j); printf(" \n Multiplication is %f ",i*j); printf(" \n Division is %f ", i/j); } Input / Output Type two values 21 3 Sum is 24.000000 Multiplication is 63.000000 Division is 7.000000 If you want to input the values seperated by comma then you can use scanf(" %f , %f ", &i , &j ); You may specify the field width and not separate the values as scanf(" %3d%2d ", &i,&j ); You can type 23145 and the value of i will be 231 and that of j will be 45. You can also use scanf( ) for inputting characters and strings but scanf() is little tricky for string. /*PROG21.C*/ main ( ) { char ch [30]; string is array of characters scanf("%s",ch); & is not used for arrays. printf (" \n Good Morning Mr. %S",ch); } printf ("type a Name \n"); input output Type a Name Satish

Page 26: C programming

C FOR ENGINEERS R.G.Salokhe

Good Morning Mr. Satish If you type Satish Sharma then also Good Morning Mr. Satish will be printed. Scanf ( ) will just ignore the surname as it is followed by a space. You can solve the problem by writing the scanf function something like. scanf("%[A-Z a-z]\n",ch) space is required here. /*PROG22.C*/ Main ( ) { char c1,c2 ; printf ("Type two charcters\n"); scanf ("%c%c", &c1,&c2); printf ("First charcter % c\n",c1); printf ("Second character % c\n",c2); } Input/Output Type two characters AB do not separate the characters. First Character A Second Character B Because space is also a character you do not separate the characters with space. If you have to separate the input characters with a space then you have to write the scanf ( ) as. scanf ("%c %c",&c1,&c2); space Incase of floating point numbers "%f %f" and "%f %f " will mean the same thing. Normally scanf ( ) will follow printf ( ) so that the operator is prompted as to what is requested to inputed. You have to also ensure that the data types inputed are correct as per format. Conversion of fahrenheit to centigrade.

Page 27: C programming

C FOR ENGINEERS R.G.Salokhe

/* PROG23.C*/ main ( ) { float fa,ce; printf ("Enter fahrenneit temperature\n"); scanf ("%f",&fa); ce= (5/9-0) * (fa-32); printf ("Fahrenneit = %f",fa); printf ("Centigrade = %f",ce); } Input/Output Enter Fahrenneit temperature 32 Fahrenneit = 32.000000 Centigrade = 0 .000000 Note that if you write 5/9 instead of 5/9-0 it will work out to be 0 because the division of two integers will be an integer number without fractional part. Function gets( ) The scanf function puts a limitation on the input when a string is entered. If you write /*PROG24.C*/ main ( ) { char ch[ ]; scanf ("% s", ch); printf ("% s", ch); } Input/Output Rajendra Salokhe Rajendra

Page 28: C programming

C FOR ENGINEERS R.G.Salokhe

The surname has vanished in the output. scanf scans the string till a white space is encountered. There is a better function available which inputs the string till new line or end of file (^z) is reached. /*PROG25.C*/ main ( ) { char ch[ ]; gets (ch); puts (ch); } Input/Output Rajendra Salokhe Rajendra Salokhe We have also used the puts function which outputs the string on the screen. scanf ( ) poses another problem when character input is considered; /*PROG26.C*/ main ( ) { char c,d; scanf ("%c%c", c,d); printf ("% d\n",c); printf ("% d\n",d): } Input/Output A 65 10 You want to input two values for c and d. When you type A and press enter the enter key is considered as another character. Thus value for A=65 and values of enter key=10 is outputed. The computer does not wait for another character. How do you input the value of d ? It is by two methods; 1) scanf ("% c\n",c); scanf ("% c\n",d); Take a dummy variable e, 2) scanf ("%c %c", c,e); To handle characters and strings c has made available some other functions.

Page 29: C programming

C FOR ENGINEERS R.G.Salokhe

getch( )/getehe( ) Both this functions allow to input a character from the keyboard with a little difference; /*PROG27.C*/ # include <conio.h> main( ) { char ch; ch=getch( ); printf ("\n%c\n", ch); ch= getehe( ); printf ("\n%c\n", ch); } Input/Output A This is not shown on the screen. A No enter key is required to press. A When you use getehe( ) what you type is shown on the screen. These are also other functions available to output the character. We will use these functions with another input function. /*PROG28.C*/ # include < conio.h > main( ) { char ch; ch= getehar( ); getehar( ) needs an enter key to be pressed. putchar (ch); output to standared output device. ch= getch ( ); putch (ch); output to text window, for now it is same as putehar( ) } Input/Output r Enter key is requited r t t No enter key required. Nothing is shown on screen. If you recollect our discussion about the functions we know that all the functions output something or return some value. and the function represents the output value. That is why we can assign.

Page 30: C programming

C FOR ENGINEERS R.G.Salokhe

ch=getch( ); We have to remember that all the input functions discussed by us return an integer value and not the character value. It is thus advisable that insted of declaring ch as character. ch should be declared as integer as. int ch; Another thing to note that we have included the conio.h (pronounced con-eye-o) file in the program because gethe( ), getch( ) and putch( ) functions are declared in the conio.h file. Also note that getehar( ) is not a function but is macro extracted from fgetchar( ) function. Macro is something you obtain with a #define statement. In the above context even the printf( ) function returns an integer value for printf it is number of characters printed. /*PROG29.C*/ main( ) { printf("% d", printf("Hello")); } Output 5 Type Conversions When you write an expression you come across mixing various types in the expression as 5+2.5 Integer Float Here we are adding an integer constand to the constant of float type. This type of addition is not easy for the computer. as integer and floats are stored in different formats. The process required to be done is to convert the integer into float and then do the addition. Since we may mix a lot of different types the rules followed by C are in the following steps Step1 :- Convert all short and char operands to int type. Step2 :- Convert all float operands to double. Step3 :- After the above conversion if a double operand is there then all the operands are coverted double. Step4 :- If a long to operand is there then all the operands are converted to long. Step5 :- If any of the operand is unsigned then all the operands are converted to unsigned.

Page 31: C programming

C FOR ENGINEERS R.G.Salokhe

Step6 :- Since all the operands are convereted into a single type the result will be calculated in that type. 'A'+3+5.0 Char is converted to int Float converted to double. 65+3+5.0 Integers converted to double 65.0+3.0+5.0 Result is double 73.0 ASSIGNMENT CONVERSION :- Evaluating the expression to a certain type and assigning it some other vanable are different things. While the expressions as discussed above evaluate to maximum accuracy the assignment works in the reverse fation. Float=Double; Value is rounded and truncated eg. Float f=12345678.5 will store a value of 12345679.0 in f. Long=Float; Fraction part of float is truncated. In the above example the value stored in long will be 12345679. Int=Long; When the value exceeds that of type int it goes back to - 32768 and starts add in further. In any case the value thus obtained may be unpredictable and will cause errors in the program. ARITHMATIC OPERATORS :- We are aware of some of the arithmatic operators. These are as follows Unary :- Unary operators work only on one operand eg. -5, -d, f

Page 32: C programming

C FOR ENGINEERS R.G.Salokhe

They change the value of the operand to negative if the operand is positive and positive if the value of operand in negative. + Operator :- The plus operator does various addition. (We will come across other additions later). Grouping of + operator is done from left to night. d= a+b+c; d= (a+b)+c; a and b are first added and then c is added to the addition. - Operator :- Is used for substraction. * Operator - Is used for multiplication. and have higher precedance than + or -. d=5+3*4; multiplication is done before addition. d=5+12 =17 If addition has higher precedance then the above expression will evaluate as (5+3) * 4 = 8 * 4 =32 Which is wrong. / Operator:- This operator performs division .Interger type divided by integer yields interger type. Thus 5/9 will always give and answer equal to 0. % Modulus operator The moudulus operator works on interger data types and yields in the result equal to the remainder of the division. e.g. 7 % 5 = 2 7 % 6 = 1 7 % 7 = 0 7 % 8 = 7 ( 7 * 0 = 0 and remainder is 7 ).

Page 33: C programming

C FOR ENGINEERS R.G.Salokhe

RELATIONAL OPERATORS :- < (Less than ), <= (less than or equal to ) , > (greater than ), >= (greater than or equal to ) are the relational operators which are used to test the conditions between two operands. /* PROG30.C */ main ( ) { int i; printf ( " Type a number " ); scanf ( " %d " , & i); if ( i > 0 ) printf ( " \n the number is positive "); } The program is self explainatory . The important point you have to remember is that the experssion (i >0 ) evaluates to be 1(true) or 0 (false). If you write printf ( " %d " ,5 >7); the answer will be 0 as 5>7 is false. EQUITY OPERATORS:- = = ( equal to ) and ! = ( not equal to ) are the equity operators which work similar to relational operators.They compare the operands. The students many a times confuse between (= equal to) assignment operator and = = equity operator. The assignment actually assigns value to the variable but the = = operator just compares the values. e.g. i = 5; will change the value of i to 5. i = = 5; will compare the value of i if it is 5. LOGICAL OPERATORS :- && ( logical and ) | | ( logical or ) ! ( logical not ) are the logical operators. /* PROG31.C */ main ( ) { int i,j; printf ( " Input two values " ); scanf ( " %d %d ",i ,j);

Page 34: C programming

C FOR ENGINEERS R.G.Salokhe

if ( (i >0 ) &&(j >0) ) printf ( "Both are positive ") } Remember to put two times & while using the logical & operator . /*PROG32.C */ main ( ) { printf ( " %d ", 3&&4); } Output 1 3 is true and 4 is true, so that 3&&4 is true which is 1. Let us analyse the results. i j i >0 j > 0 (i >0 ) && ( j >0 ) 2 2 1(true) 1 (true) 1 (true) 2 -2 1 (true) 0 (false) 0 (false) -2 2 0 (false) 1 (true) 0 (false) -2 -2 0 (false) 0 (false) 0 (false) Thus True && true is true True && false is false False && true is false False && false is false Similarly for | | ( or ) the values are True | | true is true True | | false is true False | | true is true False | | false is false /*PROG33.C*/ { int i=0; if (!i) printf ("number is zero"); } Writing (!i) is equivalent to writing ( i = = 0 ) when i is equal to zero (false), !i becomes true. In the above case because i is 0, !i becomes true and the "Number is zero" will be printed.

Page 35: C programming

C FOR ENGINEERS R.G.Salokhe

Increment and decrement operators Increment and decrement operators are unary operators. Which means they operate on a single operand. They increase or decrease the value of the operand. eg. Consider a = 5, b = 6 c = a + b + +; c = a +( b + + ); c = a + b; b = b + 1; c becomes 11, b becomes 7. While if we write c = a + + + b; c = a + ( + + b ); b = b + 1; c = a + b b becomes 7, c becomes 12. Thus a + + means use the value of a and then increment. + + a means increment the value of a and then use. /*PROG32.C*/ main ( ) { int i = 0, j = 0; int k; k = i + + + + + j ; printf ( "%d\n",k ); k + +; used like this + + k and k + + will mean the same thing. printf ( "%d\n", k ) ; } output 1 2 k = i + + + + + j; k = ( i + + ) + ( + + j ) ; k = 0 + 1 = 1 i becomes 1 after its value 0 is used. After executing the above statements the value of all i,jand k becomes 1. Conditional Expression:-

Page 36: C programming

C FOR ENGINEERS R.G.Salokhe

The query or turnary operator ? is used in conditional expression as; ( a> b ) ? a : b; if the value of a is greater than b then the value of a is returned otherwise the value of b will be returned. /*PROG33.C*/ main ( ) { int i,j,k,max; printf ("Type two numbers\n"); scanf ("%d %d", i,j ); max = ( i>j ) ? i:j ; printf ("Maximum is %d", max ); } Input/ output Type two numbers 2 3 Maximum is 3 The conditional expression can be used to find out the maximum of 3 numbers as; ( a > b ) ? (a > c ) ? a : c : ( b > c ) ? b : c

Page 37: C programming

C FOR ENGINEERS R.G.Salokhe

CONTROL STATEMENTS :- We have so far seen small programs which are executed line by line. However the major requirement of programs is to have forward and backward jumps to different lines. The statements which allow such jumps are called control statements. If Statements:- If statements allows forward jumps depending upon the condition specified. If has following two formats; true if (condition ) statement; false if ( condition) { Statement 1; Statement 2; } No semicolon. false /*PROG34.C*/ main ( ) { int i,j,max; printf ( " Type two numbers \n "); scanf ( "%d %d ", i,j); max=i; if ( i<j ) max=j; printf ("\n Maximum of two is %d",max); }

Page 38: C programming

C FOR ENGINEERS R.G.Salokhe

/*PROG35.C*/ main ( ) { /* I has to be maximum */ int i,j,t; printf ( "Type two numbers \n "); scanf ( "%d %d ", &i,&j); if ( i > j) { t=i; i=j; Interchanging values of i and j. (swapping) j=t; } no semicolon printf ( "\n i = %d j=%d \n ", i, j); } We have used a technique of swapping the values of i and j variables. For this you have to first store the value of i into a temporary variable t .Then you can equate i to j and then j to t. So that values of i and j are interchanged. Another technique you can use is . float i =5, j=6; i = i *j; j = i /j ; i = i /j ; The above method will not work for integers . if ; else ; statement :- if (expression ) statement 1; FALSE TRUE Note semicolons else statement 2;

i j 30.0 5.0 30.0 6.0 5.0 6.0

Page 39: C programming

C FOR ENGINEERS R.G.Salokhe

if (expression ) TRUE { statement1; FALSE statement2; } No semicolon. else { Statement 3; Statement 4; } No semicolon. /* PROG36.C*/ /*Maximum of two numbers*/ main ( ) { int max,i=5,j=7; if (i >j ) max =i ; else max =j; Note semicolons. printf ( "\n %d is max \n ",max ); } /*PROG37.C*/ /* Roots of quadratic equation*/ #include < stdlib.h> for exit ( ) #include <math.h> for sqrt ( ) main ( ) { double x1,x2,a,b,c,t; printf ("Type values of a b c "); scanf ("%d %d %d ", &a,&b,&c); if (b*b -4*a*c<0) { printf ( "Roots are imaginary \n "); exit (0 ); } No semicolon. else { t=sqrt (b*b -4*a*c); x1=(-b+t)/(2*d); x2=(-b-t )/(2*a); printf ("The roots are %f %f ",x1,x2); } No semicolon }

Page 40: C programming

C FOR ENGINEERS R.G.Salokhe

input 4 2 5 Nested if :- The if statement can be nested in following ways. if (condition ) if (condition) statement; This if is attached to else. else statement; /* PROG38.C*/ main ( ) { int i; scanf ( "%d ",&n); if (n >0) if (n<100) printf ( "Number is between 0 and 100 "); else printf ( "Number is greater than 100 "); } The else statement does not correspond to the first if . The else statement is marked to second if so that when n is not less than 100 the else is executed. If we want to match the else statement to the first if then it can be done in two ways. if (n >0) { if (n<100) printf ("Number is between 0 and 100"); } else printf( "Number is less than 100"); or if (n >0) if (n<100) printf ("Number is between 0 and 100"); else ; Dummy else. else printf ("Number is less than 100");

Page 41: C programming

C FOR ENGINEERS R.G.Salokhe

The If ______ else chain :- We can have series of if -else statements in the following manner. if (expression) statement; else if (experssion) statement; else if (experssion) statement; /* PROG39.C*/ main ( ) { int mark; char rank; scanf ("%d ",&mark); if mark >80 rank = 'E'; else if mark >70 rank= 'A'; else if mark >60 rank= 'B'; else if mark >50 rank= 'C'; else rank = 'F'; printf ( "Rank is %c",rank); } /* PROG40.C*/ /*Printing a number in reverse order */ #include<iostream.h> #include<conio.h> #include<stdio.h> void main ( ) { clrscr( ); int i ; int t ,h, ten,o; printf ( "Enter a 4 digits no \n"); scanf ( "%d",& i); t= i /1000 ; printf ("t =%d",t); h= (i - t* 1000)/100; printf ("h =%d",h); ten= (i -t*1000 - h*100)/10;

Page 42: C programming

C FOR ENGINEERS R.G.Salokhe

printf ("ten =%d",ten); o=i -t*1000 -h*100 - ten*10; printf ("o =%d",o); printf( "Your number in reverse order is \n"); if (t = = 0 && h= = 0&&ten= =0 ) printf ( " %d " ,o); else if (h = =0 && t = = 0) printf ( "%d",o*10+ten); else if ( t = = 0) printf ("%d",o*100+ten*10+h); else printf( " %d",o*1000+100*ten+h*10+t); getch( ); } Switch Statement :- The switch statement is equivalent to writing series of if statements. The structure of switch is; switch (experssion ) { case constant1 : statement; statement; case constant2 : statement; statement; | default : statement; statement; } /*PROG41.C*/ main ( ) { int i,j,op; float ans=0.0; printf ("Type two numbers "); scanf ("%d %d ",&i,&i); printf ("\n Type operation +, -, /, * \n"); scanf ("%d",&op); switch (op) { case '+' : ans = i+j ; break; case '-' : ans = i -j ; break; case '/' : ans = i /j ; break; case '*' : ans = i*j ; break; default : printf ("Invalid operation \n "); } printf ( "%f ",ans ); }

Page 43: C programming

C FOR ENGINEERS R.G.Salokhe

The important thing to remember about the switch statement is that you have include the break statement after each case. Otherwise all the cases after the matching conditions are executed. /*PROG42.C*/ main ( ) { int ch, digit, space, other; int count = 0 while ( ( ch = getehar( ) ) ! = EOF ) { switch (ch) {

case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': digit ++;count++;break; case ' ': case'\n': case'\t': space ++; count ++; break; default : other ++; count ++; } }

break transfers control here printf ( "Total characters %d\n", count ) ; printf ( " Digits typed %d\n",digit); printf ( " White spaces %d\n", space); } You can input a string terminated by control Z to terminate the while loop. The For Loop:- We have studied the if statement which jumps the control to the end of the body and not backwards. The loops allow a backward jump and thus the body of the loop can be repeated several times. for is one such most frequently used loops in C.

if character input is '3' all the cases upto '9' are executed.

Page 44: C programming

C FOR ENGINEERS R.G.Salokhe

The structure of for loop is; for ( j =0; j < 10; j + + ) statement; initialise condition increment for ( i = o; i < =10; i + + ) statement; TRUE { statement; statement; } No semicolon /*PROG43.C*/ main ( ) { int i ; Note semicolons for ( i = 1 ; i < = 5; i + + ) printf ( "%d %d\n", i, i * i ); } Output 1 1 2 4 3 9 4 16 5 25 The initial value of i is taken as 1. The first values of i and i * i are printed. Then the value of i is increased by 1. so i becomes 2 and, 2 and 4 are printed. We can find out the pairs of three numbers i, j, k such that i2 =j2 +k2 which means i, j, k are sides of right angle triangle.

FALSE |

Page 45: C programming

C FOR ENGINEERS R.G.Salokhe

main ( ) { int i,j,k; for ( i = 1; i < = 100; i + + ) for ( j = 1; j < = 10; j + + ) for ( k =1; k< = 10; k + +) if ( k<i && j <i) if ( i * i = j * j + k * k) printf ("%d%d%d\n",i,j,k); }

Initially i=1 j=1 k=1 j=1 k=2 j=1 k=3 j=1 k=10 j=2 k=1 j=2 k=2 ___ ___ ___ k=10 = = = j=10 k=1 --- k=10 i=2 ----- j=1--- k=1 For every value of i , j various from 1 to 10. For every value of j , k various from 1 to 10 and so on. /*PROG44.C*/ /* sum of first 5 numbers */ main( ) { int i ; int sum = 0 ; for ( i=1 ; i<=5 ; i+ +) make this i<=100 and you get sum of 100 nos. { sum=sum +i ; } printf ("sum is =%d\n", sum);

Page 46: C programming

C FOR ENGINEERS R.G.Salokhe

} Output sum is=15 Let us draw a flow chart of the above logic and the memory map. i = 1 sum = 0 i sum 1 0 initial NO print 1 1 is i <=5? sum 2 1+2=3 3 3+3=6 i=i+1 yes 4 6+4=10 5 10+5=15 sum=sum+i A simple modification in the program will help us find out the factorial. /*PROG45.C*/ /*Program to find factorial*/ main ( ) { float i;fact=1.0; for (i=1 ; i<=5 ; i+ +){ fact= fact * i ; } printf ("%f", fact); } Output 120.000000 You can modify the program asking for the input value and write

Page 47: C programming

C FOR ENGINEERS R.G.Salokhe

i<=n in place of i<=5 We can write a program to find out the power x n

x n = x * x* x -------n times so we can go on multiplying x, n times /*PROG46.C*/ main ( ) { float x, power=0.0; int n; printf (" Type a number \n"); scanf ("% f",&x); printf (" Raise this number to\n"); scanf ("%d", &n); for( i=1; i<=n; i+ +){ power= power*x;} printf ("% f Raised to %d is % f", x,n,power); }

/*PROG47.C*/ /* Printing a triangle of Numbers */ main ( ) { int i, n, j ; printf ("Type a number \n"); scanf ("%d", &n); for (i=1 ; i<n ; i+ +){ for (i=1 ; j<=i ; i+ +) Note i here printf ("%3d", j); printf ("\n"); } Output : Type a number 5 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5

Page 48: C programming

C FOR ENGINEERS R.G.Salokhe

for every value of i, j will vary from 1 to i /*PROG48.C*/ /* Pascal Triangle*/ main ( ) int nn,i ΞΞ =, m =1 int k,n,j =40, l = 0; clrscr ( ); clears the screen. printf ("Type No \n"); scanf (" %d", &nn); for(k =1;k < = nn; k =k+2) { for (n =1;n < =39-3*m;n++ ) printf (" "); for (i =m++;i< =k; ++i) printf ("%3d", i); for (i =k-1, j = l++; j > =1; j- -,i - -)printf ("%3d",i); printf ("\n"); } getch ( ); } output k decides the middle column and thus varies as 1, 3, 5, 7,9

i prints the left hand side value as 1, 2 3, 3 4 5, 4 5 6 7, 5 6 7 8 9 value of i in third loop starts with m + + which initially is 1 and then becomes 2, 3, 4 and lastly 5. In forth for loop i starts with k thus when k becomes 3 i becomes k-1=2 next time it becomes 4 then 6 and 8. This prints the right side as

2 i in second 4 3 for loop 6 5 4 8 7 6 5

9 1 2 3 2 3 4 5 4 3 4 5 6 7 6 5 4 5 6 7 8 9 8 7 6 5

Page 49: C programming

C FOR ENGINEERS R.G.Salokhe

How many numbers eg. 4 is decided by the i in second for initial value of l is taken from l which increment from 1 to 4. The second for loop is for bringing the display into center of the screen. It prints spaces 39-3m times = 36 times for first line and 39 - 3*2 = 33 times for second time etc. 1 Edge 36 space of 2 3 2 screen 33 space 3 4 5 4 3 30 space There is program which print the range of integer variables. We have already discussed that the range varius from - 32768 to 32767. /*PROG 49.C*/ main ( ) { int low, high, i,i ; low = high= 0 ; Note the type of assignment for (i=1 ; high<= 0; i=i+2){ for (low=1, i=1 ; k=i ; i + +) low = -2*low ; high = low -1 ; } printf ("Range for integers %d, %d", low,high); } In C you will come across very interesting and intelligent logic. In the above program i various from 1 in the steps of 2 . So value of i becomes 1, 3, 5, 7 etc. When i becomes 3 the second for loop is executed 3 times and the values of low changes as follows ; Iterations Value of low low = -2 * low 1 -2 2 +4 3 -8 Value of low will go on increasing but to the negative side. Since we are assigning high = low-1 the value of high remains negative till low becomes - 32768 When we subtract 1 from - 32768 it becomes + 32767 We have already discussed in earlier chapters the effect of increasing the range of data types. ( 32767+1 becomes - 32768 ) -1 0 -1

Page 50: C programming

C FOR ENGINEERS R.G.Salokhe

-2 2 3 -3 4 -32767 -32768 +32767 32767+1 becomes - 32768 Thus when value of low is - 32768 the value of high becomes + 32767 and the first for loop terminates. The control is transferred to printf statement. We have seen that the for statement can initialise any number of variables as for (i =1, j =2 ; i <=5 ; i + +, j+ +); We can have a for loop without initialisation for (j + + i<9 ;); You can have the for loop without any parameters \*PROG50.C*\ # include <ctype.h> main( ) { int c, vowels =0 , count =0 ; for ( ; ;){ c= getche( ); switch (toupper((c)) { case 'A' : case 'E' : case 'I' : case 'O' : case 'U' : vowels + +; count + +; break ; Breaks default : count + +; } if(c = = EOF) break ; Breaks the for loop printf ("Total characters %d %n" , count); printf ("Vowels are %d %n" , vowels); } Toupper( ) function converts the character into upper case if it is lower case. This function is included in ctype.h file Evaluating a series :- sum =1 + (1/2)2 + (1/3)3 + (1/4)4

Page 51: C programming

C FOR ENGINEERS R.G.Salokhe

/*PROG51.C*/ # include <math.h> main( ) { double term , sum; int i, n; printf ("Type no. of terms for series\n"); scanf ("%d", &n); for (i =1; i <=n; i + +){ term =1/(double)i ; Type casting sum = sum+ pow(term, (double) i); printf ("The sum of series is %f", sum); } With i the term becomes 1, 1/2, 1/3 etc. this is then raised to i th power with pow( ) function and added to sum Let us write a program for evaluating the series; x - x3/3! + x5/5! - x7/7! /*PROG52.C*/ main( ) { int i, n, denominator =1; float x, sum, term; printf ("Type value of x\n"); scanf ("%f",&x); printf ("Type number of terms\n"); scanf ("%f", &n); for (sum =x, term =x, i =2; i<=n; + +i){ denominator = (2*i-2) (2*i-1); term*= (-x * x) / (float) denominator; sum + = term; } printf ("value of series is = %f", sum); } Let us see how the term varies;

Page 52: C programming

C FOR ENGINEERS R.G.Salokhe

i denominator Term 2 2*3 =3! (+x) (-x2)/3! = -x3/3! 3 4*5 - x3/3! * -x2/4*5 = +x5/5! The Fibonacci series The series is Obtained by adding two precious numbers to obtain the third number eg. 1 1 2 3 5 8 13 21 34 etc. 1+1 =2 1+2 =3 2+3 =5 3+5 =8 and so on /*PROG53.C*/ # include <stdio.h> main( ) { int next =0 ; int n; int last =1; for next =0; next <1000;){ n= next + last; next = last; last = n; } } Let us see how the things are happening next last n

0 1 1 1 1 1 next = last, last = n 1 1 2 1 2 3 2 3 5 : : : The While loop

Page 53: C programming

C FOR ENGINEERS R.G.Salokhe

The syntax of while loop is as follows ; while ( expression ) statement ; FALSE TRUE while ( expression ) { statement 1; statement 2; - - - - - - - } The statement are evaluated as long as the expression is true. When the condition becomes false jump is made to out side of the body of while. \*PROG54.C*\ main( ) { int n =999; while (n< =999,) scanf ("%d"&n); printf ("%d", n); } This program will allow you to enter the number till the number is less than or equal to 999. Which means the loop will not break till you enter a number which is greater than 999 that is a four digit number. Program to count number of words, characters & lines /*PROG55.C*/ # define YES 1 # define NO 0 void main( ) { int c, nl, nw, nc, inward; inward =NO; nl =nw =nc =0; while ( (c =getche ( ))! =EOF){ + +nc; if (c = =' ' | | c = ='\n' | | c = =' \t '){ if (c ='\n') nl + +; inward =NO; } else if (inward = = NO){ inward = YES;

Page 54: C programming

C FOR ENGINEERS R.G.Salokhe

+ +nw; } } printf ("NO of lones %d words %d character %d", nl, nw, nc); } } (c =getehe ( )) !=EOF Accept character from keyboard. Assign it to c. check it the character is EOF(^z) which numbers the while loop terminated when the character input from keyboard is ^z. + +nc nc is incremented every time a character is input. Then the character is checked if it is a white space character. Let us take an example. Mumbai is a great city ^z c nc nw inward 0 0 0 NO M 1 1 YES 4 2 1 YES m 3 1 YES b 4 1 YES a 5 1 YES i 6 1 YES note space 7 1 NO change l 8 2 YES at s 9 2 YES space space 10 2 NO a 11 3 YES if you want only an alphabetic character to be inputed you can use the while loop as char ch ='a' ; while( ch <= 'z' && ch> = 'A' | | ch<= 'g' && ch> ='&'){ scanf ("%d",&c);} /*PROG56.C*/ /* program to display a series of prime no.s */ main( ) { int no, chk; int prime =1; no=1; while (no<=400){ for (chk=2; chk<=no/2; chk) if (no%chk = =0){

Page 55: C programming

C FOR ENGINEERS R.G.Salokhe

prime =0; break; Break passes control here if (prime = =1) printf("%d",no); prime=1; } } The outer while loop varies the no from 1 to 400. supposing you want to find out if 11 is a prime number or not then you have to divide it by numbers from 2 to (11/2) =5. If it is divisible by any of the numbers between 2 and 5 then it is not a prime number. In our case 11 is not divisible by numbers between 2 and 5. Thus prime remains equal to 1 and the number is printed. no % chk will be 0 when no is divisible by 2 and the if is execute which makes prime =0 and breaks the loop since prime is 0 the number is not printed. prime becomes 1 and while is executed. The do ... while loop The syntax of do....while is do statement ; while ( condition ); or do { statement 1; statement 2; ---- } while ( condition ); Let us take the earlier example where we want to allow numbers greater than 1000 to be entered. We can write the program as /*PROG57.C*/ main( ) {

Page 56: C programming

C FOR ENGINEERS R.G.Salokhe

int n; do scanf ("%d",&n); while (n<1000); printf ("%d",n); } This program will go on executing the scanf till you enter a number which is greater than or equal to 1000. Let us take another example. /*PROG58.C*/ main( ) { int n; int sum; do {printf ("\n Enter a number \n"); scanf ("%d, &n); sum+ = n; } while (n>0); } This program will allow you to enter the numbers and sum them till the number is greaterr than 0. If you enter a negative number the same will be added to sum. The program will terminate. Note that the do loop is very similar to while loop. Break Statement We have used the break statement in switeh.... case and for loops. The break statement psses control out of the do, for, while and switeh statement. for ( ; ; ){ - - - ; - - - ;

Page 57: C programming

C FOR ENGINEERS R.G.Salokhe

if( ) break; for (; ;){ - - -; - - -; if( ) break; - - -; - - -; } } Continue Statement The continue statement jumps to one line before the break statement. i.e. at the end of the body of for ,do or while loop. for ( ; ; ){ - - - -; - - - -; if ( ) continue; for ( ; ; ){ - - - -; - - - -; if ( ) continue; - - - -; } }

/*PROG59.C*/ /* Adding numbers 1+3+5+7 with continue */ main( ) { int sum =0 ; int i = 1, z = -1 ;

for (i= 1; i<=100; i++) {

Page 58: C programming

C FOR ENGINEERS R.G.Salokhe

z= -z; if (z<0) continue; sum+ = i ; } printf("\n%d \n", sum); } Initially f = -1 and t = -z will make z as +1 the statement sum + =i will be executed next time when i becomes 2 z will become -1 and continue will pass control to and of for loop thus not executing sum + =i statement. Thus t will vary between +1 and -1 making the continue statement execute alternatively. /*PROG60.C*/ /* binary to decimal conversion */ # include <math.h> main( ) { long binary; int dec=0, i=0; printf ("\n Enter a binary No\n"); scanf ("%d", &binary); while(binary>0) { dec + =(binary% 10)*pow(2,i++); binary/=10; } printf ("your no. converted to decimal is %d", dec); } This is a very interesting logic. supposing your binary number is 101 which is 22+0+20 =5 dec= (binary %10)* pow (2,i++) = (101 %10)* pow(2,0) i=1 = (1) * 20

= 1 binary= binary/10 = 101/10 = 10

Page 59: C programming

C FOR ENGINEERS R.G.Salokhe

In next interation dec=1+(10%10)* pow (2,1) = 1+0 =1 binary= 10/10 =1 i=2 In next interation dec=1+(1%10)* pow (2,2) =1+ 1*22

=1+4 = 5 which is the answer The goto statement C allows a non conditional jump with goto statement. However such jumps are not adviced and the program looses structurality.

The syntax is goto LABEL; - - - - - - - - - - - - - - LABEL : /*PROG61.C*/ main( ) { float i, i; printf("Enter devisor\n"); scanf ("%f", &i); printf("Enter dividor\n"); scanf("%f", &j); if(j= =0) goto CRASH; printf("%f", i/j); exit(0); CRASH : printf("dividor cannot be zero"); } /*PROG.62C*/ /* finding square root of a number */ # include <math.h> main( ) { float x, y,z ;

Page 60: C programming

C FOR ENGINEERS R.G.Salokhe

printf ("Type a number"); scanf ("%f", &x); y= 1.0; do{ z= x/y; y= (y+z)/2 ; } while (fabs(y-z)>0.000001); printf("Root is % 7.3f", y); } fabs( ) function is used to return the absolute value of floating point numbers. If you type 4 as the number the following changes take place in the value of z and y. z y 4 2.5 1.6 2.05 1.95 2.006 1.999 2.000 2.0 2.00 The final output is 2.

Page 61: C programming

C FOR ENGINEERS R.G.Salokhe

FUNCTIONS We now enter into the soul of C language. As discussed in the I st chapter C is the language of functions main ( ) itself is a function. We have been introduced to some standard functions as printf( ), scanf( ), etc. We will now write our own function. /* */ main( ) { void print( ); Function declaration or prototype. Print( ) ; Function call. } void print( ) No semicolon. { int i ; for (i=1; i<=10; i ++) printf( "*" ); } Output * * * * * * * * * * Function declaration : As we declare the variables before we use them, the function is also required to be declared before it is called. The declaration here is very simple. Void print ( ); Not returning Name No parameters anything The print function is not accepting any parameters and is not returning anything as the value of the function. The function is defined below the body of the main. When you call the function as print( ); The print function is executed which prints ten asterisks and returns to main. We will now pass a parameters the function. / / main( ) { int i ; void print(int); printf("Type a number"); scanf("%a", & i); print(i); Value of i is passed to this i printf("\n"); print(i); }

Page 62: C programming

C FOR ENGINEERS R.G.Salokhe

void print (ir)+ i) { int j =1 ; for (j =1; j<=i; j ++) printf("*"); } Output Type a number 5 * * * * * * * * * * In this program we have passed a value of 5 to i in the function print. So it prints 5 asterisks. However the i in the main program and i in the function print has no relation. It you change value of i in function print( ) the value of i in function main( ) is not changed. This means we have passed the parameter by value. /* */ main( ) { int i=5; void change(int); change (i); printf("%a",i); } void change (int i) { i=10; Changing the value of i in the function } would not change the value in main( ). Output 5 Finding out the maximum of two numbers using mfunction /* */ main( ) { int i, j , k; int max (int,int); printf("Type two numbers\n"); scanf("%a%a", i,j); k= max(i,j); printf("Maxmum of the two is"); printf("%a",k); } int max(int i, int j) { int m; m= i>j?i:j; return m;

Page 63: C programming

C FOR ENGINEERS R.G.Salokhe

} In this example the function max is made to return an integer value int max(int, int); Function will return integer value. The value returned by the function is returned by the statement return m ; which returns the value of m Which is maximum of i and j. When you want to do the calculators repeatedly the function comes fo your resume. Let us see how we can evaluate the series. 1+1/2! +1/3! +1/4! /* */ main( ) { long fact(int n); float sum=1.0; int i=1; for (i=1; i<=5; i ++){ sum=sum + (1.0/fact(i));} } long fact(int n) { long x=1; int i=1; for(i=1; i<=n; i+ +) x=x*i ; return x ; } The function may be called any time from other functions and the value returned by functions may or may not be assigned to any variable. /* */ main( ) { int i; for(i=1; i<=10; i+ +) printf("%3d %5d %7d", i, Sq(i) cube(i)) Sq(10); Sq ( ) is called but it's value is not assigned } int Sq(int i) { return i*i; }

Page 64: C programming

C FOR ENGINEERS R.G.Salokhe

int cube(i) { Sq( ) function is called from cube( ) return i* Sq(i); } Output 1 1 1 2 4 8 3 9 27 4 16 64 5 25 125 6 36 216 7 49 343 8 64 512 9 81 729 10 100 1000 SCOPE OF VARIABLES :- As there is no print in unnecessarily occupies the memory by using lot of variables, the variables are given other properties as visibility and life time. So that the variables can be available in the particular segments of the program and they can die after their use. The scope of the variable is the section of the program in which the variable is available. There are basically two types of scopes. 1) Global Scope 2) Local Scope The variables declared outside any function have global scope and are refered to as global variable. /* */ int i=1; i is global main( ) { printf("%a",i); i is available in both void print( ); main( )&print( ) print( ); } void print( ) { printf( "%a",i); } Global variables are visible the point of declaration to the end of the program and are initialized to 0 if not initialized. /* */ main( ) {

Page 65: C programming

C FOR ENGINEERS R.G.Salokhe

int i; } int y=5; y is global but not available in main( ) void print ( ){ printf("%a",y); variable is available } in print( ) and print 1( ) void print1( ){ printf("%a",y); } LOCAL SCOPE / LOCAL VARIABLES : The local variables are declared inside the body of the function and they can be used in that function only. Thus they loose scope outside the function and thus variable with same name can be used in the other function. Which has no relation with one declared in the other function. /* */ main( ) { int x =5; void print( ); printf("%a" ,x); } Output 10/5 X is declared in function main( ) as local variable. Similarly x is also declared in function print( ) as a local variable. The x in print( ) and x in main( ) has no relation. Thus in main( ) even after calling the function print( ) the value of x print is 5. Similarly you can declare variables in the body of if also. On the first line we have declared i=6. Which is a global variable and is available from top to bottom of the program. Let us call this variable G i When we declared another variable int=5 in main( ) the G i looses scope in the main( ) function and another i is available in main( ) let us call the as main( ) i This main( ) I further looses scope in if function and for loop. Where different i is used. In printf( ) value of main i is used. We are calling the print( ) function with main i the value of which is passed to k in the print( ) function and we are printing i in the print( ) function. The value of G i is available in print( ) function and thus same is printed.

Page 66: C programming

C FOR ENGINEERS R.G.Salokhe

/* */ int i=6; Globle main( ) { int j=5 available in the body of main( ) int j; void print(int); if(i= =5){ int i; Available in body of if i=9; printf("in if %d\n",i); } printf("In main %d\n",i); for (j=1, j<=2, j+ +){ int i=17; Available in body a for print("in body a for %d\n",i);} print(i); } void print(int k) { printf("in function %d\n",i); Value from global variable. } Output in If 9 in MAIN in Body of for 17 in Body of for 17 in function pr 6 All the variables also have a life. They must die sooner or later to free the memory. The global variables die when the program is exited. The life of the variable is determined by the storage class specified for the variables. The storage classes are 1) Auto 2) Static 3) Extern 4) Register Extern storage class is available only for global variables. AUTOMATIC VARIABLES If no class is specified for the local variables then they are considered to be up to auto variables. They are created when a particular function is called and die where the execution of the function is completed. Most of the variable used and declared by us so far were of upto type.

Page 67: C programming

C FOR ENGINEERS R.G.Salokhe

STATIC VARIABLES The variables declared static are visible only in the function in which they are declared but are not destroyed when the function is exited. Instead they retain their values which can be again used in the same function. /* */ main( ) { void pr( ); pr( ); pr( ); pr( ); } void pr( ) { static int i=1; printf("%d\n",i + +); } Output 1 2 3 When the function pr( ) is first called the value of i is initialized to 1. This value is printed and i becomes 2. When the function is exited i does not loose the value 2. However i will not be available in main or any other functions. When the function is called again the value of i=2 is available to the function and i is not initialized again. Static variables are initialized to 0 no initial value assigned. EXTERNAL VARIABLES External variable are available from one program to another. Supposing you have two defferent programs as /* */ /* */ int i; extern int i; main( ) void pr( ) { { i=5 printf("%d",i) printf("%d",i) } } We used the declaration extern in the second program which means that i is declared some where else and the second program is supposed to us that i. REGISTER VARIABLES

Page 68: C programming

C FOR ENGINEERS R.G.Salokhe

Register variables are similar to automatic variables expect that instead of storing into the random access memory the same are stored into register of microprocessor. This way they can be accessed faster. There is a limitation on the number of register variables you can declare. In case there is no space available for the register variable in the registers then the same are treated as automatic variables register variables are declared as register int i; GLOBAL VARIABLES AS STATIC Global variable can be declared of static scope. When declared thus they have a scope in the program in which the same are declared and can not be used as external variables in other programs. Let us have the summery of variable visibility and life. Global Variables Class Declaration Visibility Life - Before all Entire file & other files where functions the variable is declared extern. Global Extern Before all Entire can not be initialized Global functions Static Before all Entire file but not other files initialized Global functions to 0 if not assigned a value. Local Variable None Inside a Only in that function or block. Unit end of or function or function block auto block Register -"- -"- -"- Static Inside a Only in that function Global function RECURSION Whenever a function is called the automatic variables declared in the function are pushed in to the memory area called stack. These variables have a life fill the function ends. We end the function either by a return statement or by the conduding braces. Before the function ends you can called the same function again. Thus another set of variables is

Page 69: C programming

C FOR ENGINEERS R.G.Salokhe

pushed in the memory. The process of a function calling itself is called decursion. However some where the function has to terminate. \* *\ \* finding factorial by decudsion *\ main( ) { int n; float fact( ); printf(" Enter a number "); scanf("% d%f",n,fact(n)); } float fact(int n) { if (= =1) return(1); else return n*fact(n-1); } The function fact is calling inself back with n-1. The process takes place as 1 2 3 4 5 1 2*1 3*2*1 4*3*2*1 5*4*3*2*1 copy copy copy copy copy 5 4 3 2 1 Fact( ) calls its copy2 with 4 which calls copy3 with3 and so on. The copy5 returns 1, copy4 returns 2*1, copy 3 returns 3*2*1 and finally 5! Is returned. THE FIBONACCI NUMBER BY RETURSION We have already written a program to display the Fibonacci series. Now we will use recursion to display the series. Mathematically the Fibonacci series can be written as. F(1) =1 F(2) =1 F(n) =F(n-2) + F(n-1) for n>2 \* *\ main( ) { int fab(int); int n; for(n=1; n<=10; n + +) printf("%d", fab(n)); } int fab (n) { if (n= =1 | | n= =2) return 1;

Page 70: C programming

C FOR ENGINEERS R.G.Salokhe

else return fab(n-1) + fab(n-2); } Output 1 1 2 3 5 8 13 21 34 55 /* */ /* reversing a string with recursion */ main( ) { int n; void reverse ( ); printf("Type no of characters to reverse"); scanf("%d",&n); printf("\n"); reverse(n); puts("\n"); } void reverse(int n) { char c; if(n= 1){ c= getche( ); puts("/n"); putch(c); } else { c=getche( ); reverse(- -n); putch(c); } return; } Input 5 abcde Output edcba here we call the same function reverse before it is completed in the else block. The putch(c) in the else is thus kept pending. When n becomes 1 the last copy of reverse is complete and the function start returning. At the time of returning the pending putch( ) is executed which prints the characters typed by you in reverse order.

Page 71: C programming

C FOR ENGINEERS R.G.Salokhe

THIS IS ALL I HAVE WRITTEN ON C FOR OTHER BOOKS WRITTEN BY ME PLEASE VISIT http://www.geocities.com/arutacomp/ or mail me on [email protected] The books available are 1] AutoCAD 2007 – The third dimension 2] Visual Basic 6 – from bottom to top 3] MS-ACCESS Thank you.


Recommended