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

Module-2 Notes

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Module-2 Notes

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Managing Input and Output Operation

- C support many input and output statements.


- It also supports 2 classes of input and output.
 Unformatted : getchar( ), getch( ), putchar( ), putch ( )
 Formatted : scanf( ) and printf ( )

Unformatted Input/Output statements

getchar( ):
- It reads one character from the standard input.
- Syntax : variable_name = getchar( )
- Example: char c;
….
c=getchar();
- A dummy getchar( ) is used to eat unwanted characters given as input

putchar( ):
- It writes one character to the standard output (Monitor).
- Syntax : putchar(variable_name/ character constant)
-
Example: char c;
c=”A”;
putchar(c);

Formatted Input:

Scanf( )

- Syntax : scanf (“control string”, argument list);


- Accepts the input from keyboard
- Can be used to enter any combination of numerical values, single character and strings. –
- returns the number of data items that have been entered successfully.
Syntax: scanf( control string, arg1, arg2,….argn)
- control string: consist of control characters, whitespace characters and nor-whitespace
characters. The control characters are preceded by a % sign and are listed below.

Control Character Explanation


%c A single character
%d A decimal integer
%i An integer
%e, %f, %g A floating-point number
%o An octal number
%s A string
%x A hexadecimal number
%p A pointer
%n An integer equal to the number of characters read so far
%u An unsigned integer
%[] A set of characters
%% A percent sign

Example: int i;
float f;
char c;
char str[10];
scanf(“%d %f %c %s”,&I,&f,&c,str);

- format string: must be a text enclosed in double quotes. It contains the information for
interpreting the entire data for connecting it into internal representation in memory.
Example: integer (%d) , float (%f) , character (%c) or string (%s).
- argument list: contains a list of variables each preceded by the address list and separated
by comma. The number of argument is not fixed;
- Inside the format string the number of argument should tally with the number of format
specifier.
- Example: if i is an integer and j is a floating point number, to input these two numbers
we may use
scanf (“%d%f”, &i, &j);
-
- To input integer numbers:
 Format specification: %wd
 % -> conversion character
 w - > an integer number specifying the field width of the number to be read
 Ex: scanf(“ %2d %3d”,&a,&b)
 Input : 50 123
 50 assigned to a and 123 assigned to b
 Unassigned input value will be assigned to next scanf call
 Input data must be separated by spaces

- To input real numbers:


 Format specification: %f
 Field width for real numbers is not specified
 Ex: scanf(“ %f ”,&a)
 Input : 50.123
 50.123 assigned to b

- To input characters:
 Format specification: %wc or %ws
 % -> conversion character
 w - > an integer number specifying the field width of the number to be read
 %[characters] -> only the characters specified within the brackets are permissible
in input data
 %[^characters] -> the characters specified within the brackets are not permissible
in input data
 Ex: scanf(“ %[a-z]c %[^0-9]c”,&a,&b)
 a can take only one letter between a to z
 b can take any character except digits 0-9

Formatted Output printf( ):

- Used to output data onto the screen.


- can be used to output any combination of numerical values, single characters and strings.

Syntax: printf(“control string”, arg1, arg2, ….argn)


- control string:
 characters are listed above (same as input control string)
 Characters that will be printed on the screen as they appear
 Format specifications for output
 Escape sequence characters
- Format specification
 % w.p <type specifier>
- To output integer numbers
 %wd
 W- specifies the minimum field width for output
 If number is greater than the width, prints the whole number
 Number is printed right justified
 Leading spaces appear as blanks
 %-wd : prints the number left justified
 %0wd : leading spaces are padded with 0’s
 %whd : short integers
 %wld : long integers

- To output real numbers


 %w.p f
 w- specifies the minimum field width for output
 p-number of digits to be displayed after the decimal point rounding of to p
decimal places
 If number is greater than the width, prints the whole number
 Number is printed right justified
 Leading spaces appear as blanks
 %-wd : prints the number left justified
 %0wd : leading spaces are padded with 0’s
 %whd : short integers
 %wld : long integers

Example: printf(“%d %o %x\n”, 100,100,100);


Will print : 100 144 64

functions supported by C:

- “ctype.h” header file support all the below functions in C language

isalpha( )
 checks whether given character is alphabetic or not.
 Returns TRUE or FALSE accordingly
isspace()
 checks whether character is space or not.
isupper()
 checks whether character is an uppercase character or not.
islower()
 checks whether character is a lowercase character or not.
