c hands-on_day3

21
C Programming- Day 1 Programming: The next step after developing an algorithm Once we develop the algorithm, we need to convert it into a computer program using a programming language (a language used to develop computer programs). A programming language is entirely different from the language we speak or write. However, it also has a fixed set of words and rules (syntax or grammar) that are used to write instructions for a computer to follow. Programming languages can be divided into three types. They are: 1. Machine language This is the basic language understood by a computer. This language is made up of 0’s and 1’s. A combination of these two digits represents characters, numbers, and/or instructions. Machine language is also referred to as binary language. 2. Assembly language This language uses codes such as ADD, MOV, and SUB to represent instructions. These codes are called mnemonics. Though these codes have to be memorized, assembly language is much easier to use than machine language. 3. High-level languages High-level languages such as BASIC, FORTRAN, C, C++, and JAVA are very much easier to use than machine language or assembly language because they have words that are similar to English.  A quick comparison of programming languages Machine Language Assembly Language High-level Languages Ti me to execute Since it is t he basi c language of the computer, it does not require any translation, and hence ensures better machine efficiency. This means the programs run faster. A program called an  ‘assembler’ is required to convert the program into machine language. Thus, it takes longer to execute than a machine language program. A program called a compiler or interpreter is required to convert the program into machine language. Thus, it takes more time for a computer to execute. Ti me to develop Needs a lot o f skill, as instructions are very lengthy and complex. Thus, it takes more time to program. Simpler to use than machine language, though instruction codes must be memoriz ed. It takes less time to develop programs as compared to machine language. Easiest to use. Takes less time to develop programs and, hence, ensures better program efficiency.

Upload: garima-agrawal

Post on 09-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 1/21

C Programming- Day 1

Programming: The next step after developing an algorithm

Once we develop the algorithm, we need to convert it into a computer program

using a programming language (a language used to develop computer programs).A programming language is entirely different from the language we speak or write.However, it also has a fixed set of words and rules (syntax or grammar) that areused to write instructions for a computer to follow.

Programming languages can be divided into three types. They are:

1. Machine language

This is the basic language understood by a computer. This language is made up of 0’s and 1’s. A combination of these two digits represents characters, numbers,and/or instructions. Machine language is also referred to as binary language. 

2. Assembly language

This language uses codes such as ADD, MOV, and SUB to represent instructions.These codes are called mnemonics. Though these codes have to be memorized,assembly language is much easier to use than machine language.

3. High-level languages

High-level languages such as BASIC, FORTRAN, C, C++, and JAVA are very mucheasier to use than machine language or assembly language because they have

words that are similar to English. 

A quick comparison of programming languages 

MachineLanguage

AssemblyLanguage

High-levelLanguages

Time to execute Since it is the basiclanguage of thecomputer, it doesnot require anytranslation, andhence ensuresbetter machine

efficiency. Thismeans theprograms runfaster.

A program called an ‘assembler’ isrequired to convertthe program intomachine language.Thus, it takeslonger to execute

than a machinelanguage program.

A program called acompiler orinterpreter isrequired to convertthe program intomachine language.Thus, it takes more

time for a computerto execute.

Time to develop Needs a lot of skill,as instructions arevery lengthy andcomplex. Thus, ittakes more time toprogram.

Simpler to use thanmachine language,though instructioncodes must bememorized. It takesless time to developprograms ascompared to

machine language.

Easiest to use.Takes less time todevelop programsand, hence, ensuresbetter programefficiency.

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 2/21

Developing a computer program

Follow the steps given below to become a successful programmer:

1. Define the problem: Examine the problem until you understand it

thoroughly. 

2. Outline the solution: Analyze the problem. 

3. Expand the outline of the solution into an algorithm: Write a step-by-step

procedure that leads to the solution. 

4. Test the algorithm for correctness: Provide test data and try to work out the

problem as the computer would. This is a critical step but one thatprogrammers often forget. 

5. Convert the algorithm into a program: Translate the instructions in thealgorithm into a computer program using any programming language. 

6. Document the program clearly : Describe each line of instruction or at least

some important portions in the program. This will make the program easy tofollow when accessed later for corrections or changes. 

7. Run the program: Instruct the computer to execute the program. The

process of running the program differs from language to language. 

8. Debug the program: Make sure that the program runs correctly without any

errors or bugs as they are called in computer terminology. Finding the errors

and fixing them is called debugging. Don’t get depressed when bugs arefound. Think of it as a way to learn. 

Structure of a C program

