The if statement within the body of the for loop is used to print a comma after each value of the loop variable except the last one. [Read more…] about C Program Print a comma-separated list of numbers from 1 to 10
What is the difference between IF-ELSE and SWITCH?
Both the switch and if-else-if statements enable us to select one of several alternative statements for execution. However, they differ in several aspects: [Read more…] about What is the difference between IF-ELSE and SWITCH?
C Program Examination result in a single subject with data validation
The program segment given below accepts marks in a single subject and uses a nested if statement to determine the validity of marks and the result if the value of marks is valid. This code can be written in a more readable form using an if-else-if statement as [Read more…] about C Program Examination result in a single subject with data validation
C Program Character test letter, vowel, consonant
The program segment given below uses a nested if statement to determine whether a given character is a letter or not. In addition, if the given character is a letter, it tests whether it is a vowel or consonant. [Read more…] about C Program Character test letter, vowel, consonant
Nested if Statements in C Language
The C language allows nested if statements in which the if block and/or else block of an if statement contains if or if-else statements. The inner if statement(s) may in turn contain other if statements and so on.
Two-Level Nested if Statements
Consider the general form of the if else statement given below.
if (expr)
statement1 ;
else statement2 ;
The general form of a two-level nested if statement obtained by replacing both statement1 and statement2 in the above form with the if-else statement itself is given below.
Observe how the inner if-else statements are indented (shifted to the right) to improve readability. Also note that since the if block and else block of the outer if-else statement comprise a single if-else statement, they need not be included within braces. However, we can surround inner if-else statements with braces to improve readability as illustrated in the right-hand side form. As explained earlier, the use of such braces also prevents errors when we add one or more statements to these if and else blocks.
The flowchart for this general two-level nested if statement is given in Fig a. Observe that only one of the four alternative statements (statement}, statement2, statement3, statement4) will be executed depending on the values of the test expressions expr1, expr2 and expr3. Also note that these alternative statements can be any valid C statement such as a simple statement (assignment, function call, etc.), control statement or compound statement. The execution of this statement is as follows: Initially, expr1 is evaluated. If it is true (non-zero), expr2 is evaluated and depending on its value, either statement1 or statement2 is executed, i. e., if expr2 is true, statement] is executed; otherwise, statement2 is executed. After execution of either statement1 or statement2, the control leaves nested if statement. Note that expr3 is not evaluated in this case.
On the other hand, if expr1 evaluates as false, expr3 is evaluated and depending on its value, either statement3 or statement4 is executed. After execution of either statement, control leaves the nested if statement. Note that expr2 is not evaluated in this case.
Other Forms of Two-Level Nested if Statements
Consider that either the if block or the else block in the general form of the if-else statement is replaced with an if-else statement, but not both. Now we have two other forms of two-level nested if statement, as shown below.
The flowcharts for these statements are given in Fig b and Fig c, respectively. The second form which contains an if-else statement only in the else part is called as if else- if statement and is explained shortly in detail.
As the else block in an if-else statement is optional, we can omit the else blocks in the inner if statements to obtain several additional forms of the two-level nested if statement. However, while writing such statements we need to remember the following rule of nested if statements: An else clause is associated with the nearest if statement that is not already associated with an else clause.
If we omit the else clause in the inner if statements of a general two-level nested if statement, we get two other forms given below and illustrated in Fig.
Note that braces are required around the inner if statement in the first format for correct interpretation that the else-clause of the inner if statement is omitted, as illustrated in Fig. In the absence of these braces, the else clause of the outer if statement becomes incorrectly associated with the inner if statement. Also note that we do not require such braces in the second case.
Two other forms of two-level nested if statements are given below. In the first form, the else clause of the outer if statement is omitted. Whereas, in the second form, the else clause of the outer and inner if statements are omitted.
Illustrates nested if (expressions)
#include <stdio.h>
void main ()
{
float A, B, C;
clrscr();
printf("Enter two integers.");
scanf ("%f %f", &A, &B );
printf("You have entered the following two numbers.\n");
printf("A = %.3f\t B = %.3f \n", A, B );
if (A!=B)
{
if (A >B)
printf("A is greater than B.\n");
if (A<=B)
printf("A is less than or equal to B.\n" ); }
C = (A+ B)/2;
printf("%.3f is mean of the two numbers %.3f and %.3f\n",C,A,B);
}
C Program Reverse digits in an integer number
The program segment given below obtains a number by reversing the digits in the given number.
scanf(“%d”, &num);
rev_num = 0;
do {
digit = num % 10;
rev_num = rev_num * 10 + digit;
num /= 10;
} while(num > 0);
printf(“reverse number= %d”, rev_num);
This program segment first accepts a number num from the keyboard and initializes variable rev_ num to zero. Then it uses a do…while loop to separate the digits in num and construct number rev_num in reverse order of digits, one digit at a time. Observe carefully the statement used to obtain the reversed number:
rev_num = rev_num * 10 + digit;
In this statement, the current value of rev_num is first multiplied by I0 and the value of digit is added to it. The steps in the formation of the reverse number are illustrated below for num = 1234.
The code to determine the reverse number can also be written using the while loop. The code given below avoids use of variable digit. The I/O statements are omitted to save space.
rev_num = 0;
while (num > 0) {
rev_num = rev_num * 10 + num % 10;
num /= 10;
This code can be made more concise using the for loop as shown below.
for (rev_num = 0; num > 0; num /= 10)
rev num = rev num * 10 + num % 10;
C Program Determine sum and average of several numbers entered from the keyboard.
The program segment given below using a do …while loop and then determines the average of the given numbers.
#include <stdio.h>
void main()
{
int n,i;
float sum,x,avg;
clrscr();
printf(“How many numbers? “);
scanf(“%d”, &n);
sum = 0.0;
i = 0;
do {
scanf(“%f”, &x);
sum += x;
i++;
}while (i < n);
avg = sum/ n; /* sum is assumed to be of type float */
printf (“The Sum is = %f \n”,sum);
printf (“The Average is = %f \n”,avg);
getch();
}
C Program Accept data from the keyboard until correct data is entered
As a good programming practice, we display a message to prompt the user before accepting data from the keyboard. This enables the user to enter the required data correctly. However, the user may still enter incorrect data. Such data may cause the programs to print incorrect results.
One way to handle this problem is to print an error message and stop the program execution when incorrect data is encountered. However, the user will usually expect the program to discard incorrect data and allow him/her to reenter correct data. We can implement code to achieve this using a do…while loop. Consider the program segment given below.
do
printf (“Enter marks (0..100): “);
scanf(“%d”, &marks);
while (marks< 0 || marks> 100);
This loop prints a message and accepts marks from the keyboard as long as the marks entered are incorrect (either less than zero or greater than l 00). The control leaves the loop only when the user enters valid marks (in the range 0 to 100). The output is shown below, where the user has entered two incorrect values (120 and -20) before entering the correct value (90).
Example:
#include <stdio.h>
void main()
{
int marks;
clrscr();
do
{
printf (“Enter marks (0..100): “);
scanf(“%d”, &marks);
} while (marks< 0 || marks> 100);
printf (“The Marks = %d \n”,marks);
getch();
}
C Program Sum of Digits of a Given Integer Number with do-while loop
A program to determine the sum of digits of a given non-negative integer number using a while loop is presented in Program. The program segment given below does the same thing using a do…while loop. [Read more…] about C Program Sum of Digits of a Given Integer Number with do-while loop
do … while Loop in C
The while loop is particularly suitable when the number of iterations is not known or can not be determined in advanced. In this section, another loop that is useful in similar situations, the do … while loop is discussed.
In case of a do …while loop, it is a exit-controlled or bottom-tested loop as opposed to the while loop which is entry-controlled or top-tested. The do and while commands are separated by one statement. If it is required to include more statements they should be included between a pair of curly brackets to present them as a single block of statements, otherwise the compiler will send out an error message. In a program, do is placed at the top of the statements and while is placed at the bottom of statements. The test is carried out after the execution of statements in the while expression, i.e., at bottom of loop. The statements are executed from top to bottom. Therefore, even if the while expression evaluates false, at least one computation is carried out.
Thus, the statement(s) within a do … while loop will be executed at least once, whereas the statement(s) within a while loop may not be executed at all. The general syntax of the do…while loop is given below.
do
statement;
while ( expr) ;
where expr is the loop control expression that may be any valid C expression such as arithmetic, relational or logical and statement is the loop body that is to be executed repeatedly. The body of the do…while loop may comprise a compound or a block statement as shown below.
do
{
statement;
statement ;
………
}while ( expr ) ;
The flowchart for the do … while loop is given in Fig. When the loop is entered, the statement(s) within the loop are executed and then expression expr is evaluated. If the value of expr is true (non-zero), the body of the loop is executed again; otherwise, control leaves the loop. Thus, the body of the loop is executed until expression expr evaluates as true (non-zero). Note that the statements within the do … while loop loop will be executed at least once.
Although the for loop is more suitable in situations where the number of iterations are known or can be determined in advance, we can also use the do … while loop in such situations. This can be done as follows:
initial_expr ;
do {
statement;
update_expr ;
} while (final_expr ) ;
However, remember that this is not equivalent to the for loop given below as the do…while loop is bottom-tested, whereas the for loop is top-tested.
for ( initial_expr ; final_expr ; update_expr)
statement;
Illustrates do-while loop
#include <stdio.h>
void main()
{
int i =5, m=0,n=0;
clrscr();
printf("i\t m\t n\n");
do
{
m =i*i;
n = i*i*i;
printf("%d\t %d\t %d\n", i, m, n );
i--;
}
while(i<=2 );
}
The output given below shows that even though the condition is false, the program has been executed once.
C Program for GCD using Euclid’s algorithm
Let us use variables m and n to represent two integer numbers and variable r to represent the remainder of their division, i. e., r = m % n. Euclid’s algorithm to determine the GCD of two numbers m and n is given below and its action is illustrated form= 50 and n = 35. [Read more…] about C Program for GCD using Euclid’s algorithm
C Program Sum of Digits of a Given Integer Number
we determined the sum of digits of a non-negative integer number by determining the least significant digit and then removing it from given number.
In this example, we generalize this technique to determine the sum of digits of any non-negative integer number. To separate the digits of given number num, we can use a while loop as shown below:
while (num > 0)
digit = num % 10;
num /= 10;
In each iteration of this loop, the least significant digit of number num is separated in variable digit and then removed from the given number. The statements within this loop are executed as long as the value of num is greater than zero, i. e., as long as the number contains one or more digits.
Note that the value of digit will be modified in subsequent iterations. Thus, we should immediately add it to variable sum used to store the sum of digits. The variable sum should be initialized to zero before the loop. The program segment given below determines the sum of digits of the number num: ·
sum = 0;
while (num > 0)
digit = num % 10;
sum += digit;
num /= 10;
Note that this program works correctly even if the given number is zero. The complete program given below accepts a number from the keyboard, determines the sum of its digits and prints the sum.
#include <stdio.h>
void main()
{
int num,digit,sum;
clrscr();
printf(“Enter positive numbers:\n”);
scanf(“%d”,&num);
sum=0;
while (num > 0)
{
digit = num % 10;
sum += digit;
num /= 10;
}
printf (“Sum Digit = %d “, sum);
getch();
}
Add numbers until a negative or zero is encountered
The program segment given below accepts numbers from the keyboard until we enter a zero or a negative number and calculates their sum excluding the last number. [Read more…] about Add numbers until a negative or zero is encountered
Money payment: add numbers until desired sum is obtained
Consider that we have to add the given numbers until the desired sum is obtained (i. e., as long as the sum is less than a specified value).
This is required in many situations. For example, to pay a shopkeeper for the goods purchased, we can continue to give one currency note at a time as long as the amount being given is less than the desired amount. Such a sum can be calculated using a while loop as shown below.
printf(“Enter payment to be made: “);
scanf(“%d”, &payment);
printf(“Enter currency note values:\n”);
sum = 0;
while (sum < payment)
{
scanf (“%d”, &value);
sum += value;
}
printf(“\n Amount payable: %d Amount paid: %d\n”, payment, sum);
Initially, the value of the amount to be paid is accepted from the keyboard in variable payment (of type int).Then variable sum is initialized to zero and a while loop is setup to execute its body as long as the value of sum is less than payment. The statements within the body of the loop accept a number (value of next currency note) from the keyboard and add it to sum. The program containing this code segment is executed once and the output is given below.
Enter payment to be made: 125
Enter currency note values:
100
20
10
Amount payable: 125 Amount paid: 130
Observe that we have pressed the Enter key after each value of currency note. As a result, the program accepts only the required data values and displays the sum of entered numbers when sum exceeds payment. If we enter the currency note values separated by spaces we might sometimes get an output that looks wrong, similar to one shown below.
Enter payment to be made: 125
Enter currency note values:
100 20 10 10 10
Amount payable: 125 Amount paid: 130
However, this output is correct. Actually, the last two numbers were not processed by the program as the desired sum was obtained after the third number. This can be easily verified by printing the numbers read from the keyboard within the while loop as shown below (only the while loop is shown to save space):
while (sum < payment) {
scanf (“%d”, &value);
printf(“%d “, value);
sum += value;
The output of the modified program is given below. Observe that after we press the Enter key, the program first prints the three values processed by it followed by the result.
Enter payment to be made: 125
Enter currency note values:
JOO 20 10 10 10
100 20 10
Amount payable: 125 Amount paid: 130
Note that the code to calculate the sum can be written concisely using the for loop as shown below.
printf(“Enter currency note values:\n”);
for (sum = 0; sum < payment; sum += value)
scanf(“%d”, &value);
Example: Money payment: add numbers until desired sum is obtained
#include <stdio.h>
void main()
{
int payment,sum,value;
clrscr();
printf(“Enter payment to be made: “);
scanf(“%d”, &payment);
printf(“Enter currency note values:\n”);
sum = 0;
while (sum < payment)
{
scanf (“%d”, &value);
sum += value;
}
printf(“\nAmount payable: %d Amount paid: %d\n”, payment, sum);
getch();
}
while loop in C
The while loop is particularly useful when the number of iterations is not known or cannot be determined in advance. The general syntax of the while loop is as follows: [Read more…] about while loop in C
C Programming for Loop
The for loop is used for repetitive execution of a statement or a group of statements. It is a very powerful and flexible statement of the C language. It is generally used in situations where the number of iterations of the loop statement is known or can be determined in advance.
It can also be used in situations where the number of iterations is not known or cannot be determined in advance. However, the while loop is more convenient in such situations. The general form of the for loop is given below.
for ( initial_ expr ; final_ expr ; update_ expr )
statement;
This loop executes the contained statement repeatedly as decided by three control expressions (initial_expr, final_expr and update_expr). The initial_expr is usually an assignment expression, whereas the update_expr is an increment/decrement or compound assignment expression. The final_expr expression is usually a relational expression but may also be a Boolean expression or any valid C expression. Observe that the control expressions are written within a pair of parentheses and are separated by semicolons.
The most commonly used form of the for loop uses a loop control variable (also called loop variable, counter variable or index variable). It is a variable of any arithmetic type such as integer, floating-point, character, etc. Most programmers prefer short names for loop variables, e. g., variables i, j and k are commonly used in situations where integer loop variables are required.
The loop variable assumes a sequence of values as decided by the three control expressions. For each value of the loop variable, the statement included in the for loop is executed once. The initial_ expr initializes the loop variable, the update_expr updates (increment, decrement, etc.) its value and the final_expr is a test expression that compares its value with the desired final value to decide whether the execution of the contained statement should be continued or not.
Consider the for loop given below used to print the string “Hello world\n” four times.
for (i = l; i <= 4; i++)
printf(“Hello world\n”);
In this for loop, variable i (assumed to be of type int) is used as a loop variable. The initial expression, i = 1 , initializes the i to 1. The final expression, i <= 4 , compares value of i with the desired final value, i.e., 4. The update expression, i++, increments the value of i by 1. Thus, the loop variable i assumes values 1, 2, 3 and 4. For each of these values, the printf statement prints the string “Hello world” followed by a newline. Thus, the output is as follows:
Hello world
Hello world
Hello world
To understand the execution of the for loop, refer control flow diagram shown in Fig and the flowcharts in Fig. The execution of the for loop proceeds as follows: Initially, expression initial_ expr is evaluated. It performs the initialization of the loop variable. Then final_expr is evaluated. If it is true, the statement included in the loop is executed followed by evaluation of update_expr.
Then final expr is evaluated again. The execution of statement within the loop followed bythe evaluation of update_expr and final_expr continues as long as final_expr evaluates true; otherwise, the control leaves the for loop and continues with the execution of the next statement in the program. Note that the execution of the contained statement followed by the evaluation of update expression and final expression is commonly referred as an iteration of the loop. Also, the statement contained in the loop is commonly referred to as the body of the loop. ·
Although the values of loop variables used in the above for loop are quite natural, it is a common practice to use zero as the initial value for the loop variable. Moreover, as the array subscripts start from zero, the for loops used to process arrays also use zero as the initial value of loop variable. Hence, the style of using zero as the initial value of loop variables, wherever appropriate, is strongly recommended. Such a for loop to perform n iterations is given below.
for (i = 0; i < n; i++)
Note the use of the ‘<‘ operator in the final expression (i < n). Now the program segment to print Hello world five times can be rewritten as follows: ·
for (i = 0; i < 5; i++)
printf(“Hello world\n”);
Illustrates the application of a for loop for calculating factorial of a given number
#include<stdio.h>
void main()
{
int i, n , Factorial=1;
clrscr();
printf("Enter the number for finding factorial.");
scanf("%d", &n);
printf("n\tFactorial\n" );
for ( i= 1;i<=n; i++)
Factorial *= i;
printf( "%d\t%d\n", n, Factorial);
}
In one execution of the above program, the number entered is 5 and value of 5! is given by the program.
In the above program you would observe that the loop starts from the line for (int i=1; i<=n; i++) and ends at the statement Factorial *=i;. For the next iteration, the i is incremented, tested by the middle expression of the for loop and the iteration is carried out if the test is not false. So, in every iteration, the value of i is multiplied to the previous value of the factorial. At the end of the loop, we obtain Factorial= 1×2 x 3 x 4 x 5 =120.
C Program for Print all uppercase letters followed by all lowercase letters on the next line
In this example, we use two for loops in conjunction with the putchar library function to print all uppercase letters followed by all lowercase letters. The loop variable ch is assumed to be of type char or int. The first for loop prints the uppercase letters as loop variable ch assumes values as ‘A’, ‘B’, … , ‘z’.
Then a put char function prints a newline character to move the cursor to the next line on which the second for loop prints the lowercase letters. Note that the same loop variable is used for both for loops. The output is given below.
#include <stdio.h>
void main()
{
int ch;
clrscr();
printf(“Print all uppercase letters followed by all lowercase letters on the next line :\n”);
/* print uppercase letters */
for (ch= ‘A’; ch<= ‘Z’; ch++)
putchar(ch);
putchar (‘\n’ ) ;
/* print lowercase letters */
for (ch= ‘a’; ch<= ‘z’; ch++)
putchar(ch);
putchar (‘\n’) ;
getch();
}
C Program for Print integer number from 100 to 0 in steps of -10
In this example, the initial value of loop variable j (of type int) is 100 and the update expression (j -= 10) reduces it by 10 after each iteration of the for loop. [Read more…] about C Program for Print integer number from 100 to 0 in steps of -10
C Program for Print integer number in a given range
This code segment-first accepts a range of values in variables m and n, both of type int. The variable num, also of type int, is used as the loop variable. It assumes values from m to n. For each value of loop variable num, the printf statement within the for loop executes.
[Read more…] about C Program for Print integer number in a given range
C program for Print a line of dashes
The for loop given above prints a line of fifty dashes followed by a newline. The for loop uses i as the loop variable whose initial and final values are 0 and 49, respectively (note the < operator in i < 50). The update expression increments the value of i by 1.
Thus, the loop variable assumes values as 0, 1, 2, …, 49. For each value of i, the printf statement contained within the for loop prints a dash. Finally, the printf statement after the for loop prints a newline character to move the cursor to the next line.
#include <stdio.h>
void main()
{
int i;
clrscr();
printf(“Print a line of dashes :\n”);
for (i = 0; i < 50; i++)
{
printf(“-“);
}
getch();
}
C Program find the absolute value of a given Number
These statements determine and print the absolute value of variable n. If n is negative, then n < 0 evaluates as true and n is assigned the value of -n, which is then printed in the next statement assuming variable n to be of some integer type. However, if the value of n is positive, it remains unchanged and is printed.
Note that the above if statement works with both integral and floating point types. Recall that we can also use the abs and fabs functions to determine the absolute value of an integer and floating point expression, respectively.
Illustrates the determination of absolute values
#include <stdio.h>
#include <math.h>
void main()
{
int n = -765;
long int m = - 786548;
float x = -78.0;
double y = -67.78654;
long double z = - 564.564327;
clrscr();
printf("abs(n)= %d,\t labs(m) = %d\n", abs(n), labs(m));
printf("fabs(x)= %f\nfabs(y) = %f\nfabs(z)= %f\n", fabs(x), fabs(y),fabsl (z) );
}
C Program division without causing a division by zero error
While performing a division operation, if the divisor is zero, the division by zero error occurs and program execution halts abruptly. The program segment given below calculates and prints the value of a/b without causing a division by zero error. [Read more…] about C Program division without causing a division by zero error
C Program Find the Validity of marks in a single subject
if (marks >= 0 && marks <= 100)
printf(“Valid marks”);
else printf(“Invalid marks”);
This program segment uses an if-else statement to test whether the marks entered are valid or not and print the appropriate message. It is assumed that for marks to be valid, it should be in the range 0 to 100, i.e., greater than or equal to zero and less than or equal to 100. We may rewrite the above code by using a test for invalid marks. The value of marks is invalid if it is outside the range 0 to 100, i. e., less than 0 or greater than 100. The if-else statement using such a test is given below.
if (marks < 0 || marks > 100)
printf(“Invalid marks”);
else printf(“Valid marks”);
Note that there is also another way to express the validity of marks: it should not be invalid, i. e., it should not be outside the range 0 to 100. This logic is used in the if statement given below.
if (! (marks < 0 || marks > 100))
printf(“Valid marks”);
else printf(“Invalid marks”);
Example: Validity of marks in a single subject
#include <stdio.h>
void main()
{
int marks;
clrscr();
printf(“Enter the Marks :\n”);
scanf(“%d”,&marks);
if (marks >= 0 && marks <= 100)
printf(“Valid marks”);
else printf(“Invalid marks”);
getch();
}
C Program Find the Result of a student in SSC Examination
Consider that we wish to determine the result of a student in the SSC (Secondary School Certificate) examination, which has six subjects: four of 100 marks each and two of 150 marks each.
For a student to pass the examination, he/she has to pass each subject, where the pass percentage is 35. Let us use variables ml, m2, m3, m4, m5 and m6 for marks in these subjects where the first four variables (ml to m4) represent marks in subjects having maximum 100 marks. The if statement given below determines the result of a student.
if (ml >= 35 && m2 >= 35 && m3 >= 35 && m4 >=35 && m5>=52 && m6>=52)
printf(“Pass\n”);
else printf(“Fail\n”);
Alternatively, a student fails if he fails in any one of the subjects. Thus, the above if statement can be written as shown below.
if (ml < 35 || m2 < 35 || m3 < 35 || m4 < 35 || m5 < 52 || m6 < 52)
printf(“Fail\n”);
else printf(“Pass\n”);
Example: Find the Result of a student in SSC Examination
#include <stdio.h>
void main()
{
int m1,m2,m3,m4,m5,m6;
clrscr();
printf(“Enter the Marks :\n”);
scanf(“%d%d%d%d%d%d”,&m1,&m2,&m3,&m4,&m5,&m6);
if (m1 >= 35 && m2 >= 35 && m3 >= 35 && m4 >=35 && m5>=52 && m6>=52)
printf(“Pass\n”);
else printf(“Fail\n”);
getch();
}
C program Test for whitespace
A character is a whitespace if it is one of the following characters: blank space (‘ ‘), newline (‘\n’), horizontal tab (‘\t’), carriage return (‘\r’), form feed (‘\f’) or vertical tab (‘\v’). The if statement given below tests whether the given character ch is equal to one of these characters using logical or (||) operator and prints an appropriate message.
if (ch == ‘ ‘ || /* ch is a blank space or */
ch == ‘\t’ || /* a horizontal tab or */
ch ==’\n’ || /* a new line or */
ch == ‘\r’ || /* a carriage return or */
ch == ‘\f’ || /* a form feed or */
ch== ‘\v’) /* a vertical tab */
printf(“Whitespace\n”);
else printf(“Not whitespace\n”);
Note that to test for a whitespace, it is often sufficient to check whether the given character is equal to one of three characters: space, horizontal tab and new line, e. g., when the characters are entered from the keyboard. Thus, the above if statement can be rewritten as shown below.
if (ch== ‘ ‘ || ch== ‘\t’ || ch== ‘\n’)
printf(“Whitespace\n”);
else printf(“Not whitespace\n”);
Example: Test for whitespace
#include <stdio.h>
void main()
{
char ch;
clrscr();
Printf(“Enter the Character”);
scanf(“%c”,&ch);
if (ch == ‘ ‘ || /* ch is a blank space or */
ch == ‘\t’ || /* a horizontal tab or */
ch ==’\n’ || /* a new line or */
ch == ‘\r’ || /* a carriage return or */
ch == ‘\f’ || /* a form feed or */
ch== ‘\v’) /* a vertical tab */
printf(“Whitespace\n”);
else printf(“Not whitespace\n”);
getch();
}
C Program for print a name of color that start with a given character
The program segment given below accepts a character from the keyboard and prints the name of the corresponding color, e. g., if the user enters character R, it prints Red. However, it handles only three colors, namely, red, green, and blue.
The character entered from the keyboard is first accepted in variable color (of type char) and then tested in the switch statement. The program includes three cases corresponding to the colors red, green, and blue. Note that the case values are character constants’ R,’ ‘G’ and ‘B.’ Each case includes a printf statement to print the color’s name followed by a break statement. The output of the program containing the above code shown below. [Read more…] about C Program for print a name of color that start with a given character
C Program for print a given digit as a word
The program segment given below accepts an integer number in variable digit of type int from the keyboard and if it is a single digit number (0-9), it displays the word corresponding to it;
otherwise, it displays the message Not a digit. The switch statement has a case block for each digit (0-9) and a default block to handle all other numbers. Note that the code for each case has been written on a single line to save space.
#include <stdio.h>
void main()
{
int digit;
clrscr();
printf(“Enter a digit (0-9): “);
scanf (“%d”, &digit);
switch (digit)
{
case 0: printf(“Zero”); break;
case 1: printf(“One”); break;
case 2: printf(“Two”); break;
case 3: printf(“Three”); break;
case 4: printf(“Four”); break;
case 5: printf(“Five”); break;
case 6: printf(“Six”); break;
case 7: printf(“Seven”); break;
case 8: printf(“Eight”); break;
case 9: printf(“Nine”); break;
default:printf(“Not a digit”); break;
}
printf(“\n”);
getch();
}
C Program for Simple Calculator
Let us use variables a and b of type float to represent two operands, variable c of type float to represent the result and variable op of type char to represent the operator. In the program given below, an expression of the form a op b is first accepted from the keyboard and a switch statement is used to evaluate the result.
The operator op is used as test expression in the switch statement and four cases correspond to the given operators. In each case, the desired value is evaluated in variable c. This value is printed using a printf statement after the switch statement.
/* Simple calculator: evaluates expression of form a op b */
#include <stdio.h>
void main()
{
float a, b, c; /* operands */
char op;
clrscr();
printf(“Enter expression of the form a op b:\n”);
scanf(“%f %lc %f”, &a, &op, &b);
switch (op)
{
case ‘+’:
c = a + b;
break;
case ‘-‘:
c = a – b;
break;
case ‘*’:
case ‘x’:
case ‘X’:
c = a * b;
break;
case ‘/’:
c = a / b;
break;
}
printf(“c =%f\n”, c);
getch();
}
Observe that the case values are character constants: ‘+’ , ‘- ‘, ‘ * ‘, ‘x ‘, ‘x’ and ‘/ ‘. Also, an operator is accepted from the keyboard using the %lc format in the scanf statement.
C Program Find The Larger between Two Numbers
large= a> b? a : b;
This example illustrates how a conditional expression can be used to assign one of two alternative values to a variable depending on the outcome of some condition. As the conditional expression operator has higher precedence than the assignment operator, the above assignment statement is equivalent to
large= (a> b? a : b);
The value of the conditional expression (a > b ? a : b) is equal to that of variable a if a is greater than b; otherwise, it is equal to the value of variable b. This value is assigned to variable large. Thus, the given statement assigns the larger of variables a and b to variable large. The same effect can be achieved using an if-else statement given below.
if (a > b)
large = a;
else large = b;
We can rewrite the given conditional expression using the assignment expressions as alternative expressions, as shown below. Note that the parentheses are essential as the assignment operator has lower precedence than the conditional expression operator.
a> b? (large= a) : (large= b);
We can also use a conditional expression as an argument in the printf statement, as shown below:
printf(“Larger number: %d”, a> b? a : b);
We can also rewrite the above statement by calling the printf functions from within the conditional expression, as shown below.
a> b? printf(“Larger number: %d”, a) : printf(“Larger number: %d”, b);
Recall that the printf (and scanf)function actually returns an integer value that is ignored in most calls. Thus, the printf function calls in the above statement are expressions as expected and not statements.
#include<stdio.h>
#include<conio.h>
void main()
{
int a,b,large;
printf(“Enter the Value of a : “);
scanf(“%d”, &a);
printf(“\nEnter the Value of b : “);
scanf(“%d”, &b);
large= a> b? a : b;
printf(“The Large value is = %d”, large);
getch();
}
C Program Find The Days in February
The if-else statement given below uses the leap year test to determine the number of days in February.
if (yy % 4 == 0 && yy%100 != 0 || yy % 400 == 0) /* leap year test */
days = 29;
else days = 28;
We can rewrite this code using a conditional expression as shown below.
(yy % 4 == 0 && yy % 100 != 0 || yy % 400 == 0) ? days = 29 : days=28;
However, the code is concise and more readable when we first determine the desired value and then assign it to days as shown below:
days = ( (yy % 4 == 0 && yy % 100!= 0 || yy % 4 00 == 0 )? 2 9 : 2 8 ) ;
We can verify, by applying the operator precedence rules, that the parentheses in the above statement are not essential but are useful as they improve the readability. The above statement can thus be written by removing the redundant parentheses as shown below.
days = (yy % 4 == 0 && yy % 100 != 0 || yy % 400 == 0) ? 29 : 28;
days = yy % 4 == 0 && yy % 100 != 0 ||yy % 400 == 0 ? 29 : 28;
Let us now use another approach to determine the number of days in February. We can use a simple if statement to determine days as follows:
days = 28;
if (yy % 4 == 0 && yy % 100 != 0 || yy % 400. == 0)
days++;
Here the value of days is first initialized to 28 and then incremented by 1 only if the given year yy is a leap year. This code can be written concisely using the conditional expression as
days= 28 + (yy % 4 == 0 && yy % 100 != 0 || yy % 400 == 0? 1 : 0);
Here, depending on whether the given year is leap or not, we add either 1 or 0 to 28. Although the addition of 0 is meaningless, it cannot be avoided as both the alternative expressions must be specified in a conditional expression. Also, observe that the parentheses cannot be omitted. Finally, let us see one more variation of this statement. We know that the value of a Boolean expression is 1 if it is true and 0 otherwise. This is exactly what is required in the ·above conditional expression. Thus, we can omit the conditional expression operator and simply add the value of Boolean expression to 28 as shown below.
days = 2 8 + (yy % 4 == 0 & & yy % 100 != 0 || yy % 400 == 0) ;
Observe that this statement is bit difficult to understand and that the parentheses surrounding the Boolean expression cannot be omitted.
#include<stdio.h>
#include<conio.h>
void main()
{
int yy;
clrscr();
printf(“Enter a Year : “);
scanf(“%d”,&yy);
if (yy % 4 == 0 && yy%100 != 0 || yy % 400 == 0) /* leap year test */
{
printf(“Days in February are 29”);
}
else
{
printf(“Days in February are 28”);
}
getch();
}