ispunct()
 checks whether character is a punctuation character or not.
 Punctuation characters are , . : ; ` @ # $ % ^ & * ( ) < > [ ] \ / { } ! | ~ - _ + ? = ' "
isprint()
 checks whether character is printable or not.
toupper()
 returns character in upper case.
tolower()
 returns character in lower case.

Decision making and Branching:


if statement

- a powerful decision making statement


- used to control the flow of execution of statements.
- basically a two-way decision statement
- used in conjunction with an expression.
- The if statement may be implemented in different forms depending on the complexity of the
conditions to be tested.
1. Simple if statement
2. if...else statement
3. Nested if...else statement
4. else if ladder.

Simple if statement

- syntax:
if (test Example:
expression) false ..........
Test
{ if (x == 1)
exp ?
statement-block; {
} y = y +10;
statement-x; }
true
Statement Block
printf("%d", y);
.........

Statement - X

- The statement-block may be a single statement or a group of statements.


- If the test expression is true, the statement-block will be executed;
- otherwise the statement-block will be skipped and the execution will jump to statement-x.
- Remember, when the condition is true both the statement-block and the statement-x are
executed in sequence.
- Example:
o The program tests the value of x and accordingly calculates y and prints it.
o If x is 1 then y gets incremented by 1 else it is not incremented
o if x is not equal to 1. Then the value of y gets printed
.
The if…else statement
- an extension of the simple if statement.
-
- Syntax
if (test expression)
{
True-block statement(s)
}
else
{
False-block statement(s)
}
statement-x

- If the test expression is true , then the true-block statement(s), immediately following the
if statement are executed;
- otherwise the false-block statement(s) are executed.
- In either case, either true-block or false-block will be executed, not both.
- Example:
........
if (c == 'm')
male = male +1;
else
fem = fem +1;
.......
Nesting of if…else statements

- When a series of decisions are involved, we may have to use more than one if.....else statement
in nested form as follows:
if (test condition1)
{
if (test condition 2)
{
statement-1;
}
else
{
statement-2;
}
}
Else
{
if (test condition 3)
{
statement-1;
}
else
{
statement-2;
}
}
statement-x;

- If the condition-1 is false statement-3 will be executed;


- otherwise it continues to perform the second test.
- If the condition-2 is true, the statement-1 will be evaluated;
- otherwise the statement-2 will be evaluated and then the control is transferred to the
statement-x.

The else if ladder


- There is another way of putting ifs together when multipath decisions are involved.
- A multipath decision is a chain of ifs in which the statement associated with each else is
an if.
- It takes the following general form:
if (condition 1)
statement 1 ;
else if (condition 2)
statement 2;
else if (condition 3)
statement 3;
else if (condition n)
statement n;
else
default statement;
statement x;

-
- This construct is known as the else if ladder.
- The conditions are evaluated from the top (of the ladder), downwards.
- As soon as a true condition is found, the statement associated with is executed and the
control is transferred to the statement x (skipping the rest of the ladder).
- When all the n conditions become false, then the final else containing the default
statement will be executed.

The Switch statement: C has a built-in multi-way decision statement known as a switch. The
switch statement tests the value of a given variable (or expression) against a list of case values
and when a match is found, a block of statements associated with that case is executed. The
expression is an integer expression or characters.Value-1, value-2….are constants or constant
expressions and are known as case labels. Each of these values should be unique within a switch
statement. Block-1 , block-2…are statement lists and may contain zero or more statements.
There is no need to put braces around these blocks. Case labels end with a colon (: ).
When the switch is executed, the value of the expression is successively compared against the
values value-1, value-2,…If a case is found whose value matches with the value of the
expression, then the block of statements that follows the case are executed.

switch (expression)
{
case value-1;
block1
break;
……
……
default:
default-block
break;
}
statement-X;
The break statement at the end of each block signals is the end of a particular case and causes an
exit from the switch statement, transferring the control to the statement-x following the switch.
The default is an optional case. When present, it will be executed if the value of the expression
does not match with any of the case values. If not present, no action takes place if all natches fail
and the control goes to the statement X.

What is difference between switch and if-else?


 Simply saying, IF-ELSE can have values based on constraints where SWITCH can have
values based on user choice.
 The main difference between switch - case and if - else is we can't compare variables. In the
if - else, first the condition is verified, then it comes to else whereas in the switch - case first
it checks the cases and then it switches to that particular case.
 The switch branches on one value only, whereas the if-else tests multiple logical expressions.
So you could say that the switch is a subset of if-else.
The potential difference if that switch is conceptually an N-way branch point, whereas
the if-else is always a (repeated) binary branch.

The conditional operator: The conditional operator is useful for making two-way decisions.
This operator is a combination of ? and : and takes three operands. The general form of use of the
conditional operator is as follows.

conditional expression ? expression1: expression2

The conditional expression is evaluated first. If the result is nonzero, expression1 is evaluated
and is returned as the value of the conditional expression. Otherwise, expression2 is evaluated
and its value is returned. For example
the segment

if ( x < 0)
flag = 0;
else
flag =1;
can be written as flag = ( x < 0 )? 0 :1;

Example2.
Y = 1.5x + 3 for x  2
Y = 2x +5 for x >2
Y = ( x >2 ) ? (2*x +5): (1.5*x+3);
The conditional operator may be nested for evaluating more complex assignment decisions.
4x +100 for x < 40
Example: salary = 300 for x =40
4.5x + 150 for x > 40
Salary = ( x!=40)? ((x<40)? (4*x+100): (4.5*x+150):300;
The same can be evaluated using if … else statement as follows
if (x < = 40)
if ( x< 40)
salary = 4*x+100;
else
salary = 300;
else
salary = 4.5*x + 150;
List of simple programs:

1. Write a C program to check whether a given number is even or odd.


2. Write a C program to check whether a given number is positive or negative.
3. Write a C program to find biggest of two numbers.
4. Write a C program to check whether a given year is leap year or not.
5. Write a C program to find square root of a negative number.
1. Write a C program to find sum of first and second digit of a two digit number.
2. Write a C program to find distance given the time and velocity.
3. Write a C program to calculate salary given BASIC, DA, HRA and IT

You might also like