Every C program consists of one or more functions. A function is nothing but agroup or sequence of C statements that are executed together. Each C programfunction performs a specific task. The ‘main()’ function is the most importantfunction and must be present in every C program. The execution of a C programbegins in the main() function.

The figure below shows the structure of a C program.

main() function1() function2() 

{ { {

statement1; statement1; statement1;

statement2; statement2; statement2;

……; ……..; ……;

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 3/21

……; ……..; ……;

} } }

Programmers are free to name C program functions (except the main() function). 

Writing your first C program 

The following is a simple C program that prints a message ‘Hello, world’ on thescreen.

1.#include<stdio.h>2.main()3.{4. printf(“Hello, world”);5.}

1. Save the program as hello.c by pressing F2 or Alt + ‘S’. 

2. Press Alt + ‘C’ or Alt + F9 to compile the program.  

3. Press Alt + ‘R’ or Ctrl + F9 to execute the program. 

4. Press Alt + F5 to see the output. 

Understanding the program

The information enclosed between ‘/* */’ is called a ‘comment’ and may appearanywhere in a C program. Comments are optional and are used to increase thereadability of the program.

The ‘#include’ in the first line of the program is called a preprocessor directive. A preprocessor is a program that processes the C program before the compiler. Allthe lines in the C program beginning with a hash (#) sign are processed by thepreprocessor.

 ‘stdio.h’ refers to a file supplied along with the C compiler. It contains ordinary Cstatements. These statements give information about many other functions thatperform input-output roles.

Thus, the statement ‘#include<stdio.h>’ effectively inserts the file ‘stdio.h’ into thefile hello.c making functions contained in the ‘stdio.h’ file available to the

programmer. For example, one of the statements in the file ‘stdio.h’ provides theinformation that a function printf() exists, and can accept a string (a set of characters enclosed within the double quotes).

The next statement is the main() function. As you already know, this is the placewhere the execution of the C program begins. Without this function, your Cprogram cannot execute.

Next comes the opening brace ‘{’, which indicates the beginning of the function.The closing brace ‘}’ indicates the end of the function.

The statement printf() enclosed within the braces‘{}’ informs the compiler to print

(on the screen) the message enclosed between the pair of double quotes. In thiscase, ‘Hello, world’ is printed. As mentioned earlier, the statement printf() is a

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 4/21

built-in function shipped along with the C compiler. Many other built-in functionsare available that perform specific tasks. The power of C lies in these functions.

Be cautious about errors! 

Errors/bugs are very common while developing a program. If you don't detect themand correct them, they cause a program to produce wrong results. There are threetypes of errors — syntax, logical, and run-time errors. Let us look at them:

1. Syntax errors: These errors occur because of wrongly typed statements,

which are not according to the syntax or grammatical rules of the language.For example, in C, if you don’t place a semi-colon after the statement (asshown below), it results in a syntax error. 

printf(“Hello,world”) – error in syntax (semicolon missing)

printf("Hello,world"); - This statement is syntactically correct.

2. Logical errors: These errors occur because of logically incorrect instructions

in the program. Let us assume that in a 1000 line program, if there shouldbe an instruction, which multiplies two numbers and is wrongly written toperform addition. This logically incorrect instruction may produce wrongresults. Detecting such errors are difficult. 

3. Runtime errors: These errors occur during the execution of the programs

though the program is free from syntax and logical errors. Some of the mostcommon reasons for these errors are 

a. when you instruct your computer to divide a number by zero. 

 b. when you instruct your computer to find logarithm of a negative

number. c. when you instruct your computer to find the square root of a

negative integer. 

Unless you run the program, there is no chance of detecting such errors.

Exercise

1. Write a C program to print your name on the screen.

2. Write a C program to print the name of your favorite cricketer.

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 5/21

Data Type

Table 1

Datatype

Memory size(in bytes)

Range

int 2 or 4(depends onwhether youare using 16-bit processor or 32-bitprocessor)

-32,768 to +32767 (2-bytes)

-2,147,483,648 to +2,147,483,648 (4-bytes) 

short 2 -32768 to +32767

long 4 -2,147,483,648 to +2,147,483,648

float 4 ±10 e-37 to ±10e+37

double 8 ±10 e-307 to ±10e+307

char 1 -128 to +127

Declaring variables in a C program

Writing a program to print values in variables 

*/

#include<stdio.h>

main()

{

inta=10;

floatb=3.1412;

charch=’A’;

printf(“%d\n%f\n%c”,a,b,ch);

}

When you run this program, the following output will be displayed on screen:

10

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 6/21

3.1412

A

The characters %d, %f, and %c are called format specifiers or simply format 

strings. The ‘%’ symbol alerts the compiler that a variable is to be printed at thatlocation and the letter that follows tells it to print the value as an int , float , char ,and so on.

The character ‘\n’ is called a newline character. It is used to insert a new line sothat the values in variables mentioned after it are printed on a new line

Characters like the ‘\n’ character that start with ‘\’ are called escape sequences.

The following tables gives you a partial list of format strings and escape

sequences that you will frequently come across in C programs.

Table 2 Table 3

 Experiment to find out what happens

when  printf  's argument string 

contains \c, where c is some character not listed in:

\n (newline)

\t (tab)

\b (backspace)\" (double quote)

\\ (backslash)

#include <stdio.h> 

int main( void ){  printf("Audible or visual alert. \a\n"); printf("Form feed. \f\n");

  printf("This escape, \r, moves the active position to the initialposition of the current line.\n");  printf("Vertical tab \v is tricky, as its behaviour is unspecifiedunder certain conditions.\n");

Sl. No Data type FormatSpecifier 

1. Int d

2. float f 

3. char c4. unsigned int u

5. string s

6. long int ld

7. double lf 

Sl.No

Escapesequence

Purpose

1. \n Newline

2. \t Tab

3. \a Beep

4. \b Backspace

5. \r Return

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 7/21

  return 0;}

3. Calculate Average of marks for five subjects.

#include <stdio.h>main ( ){int ml,m2,m3,m4,m5;int total;float average;printf("Enter the 5 marks..");scanf("%d%d%d%d%d",&ml,&m2,&m3,&m4,&m5);total = ml + m2 + m3 + m4 + m5;average = total / 5.0;

printf("Total=%d average%f\n",total,average);

}

4. Calculate Simple Interest

/* Calculation of simple interest */

main( ){int p, n ;float r, si ;printf ( "Enter values of p, n, r" ) ;scanf ( "%d %d %f", &p, &n, &r ) ;si = p * n * r / 100 ;

printf ( "%f" , si ) ;

}

5. Print the ASCII Code

#include <stdio.h> main ( ){int i; float f; char c; i = 65;f = i; /* f now contains 65.0 */C.= f; /* c contains 65 */

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 8/21

printf("%c ",C);/* prints 'A': the ascii code of 'A' is 65 I */f = f + 0.99;i = f; /* i contains 65 and not 66 I */ /* c becomes 66 */c = c+ 1;printf("%d\n", c+l) ; /* prints 67 */

}

Exercise

1. Write a program to store 10, 12.5, and a character ‘Z’ in integer, float,and character variables respectively and display the values on thescreen.

2. Write a program to store 15, 3,14, and ’X’ in integer, float, and character variables respectively and display the values on separate lines on the

screen.

Input Function

Suppose you develop a piece of software to be used for computerizing a bank’soperations. In the code for this software, you would write a program to storedetails of the bank’s customers. In this program let us assume that you haveused the assignment  operator (refer to the previous article) for storing customer details such as name, age and telephone number in the respective variables.How would you enter the details of a new customer?

You would do this by opening the program, assigning the values to variables,and compiling the program again. However, this is a cumbersome process, asyou have to recompile the program each time that you make a change.Moreover, when using an assignment operator , you may not know in advancethe values that you want to assign to the variables.

Data and input functions 

Almost every program should include statements used to request input from userswhile the program is running. Such statements are called input statements. The Ccompiler has built-in input functions for storing data (entered through a keyboard)in variables while the program is running. These input functions facilitateinteractive programming, i.e., you can interact with a running program. One suchwidely used function in C is scanf(). 

The scanf() function

The syntax of scanf() and that of printf() look alike except that an ‘&’ symbolprecedes every variable in the case of scanf(). This function is used to inputdifferent kinds of values — int, float, and char.

Use of the scanf() function

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 9/21

main()

{

1. int a;

2. float b;

3. char c;

4. printf(“Enter an integer:”);

5.  scanf(“%d”,&a);

6. printf(“Enter a float:”);

7.  scanf(“%f”,&b);

8. printf(“Enter a character:”);

9.  scanf(“%c”,&c);

10. printf(“You entered %d %f %c”, a, b, c);

}

Other input functions 

Apart from the scanf() function, there are also other functions such as getchar()and gets() to store characters and strings (set of characters). The followingprogram demonstrates the use of these functions.

#include<stdio.h>

main()

{

1. char a;

2. printf (“Enter any character:”);

3. a=getchar();

4. printf(“The character you entered is:%c”,a);

}

Observe how the function getchar() is used in this program. This function

receives a character entered by the user and stores it in the variable a. Theprintf() function written below the getchar() statement displays on the

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 10/21

screen the character that you entered from the keyboard. C, however, alsoprovides a function called putchar() to display the character on the screen. Youcan use this function in the above program instead of  printf(). The followingstatement is written to use putchar() in the above program.

putchar(a);

 

Accepting strings using gets() function

The program that displayed a string (Hello, World) on the screen use theprintf() function. Now see how to accept a string from keyboard and display it.

#include<stdio.h>

main()

{

char a[25];

printf (“Enter a string:”);

gets(a);

printf (“%s”,a);

}

 

In this program:

The first statement — char a[25]; — informs the compiler to setaside 25 locations to store 25 characters.

The second statement prompts the user by displaying the message “Enter a string” on the screen. 

The third statement accepts the string from the keyboard.  

The fourth statement displays the string that you entered on thescreen. 

%s stands for ‘format string’ to print strings. 

You can also get the same result for the above program by using another kind of output function, puts(). This function is used exclusively for handling strings. It

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 11/21

can’t be used for printing numeric data. The following statement would bewritten to use puts() in the above program. 

puts(a);

 

Exercise

1. Write a program to accept and store the values 15, 30.5 and ‘A’ in thevariables i, f, and c using the function scanf(), and to display them usingthe printf() function.

2. Write a program to accept and store a character (say, ‘$’) in the variablech using the function getchar() and t display it on the screen using the

function putchar().

3. Write a program to accept and store a string (say, “Hi-Tech City”) in thevariable city and to display it on the screen using the function puts().

 

MORE ON I/O

character I/O – getchar() and putchar()

The function getchar does not take any parameters. When it is called, it readsa character from the standard input device, and returns an integer valuecorresponding to the ASCII code of the input char. If no input is availablegetchar returns a special value called EOF.

 putchar is the twin of getchar and does the complementary job: it prints a char to the

standard output device. The char which is to be printed will have to be passed as

 parameter to putchar.

use of getchar and putchar 

#include <stdio.h>main ( ){int c;printf ("Enter an uppercase letter");

c = getchar();/* parenthesis needed even if no parameter I */

printf("Lowercase=”);

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 12/21

putchar(c + 32);

}

putchar('A') ;putchar (65); /* int and char can be mixed in c */

putchar('A' + 5); /* prints 'F' : char can take part in arithmetic ! */

Since putchar takes an int as a parameter, you can pass to it either an intconstant (like 65) or an int variable, or an integer expression, or a function thatreturns an integer (for example getchar).

Writing programs to process data 

Mathematical operators

In C, arithmetic operations (addition, subtraction, multiplication, division, andmodulo division) are performed using five arithmetic operators:.

1. + - Addition

2. - - Subtraction

3. * - Multiplication

4. / - Division

5. % - Modulo Division (remainder after integer division)

#include<stdio.h>

main()

{

1. int a=5,b=2; float c;

2. printf(“Addition\n”);

3. c=a+b;

4. printf(“Result=%f\n”,c);

5. printf(“Subtraction\n”);

6. c=a-b;

7. printf(“Result=%f\n”,c);

8. printf(“Multiplication”);

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 13/21

9. c=a*b;

10. printf(“Result=%f\n”,c);

11. printf(“Division\n”);

12. c=a/b;

13. printf(“Result=%f\n”,c);

}

When you run this program, you will see this:

 

Addition

Result=7.000000

Subtraction

Result=3.000000

Multiplication

Result=10.000000

Division

Result=2.000000

Observe the last output. The result of division is displayed as 2.000000 instead of 2.500000! What is the reason for this? Let us find out.

Division works differently for ints and floats. Floating-point division results in afloat, and integer division results in an int. In this example, the two variablesinvolved in the division calculation are of integer type, and hence the result is aninteger. In C, any fraction resulting from an integer division is ignored. This processis called truncation. This can be avoided using a mechanism called typecasting.

Typecasting 

Typecasting allows you to convert the value of an expression to a particular datatype. If you want the result of 5/2 in the above example as 2.5, you must type thecode in line 12 as follows:

c= (float) a/b;

A pair of parentheses with a data type written inside is known as C’s cast operator.To print the output correctly, remember to change the format string in the printf()statement on line 13 from %d to %f.

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 14/21

SPECIAL OPERATORS

C provides a number of operators which perform various operations.

+ + serves as the increment operator in C and -- serves as the decrement

operator.

The increment and decrement operators are available in two forms:1. The prefix form and 2. the postfix form. That is, if you have an int variable byname count, and you want to increment it, you can achieve this either by saying++countor by saying

count++;

Difference between the two forms

int a = 50, b = 100;a = ++b /* now both a and b contain 101 I*/b = a++; /* now b contains 101 whereas a's value is 102 I*/printf("%d\n", ++a) /* printf is going to print 103 now */

printf("%d\n", a++) /* prints 103 again I; but a has become 104 */

C provides a number of operators which can be expressed in the general formop=Where op is an operator like +,., *, I, % etc.So you have operators like + = , - = , * = ,= and so on. In general, an expression likesvar op= value;is interpreted as

var = var op value;

So

Temperature += 5;is actually equivalent to saying

Temperature = Temperature + 5;

Total *= i; /* Total = Total * i ; */Count 1; /* Equivalent to Count */

These operators serve a number of purposes:1. They provide a short hand notation, which once clearly understood andmastered, reduce the number of key strokes.

2. They reduce the possibility of spelling errors (since you do not have to specifythe variable name on both sides of the assignment operator).

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 15/21

3. Last but definitely not the least: They often result in better object code.

Expressions and operator precedence

What is an expression?  

If you have done some basic math, you would have heard of expressions. Anexpression consists of a combination of operators and operands (values on whichan operator operates on). For example

c=a+b;

or

x=a*(b/c+d*3)+5;

operands can be constants, variables, or combinations of the two.

In C, arithmetic expressions are evaluated according to a strict hierarchy of operators. Given below is the hierarchy of arithmetic operators in C:

Priority Operators Description

1st * / % multiplication, division, modulo division

2nd + - addition, subtraction

3rd = Assignment

If there are two operators of the same level in an expression, the operator thatcomes first is considered first — ‘first come, first served ’.

 /* Demo of operator precedence */

#include<stdio.h>

main()

{

1. int a=10,b=20,c=15,d=5,result;

2. result=a+b%5-c*d/2;

3. printf(“Result=%d”,result);

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 16/21

}

 

When you run this program you will see this:

Result=-27

Let us see how you got this result.

The expression result= a+b%5-c*d/2 is evaluated as follows:

result=10+20%5-15*5/2

1. result=10+0-15*5/2 % is evaluated first. The remainder is 0 when5 divides 20.

2. result=10+0-75/2 Multiplication is performed. 15*5=75.

3. result=10+0-37 Division is performed. (75/2 results in 37 instead of 37.5

because both 75 and 2 are integers.

4. result=10-37 Addition is performed because it comes beforeminus.

5. result=-27 Finally subtraction is performed and –27 isstored in the variable result.

 Exercise: 

1. Write a program to accept the marks of a student in three subjects, and

display the total marks and the average. 

2. Write a program to accept basic salary, HRA, DA and PF and display the net

salary. (Hint: Net salary is computed as: Basic+HRA+DA–PF). 

3. Write a program to accept the radius of a circle and display its radius and

perimeter. (Hint: area=∏*r*r; perimeter= 2*∏*r) 

Relational Operators

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 17/21

1. Relational operators are used in Boolean conditions or expressions.2. Boolean conditions or expressions return either true or false.3. The relational operator returns zero values or nonzero values.

4. The zero value is taken as false while the nonzero value is taken as true.

1. The relational operators are as follows: <, <=, >, >=, ==, !=.

2. The priority of the first four operators is higher than that of the later two operators.

Boolean Operator in C

Character SetBoolean Operator 

&& and

|| or  

&& Operator 

1. && operator: evaluate a Boolean expression from left to right.

2. Both sides of the operator must evaluate to true before the entire expression becom

|| Operator 

1. || operator: evaluate from left to right.2. If either side of the condition is true, the whole expression results in true.

Logic Operator OR ||

#include <stdio.h> int main(){  char c; 

printf("Y/y?");  c=getchar();  if(c=='Y' || c=='y')  {  printf("Bye!\n");  }

  else  {  printf("Okay!\n");  }  return(0);}

logic operator and (&&)

#include <stdio.h>int main( void )

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 18/21

{  char letter =0;

printf("Enter an upper case letter:");scanf(" %c", &letter);

if ((letter >= 'A') && (letter <= 'Z')){

  letter += 'a'-'A';printf("You entered an uppercase %c.\n", letter);

  }  else

  printf("You did not enter an uppercase letter.\n");  return 0;}

Practice Questions

1. Modify the temperature conversion program to print a heading above the table.

#include <stdio.h> 

int main( void ){  float fahr, celsius;  int lower, upper, step;

  lower = 0;  upper = 300;  step = 20;

  printf("F C\n\n");  fahr = lower;  while(fahr <= upper)  {  celsius = (5.0 / 9.0) * (fahr - 32.0);  printf("%3.0f %6.1f\n", fahr, celsius);  fahr = fahr + step;  }

  return 0;}

2. Write a program to print the corresponding Celsius to Fahrenheit table.

#include <stdio.h> 

int main( void ){  float fahr, celsius;  int lower, upper, step;

  lower = 0;

  upper = 300;  step = 20;

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 19/21

  printf("C F\n\n");  celsius = lower;  while(celsius <= upper)  {  fahr = (9.0/5.0) * celsius + 32.0;

  printf("%3.0f %6.1f\n", celsius, fahr);  celsius = celsius + step;  }  return 0;}

Verify that the expression getchar() !=  EOF  is 0 or 1

#include <stdio.h> 

int main( void ){

  printf("Press a key. ENTER would be nice :-)\n\n");  printf("The expression getchar() != EOF evaluates to %d\n",getchar() != EOF);  return 0;}

Write a program to print the value of EOF.

#include <stdio.h> 

int main( void ){  printf("The value of EOF is %d\n\n", EOF);

  return 0;}

Write a program to count blanks, tabs, and newlines.

#include <stdio.h> 

int main( void ){  int blanks, tabs, newlines;  int c;

 int

 done = 0;  int lastchar = 0;

  blanks = 0;  tabs = 0;  newlines = 0;

  while(done == 0)  {  c = getchar();

  if(c == ' ')  ++blanks;

  if(c == '\t')  ++tabs;

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 20/21

  if(c == '\n')  ++newlines;

  if(c == EOF)  {

 if(lastchar != 

'\n')  {

  ++newlines; /* this is a bit of a semantic stretch, but itcopes

* with implementations where a text file mightnot

* end with a newline. Thanks to Jim Stad forpointing

* this out.*/

  }  done = 1;  }

  lastchar = c;  }

  printf("Blanks: %d\nTabs: %d\nLines: %d\n", blanks, tabs, newlines);  return 0;}

Write a program to copy its input to its output, replacing each stringof one or more blanks by a single blank.

#include <stdio.h> 

int main( void ){  int c;  int inspace;

  inspace = 0;  while((c = getchar()) != EOF)  {  if(c == ' ')  {  if(inspace == 0)  {  inspace = 1;  putchar(c);  }  }

  /* We haven't met 'else' yet, so we have to be a little clumsy */  if(c != ' ')  {  inspace = 0;  putchar(c);  }  }

  return 0;}

Write a program that prints its input one word per line.#include <stdio.h> 

8/8/2019 C Hands-on_Day3

http://slidepdf.com/reader/full/c-hands-onday3 21/21

int main( void ){  int c;  int inspace;

  inspace = 0;

 while

((c = getchar()) != EOF)  {  if(c == ' ' || c == '\t' || c == '\n')  {  if(inspace == 0)  {  inspace = 1;  putchar('\n');  }  /* else, don't print anything */  }  else

  {

  inspace = 0;  putchar(c);

  }  }  return 0;}

Write a program to determine the ranges of char , short , int , andlong variables, both signed and unsigned , by printing appropriatevalues from standard headers and by direct computation. Harder if youcompute them: determine the ranges of the various floating-pointtypes.

#include <stdio.h> 

#include <limits.h> 

int main (){  printf("Size of Char %d\n", CHAR_BIT);  printf("Size of Char Max %d\n", CHAR_MAX);  printf("Size of Char Min %d\n", CHAR_MIN);  printf("Size of int min %d\n", INT_MIN);  printf("Size of int max %d\n", INT_MAX);  printf("Size of long min %ld\n", LONG_MIN);  /* RB */  printf("Size of long max %ld\n", LONG_MAX);  /* RB */  printf("Size of short min %d\n", SHRT_MIN);  printf("Size of short max %d\n", SHRT_MAX);  printf("Size of unsigned char %u\n", UCHAR_MAX);  /* SF */  printf("Size of unsigned long %lu\n", ULONG_MAX); /* RB */  printf("Size of unsigned int %u\n", UINT_MAX);  /* RB */  printf("Size of unsigned short %u\n", USHRT_MAX); /* SF */

  return 0;}