0% found this document useful (0 votes)
8 views90 pages

Module 2B

The document outlines programming concepts in C, focusing on statements, conditional expressions, and control flow structures such as selection and iteration statements. It includes examples of if statements, nested ifs, switch statements, and practical programming exercises. Additionally, it provides programming tasks to reinforce understanding of these concepts.

Uploaded by

khushiniveditha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views90 pages

Module 2B

The document outlines programming concepts in C, focusing on statements, conditional expressions, and control flow structures such as selection and iteration statements. It includes examples of if statements, nested ifs, switch statements, and practical programming exercises. Additionally, it provides programming tasks to reinforce understanding of these concepts.

Uploaded by

khushiniveditha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1BEIT105

Programming in C
3:0:0
Textbook:
1. Schildt, Herbert." C the complete reference",4thEdition, Mc Graw Hill.

2. Hassa A fyouni, Behrouz A. Forouzan. “A Structured Programming Approachin”,4th Edition,


Cengage.

Amruthasree V M, Assistant Professor, NIE 1


MODULE 2B

Amruthasree V M, Assistant Professor, NIE 2


STATEMENTS:
• A statement is a part of program that can be executed. That is, a statement specifies an action. C categorizes
statements into these groups:
• Selection
• Iteration
• Jump
• Label
• Expression
• Block
• The selection statements are if and switch. (The term conditional statement is often used in place of selection
statement.)
• The iteration statements are while, for, and do-while. These are also commonly called loop statements.
• The jump statements are break, continue, goto, and return.
• Expression statements are statements composed of a valid expression.
• Block statements are simply blocks of code. (A block begins with a { and ends with a }.) Block statements are also
referred to as compound statements.
Amruthasree V M, Assistant Professor, NIE 3
TRUE AND FALSE IN C
• Many C statements rely upon a conditional expression that determines
what course of action is to be taken.
• A conditional expression evaluates to either a true or false value.
• In C, true is any nonzero value, including negative numbers.
• A false value is 0.

Amruthasree V M, Assistant Professor, NIE 4


Amruthasree V M, Assistant Professor, NIE 5
SELECTION STATEMENTS/ CONDITIONAL STATEMENT
This help to jump from one part of the program to another depending on whether the
condition is satisfied or not.
The different decision control statements are :
• if statements
• if-else statements
• if-else-if statements
• nested if statements
• switch statements
1. if statement
• If expression evaluates to true, the Synatx
statement or block that forms the target if(expression)
of if is executed; otherwise, the {
statement or block that forms the target
statements;
of else will be executed, if it exists.
}
• Remember, only the code associated else
with if or the code associated with else {
executes, never both.
statements;
• where a statement may consist of a } //Rest of the code
single statement, a block of statements, • Two possible outcomes for test
or nothing (in the case of empty condition (True or False)
statements).
• Don’t use semicolon after the test
• The else clause is optional. expression.
• The program contains an example of
if.
• The program plays a very simple
version of the ''guess the magic
number" game.
• It prints the message ** Right **
when the player guesses the magic
number.
• It generates the magic number using
the standard random number generator
rand( ), which returns an arbitrary
number between 0 and RAND_MAX
(which defines an integer value that
is 32,767 or larger).
• The rand( ) function requires the
header <stdlib.h>.
8
Amruthasree V M, Assistant Professor, NIE
• the next version illustrates
the use of the else
statement to print a
message in response to the
wrong number.

Amruthasree V M, Assistant Professor, NIE 9


Q1 : Write a program to check whether a number is +ve or –ve.
#include<stdio.h>
void main()
{
int num;
printf(“Enter a number”);
scanf( “%d” , &num);
if(num > 0)
{
printf("%d is positive",num);
}
else
{
printf ("%d is not positive",num);
}
}
Q2. Check whether an integer is odd or even
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number%2 == 0)
{
printf("%d is an even integer.",number);
}
else
{
printf("%d is an odd integer.",number);
}
return 0;
}
Q3. Write a program to find largest of two numbers.
#include <stdio.h>
int main()
{
int num1, num2;
printf("Enter two numbers: ");
scanf("%d%d", &num1,&num2);
if (num1>num2)
{
printf("%d is greater than %d",num1, num2);
}
else
{
printf("%d is smaller than %d.",num1,num2);
}
return 0;
}
Q4. Write a program to enter a character and then
determine whether it is a vowel or not
#include <stdio.h>
void main()
{
char c;
printf("Enter a character: ");
scanf("%c", &c);
if(c==‘a’ ||c==‘e’||c==‘i’||c==‘o’||c==‘u’||c==‘A’|c==‘E’||c==‘I’||c==‘O’||c==‘U’)
{
printf(“ %c is vowel”,c);
}
else
{
printf(“Consonant”);
}
}
Q5. C program to check whether a character is alphabet or not
#include <stdio.h>
int main()
{
char ch;
printf("Enter any character: ");
scanf("%c", &ch);
if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
printf("Character is an ALPHABET.");
}
else
{
printf("Character is NOT ALPHABET.");
}
return 0;
}
2. Nested if..else statement
• A nested if is an if that is the target
of another if or else.
• Nested ifs are very common in
programming.
• In a nested if, an else statement
always refers to the nearest if
statement that is within the same
block as the else and that is not
already associated with an else.
#include <stdio.h> else if (b > c)
void main {
{ printf("\n Greatest number = %d \n",b);
int a, b, c; }
printf(" Enter the number1 = "); else
scanf("%d", &a); {
printf("\n Enter the number2 = "); printf("\n Greatest number = %d \n",c);
scanf("%d", &b); }
printf("\n Enter the number3 = "); }
scanf("%d", &c);
if (a > b)
{
if (a > c)
{
printf("\n Greatest number = %d \n",a);
Q1. C program to find the greatest
} among three numbers
else
{
printf("\n Greatest number = %d \n",c);
}
}
3. if – else – if ladder (if-else-if staircase)
• The conditions are evaluated from the top
downward.
• As soon as a true condition is found, the
statement associated with it is executed and
the rest of the ladder is bypassed.
• If none of the conditions are true, the final
else is executed. That is, if all other
conditional tests fail, the last else statement is
performed.
• If the final else is not present, no action takes
place if all other conditions are false.
#include<stdio.h> Q1. Write program to check whether the number is
int main()
zero, positive or negative.
{
int x;
printf(“Enter the number”);
scanf(“%d”,&x);
if(x>0)
{
printf(“%d is +ve”,x);
}
else if(x<0)
{
printf(“%d is –ve”,x)
}
else
{
printf(“Zero”);
}
#include<stdio.h> Q2. Read two numbers and check whether
int main() they are equal, greater or smaller
{
int a,b;
printf(“Enter 2 numbers”);
scanf(“%d%d”,&a,&b);
if(a<b)
{
printf(“%d is greater than %d”,b,a);
}
else if(a>b)
{
printf(“%d is greater than %d”,a,b);
}
else
{
printf(“both are equal”);
}
return 0;
}
Q3. Write a program to display the examination result.

Mark>=75 Distinction
60 <= marks < 75 A grade
50 <= marks < 60 B grade
40 <= marks <50 C grade
else failed
Q4. Simulation of simple calculator.
Q5. Write a program to enter a character and then determine whether
it is a vowel or not
Q6. Largest among 3 numbers using && operator

if(a>b && a>c)


{
printf(“a is greater”);
}
else if(b>a && b>c)
{
printf(“B is greater”);
}
else
{
printf(“C is greater”);
}
Switch Statement
• The switch case statement is an multi-way decision statement.
• Alternative to the if-else-if ladder
• It execute the statements based on the value of the variable specified in
the switch statement.
• The switch expression should evaluate to either integer or character.
It cannot evaluate any other data type.
• The expression must evaluate to an integer type. Thus, can use
switch(expression)
character or integer values, but floating-point expressions are not
{
allowed.
case value1:
block-1 • The value of expression is tested against the values, one after
break; another, of the constants(case value) specified in the case
statements.
case value2:
block-2 • When a match is found, the statement sequence associated with
break; that case is executed until the break statement or the end of the
case value3: switch statement is reached.
block-3 • The default statement is executed if no matches are found.
break; • The default is optional, and if it is not present, no action takes
. place if all matches fail.
. • The break statement is one of C's jump statements. It can use it in
default: loops as well as in the switch statement.
block-default
• When break is encountered in a switch, program execution
break;
"jumps" to the line of code following the switch statement.
} • case label must end with a colon.
• There are three important things to know about the switch statement:
1. The switch differs from the if in that switch can only test for
equality, whereas if can evaluate any type of relational or logical
expression.
2. No two case constants in the same switch can have identical
values. Of course, a switch statement enclosed by an outer switch
may have case constants that are in common.
3. If character constants are used in the switch statement, they are
automatically converted to integers

Amruthasree V M, Assistant Professor, NIE 27


printf(“Enter the grade”);
Scnf(“%c”,&grade);
switch(grade)
{
case ‘O’:
printf(“Outstanding”);
break;
case ‘A’:
printf(“Excellent”);
break; Output:
case ‘B’: Enter the grade : c
printf(“Good); Invalid Grade
break;
case ‘C’:
Enter the grade : F
printf(“Fair);
Fail
break;
case ‘F:
printf(“Fail);
break;
default:
printf(“Enter the grade”);
Program without break
scanf(“%c”,&grade);
switch(grade)
{
case ‘O’:
printf(“Outstanding”);

case ‘A’:
printf(“Excellent”);
Output:
case ‘B’: Enter the grade : c
printf(“Good); Invalid Grade

case ‘C’:
Enter the grade : O
printf(“Fair);
Outstanding
break; Excellent
case ‘F: Good
printf(“Fail); Fair
break;
default:
Q1 : Write a program to read number between 1 to 7 and display the day
corresponding to the number.
#include <stdio.h> case 4:
int main() printf("Thursday");
break;
{
case 5:
int week;
printf("Friday");
printf("Enter week number(1-7): ");
break;
scanf("%d", &week); case 6:
switch(week) printf("Saturday");
{ break;
case 1: case 7:
printf("Monday"); printf("Sunday");
break; break;
default:
case 2:
printf("Invalid input.");
printf("Tuesday");
}
break; return 0;
case 3: }
Q2. Write a program to check the character is vowel or note
#include <stdio.h> case 'A':
int main() printf("%c is a vowel",ch);
{
break;
char ch;
case 'E':
printf("Enter any Alphabet\n");
scanf("%c",&ch); printf("%c is a vowel",ch);
switch(ch) break;
{ case 'I':
case 'a': printf("%c is a vowel",ch);
printf("%c is a vowel",ch);
break;
break;
case 'O':
case 'e':
printf("%c is a vowel",ch); printf("%c is a vowel",ch);
break; break;
case 'i': case 'U':
printf("%c is a vowel",ch); printf("%c is a vowel",ch);
break;
break;
case 'o':
printf("%c is a vowel",ch);
default:
break; printf("%c is a consonant",ch);
case 'u': break;
printf("%c is a vowel",ch); }
break; return 0; }
#include <stdio.h>
int main() case 'o':
{ case ‘O’
char ch; printf("%c is a vowel",ch);
printf("Enter any Alphabet\n"); break;
scanf("%c",&ch); case 'u':
switch(ch){ case ‘U’
case 'a': printf("%c is a vowel",ch);
case 'A': break;
printf("%c is a vowel",ch); default:
break; printf("%c is a consonant",ch);
case 'e': break;
case 'E': }
printf("%c is a vowel",ch); return 0;
break; }
case 'i':
case ‘I’
printf("%c is a vowel",ch);
break;
Q3. Write a program that accepts a number from 1 to 10. Print whether the
number is even or odd using a switch case construct.
#include <stdio.h>
case 2:
int main() case 4:
{ case 6:
int num; case 8:
printf("Enter a number"); case 10:
scanf("%d",&num); printf("%d is a even number",num);
switch(num){ break;
default:
case 1:
case 3: printf(“Invalid");
case 5: break;
case 7: }
case 9: return 0;
printf("%d is an odd number",num); }
break;
Simulation of a Simple Calculator.
#include<stdio.h> case'/':
int main() if(b==0)
{ {
int a,b,ans; printf("Divide by Zero error");
char op; }
scanf("%d\n%c\n%d",&a,&op,&b); else
switch(op) {
{ ans=a/b;
case '+': printf("The quotient is %d",ans);
ans=a+b; }
printf("The sum is %d",ans); break;
break; case'%':
case'-': ans=a%b;
ans=a-b; printf("The remainder is %d",ans);
printf("The difference is %d",ans); break;
break; default:
case'*': printf("Invalid Input");
ans=a*b; break;
printf("The product is %d",ans); }
break; return 0;
}
#include<stdio.h>

int main()
{
Q1. Write program to check whether the number is
int x,choice;
printf(“Enter the number”); zero, positive or negative using switch.
scanf(“%d”,&x);
if(x>0)
{
choice =1;
break;
}
else if(x<0)
{
choice=2;
}
else
{
choice=3;
}
switch(c)
{
case 1:
printf(“%d is +ve”,x);
break;
case 2:
printf(“%d is –ve”,x)
break;
case 3:
printf(“Zero”);
Iterative Statements
• Iterative or Looping statements are used to repeat the execution
of a block of code until the specified condition is met.
• A loop statement allows programmers to execute a statement or
group of statements multiple times without the repetition of
code.
•There are mainly two types of loops in C Programming:

1. Entry Controlled loops: Here the test condition is checked before entering the body
of the [Link] Loop and While Loopis Entry-controlled loops.

2. Exit Controlled loops: Here the test condition is evaluated at the end of the loop
body. The loop body will execute at least once, irrespective of whether the condition is
true or
while loop
• Where statement is either an empty statement, a single
• Syntax: statement, or a block of statements.
statement x; • The condition may be any expression, and true is any nonzero
value.
while (condition)
• The loop iterates while the condition is true.
{
statement block; • When the condition becomes false, program control passes to
the line of code immediately following the loop.
update condition;
} • While loops check the test condition at the top of the loop,
which means that the body of the loop will not execute if the
statement y; condition is false to begin with.
• This feature may eliminate the need to perform a separate
conditional test before the loop.
#include <stdio.h>
int main()
{
int i=0;
while(i<10)
{
printf( "Hello World\n");
i=i+1; //i++;
}
return 0;
}
Q1 : Program to print numbers 1 to 10
#include<stdio.h>
int main(void)
{
int i=1;
while(i<=10)
{
printf("%d\n",i);
i = i+1;
}
return 0;
}
Q2: Write a program to print numbers between m to n
#include < stdio.h >
void main()
{
int m,n;
printf("Enter 2 positive numbers\n");
scanf("%d%d", &m, &n);
printf("Natural numbers between %d and %d are:\n", m, n);
while(m <= n)
{
printf("%d ", m);
m++;
Q3 : print 20 horizontal asterisk (*).
#include <stdio.h>
int main()
{
int i = 1;
while ( i <=20)
{
printf("*");
i += 1
}
}
Q4 : Write a program to calculate the sum of first 10 numbers.
#include<stdio.h>
void main()
{
int i=1, sum = 0;
while(i<=10)
{
sum = sum + i;
i++;
}
printf("\nSum of first 10 Natural Numbers is : %d", sum);
}
Q5 : Write a program to calculate the sum of numbers from m
to n.
#include <stdio.h>
void main()
{
int m,n,sum=0;
printf("Enter the value of m: ");
scanf("%d",&m);
printf("Enter the value of n: ");
scanf("%d",&n);
while(m<=n)
{
sum+=m;
m++;
}
printf("Sum = %d\n",sum);
}
Q6 : Write a program to read the numbers untill -1 is encountered. Also count the –
ve, +ve , and zero entered by the user.
do while
• The do-while loop is similar to a while loop but the only difference is it is exit
controlled loop.
• Here test condition is tested at the end of the body.
• The loop body will execute at least once irrespective of the test condition.
• Test condition is enclosed in parenthesis and followed by a semicolon.
• Statements in the statement bock are enclosed within curly bracket.
• The curly bracket is optional if there is only one statement in the body of the loop.
Syntax
statement x;
do
{
statement block;
}while(condition);
statement y;

• The major disadvantage of using a do-while loop is that it always execute


at least once, even if the user entered some invalid data, the loop will
execute.
// Sum of the entered numbers. Stops when 0 entered
#include<stdio.h>
int main()
{
int n,sum=0;
do
{
printf("Enter a number:");
scanf("%d",&n);
sum = sum+n;
}while(n!=0);
printf("Out of loop...\n");
printf("sum = %d",sum);
return 0;
}
for loop

• The initialization is an assignment statement that is used to set the loop


control variable.
• The condition is a relational expression that determines when the loop
exits.
• The increment defines how the loop control variable changes each
time the loop is repeated.
• You must separate these three major sections by semicolons.
• The for loop continues to execute as long as the condition is true. Once
the condition becomes false, program execution resumes on the
statement following the for.
• In the loop, x is initially set to 1 and then compared with 100. Since x is
less than 100, printf( ) is called and the loop iterates. This causes x to be
increased by 1 and again tested to see if it is still less than or equal to 100.
If it is, printf( ) is called. This process repeats until x is greater than 100,
at which point the loop terminates. In this example, x is the loop control
variable, which is changed and checked each time the loop repeats.

Amruthasree V M, Assistant Professor, NIE 52


#include <stdio.h> #include <stdio.h>
int main() int main()
{ {
int i; int i=0;
for(i=0;i<10;i++) while(i<10)
{ {
printf( "Hello World\n"); printf( "Hello World\n");
} i=i+1; //i++;
return 0; }
} return 0;
}
for Loop Variations
1. In a for loop any or all the expressions can be omitted.
for(;i<10;i++)
for(i=0;i<10;)
for(;i<10;)
In case all the expression are omitted, then there must be two semicolon in
the for statement
for(;;)
2. There must be no semicolon after a for statement.

#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i++);
{
printf( “%d“,i);
}
Compiler will not generate any error message
return 0; You will get an unexpected output.
}
3. Multiple initialization can be separated with a comma operator
for(i=1,sum=0;i<=10;i++)
{
sum = sum + i;
}

4. Multiple condition in the test expression can be tested by using the


logical operator. (&& and ||)
5. If there is no initialization to be done, then the initialization statement can
be skipped by giving only a semicolon.

#include <stdio.h>
void main()
{
int i=0;
for(;i<10;i++)
{
printf( “%d“,i);
}
}
6. If the loop controlling statement is updated within the statement block, then
the third part can be skipped.

#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;)
{
printf( “%d“,i);
i++;
}
return 0;
}
7. Multiple statement can be included in the third part by using comma
operator

for(i=0;j=10; i<j; i++,j--)


8. The controlling variable can be incremented and decremented by values other than
one.

#include <stdio.h>
int main()
{
int i;
for(i=0;i<10;i+=2)
{
printf( “%d“,i);
}
return 0;
}
9. If the for loop containing nothing but two semicolons, the loop may
become an infinite loop.

Infinitely print C programming on the computer screen.


10. Never use a floating point variable as loop control variable.
Q1 : Program to print numbers 1 to 10
#include<stdio.h>
int main(void)
{
//int i;
for(int i=1;i<=10;i++)
{
printf("%d\n",i);
}
return 0;
}
Q2: Write a program to print numbers between m to n
#include < stdio.h >
void main()
{
int m,n;
printf("Enter 2 positive numbers\n");
scanf("%d%d", &m, &n);
printf("Natural numbers between %d and %d are:\n", m, n);
for(;m <= n;m++)
{
printf("%d ", m);
}
Q3 : print 20 horizontal asterisk (*).
#include <stdio.h>
int main()
{
int i;
for(i=1;i <=20;i++)
{
printf("*");
}
}
Q4 : Write a program to calculate the sum of first 10 numbers.

#include<stdio.h>
void main()
{
int i;
for(i=1,sum=0;i<=10;i++)
{
sum = sum + i;
}
printf("\nSum of first 10 Natural Numbers is : %d", sum);
}
Q5 : Write a program to calculate the sum of numbers from m
to n.
#include <stdio.h>
void main()
{
int m,n,sum=0;
printf("Enter the value of m: ");
scanf("%d",&m);
printf("Enter the value of n: ");
scanf("%d",&n);
for(;m<=n;m++)
{
sum+=m;
}
printf("Sum = %d\n",sum);
}
Programs
1. Palindrome of a number using while loop
2. Factorial of a number using while loop
Nested Loop
• When a loop written inside the body of another loop then, it is known
as nesting of loop. (Loops that can be placed inside other loop).
• Any type of loop can be nested in any type such as while, do while,
for.
Programs
• Write a program to print numbers from 1 to 10.
• Write a program to print the sum of N natural numbers.
• Write a C program to print the sum of all even numbers between 1 and 50.
• Write a program to print the multiplication table of a given number.
• Write a program to print the factorial of a given number.
• Write a program to reverse a number.
• Write a program to check whether a number is a palindrome.
• Write a program to check whether a number is a prime number.
• Write a program to count the digits in a number.
• Write a program to find the sum of digits of a number
• Print a multiplication table(1-10) using nested for loop
• Write a program to accept numbers until the user enters 0, and display their sum
using do-while loop.
Jump Statements
C has four statements that perform an unconditional branch:
1. return statement
2. goto statement
3. break statement
4. continue statement
5. exit() function
return statement
• The return statement is used to return from a #include <stdio.h>
function.
// Function that adds two integers and returns sum
• It is categorized as a jump statement because it causes int add(int a, int b)
execution to return (jump back) to the point at which
{
the call to the function was made. int sum = a + b;
• A return may or may not have a value associated with return sum; // Returns the calculated sum
it. }

• A return with a value can be used only in a function int main()


with a non-void return type. In this case, the value {
associated with return becomes the return value of the int num1 = 10;
function. int num2 = 5;
int result = add(num1, num2); // Call the function
• A return without a value is used to return from a void printf("The sum of %d and %d is: %d\n", num1,
function. num2, result);
return 0;
• The general form of the return statement is
}
73
return expression; Amruthasree V M, Assistant Professor, NIE
The goto Statement #include <stdio.h>
int main() {
• The goto statement requires a label for operation. (A int n = 26;
label is a valid identifier followed by a colon.) if (n % 2 == 0){

• The label must be in the same function as the goto goto even; // jump
to even
that uses it— you cannot jump between functions.
}
• It transfers program control from els{
the goto statement to the code block associated goto odd; // Jump to odd
with the designated label. }
• The general form of the goto statement is even:

goto label; printf("%d is even", n);


return 0;
...
label: odd:
• where label is any valid label either before or after printf("%d is odd", n);
goto. return 0; 74
Amruthasree V M, Assistant Professor, NIE
Prints numbers from 1 to 10
#include <stdio.h>
int main(){
int n = 1;
// Label here
label:
printf("%d ", n);
n++;
if (n <= 10)
goto label; // jumb back to the label
return 0;
}

Amruthasree V M, Assistant Professor, NIE 75


break statement
• The break statement has two uses.
1. Use to terminate a case in the switch
statement
2. Use to force immediate termination of a
loop, bypassing the normal loop
conditional test.
• When the break statement is encountered
inside a loop, the loop is immediately
terminated, and program control resumes at
the next statement following the loop.

Amruthasree V M, Assistant Professor, NIE 76


1. Write a program to print numbers from 1 to 10, but stop printing when the number is 5.
#include <stdio.h>
int main()
{
int i;
for (i = 1; i <= 10; i++)
{
if (i == 5) // If 'i' becomes 5, exit the loop
{
break;
}
printf("%d ", i);
}
printf("\nLoop terminated.\n");
return 0;
}

Amruthasree V M, Assistant Professor, NIE 78


2. Write a C program to display numbers from 1 to n, but terminate the loop if the current number is divisible by 7.
#include <stdio.h>
int main()
{
int n, i;
printf("Enter a positive integer (n): ");
scanf("%d", &n);
if (n <= 0)
{
printf("Please enter a positive integer.\n");
return 1; // Indicate an error
}
printf("Numbers from 1 to %d (stopping if divisible by 7):\n", n);
for (i = 1; i <= n; i++)
{
if (i % 7 == 0)
{
printf("Loop terminated because %d is divisible by 7.\n", i);
break; // Exit the loop
}
printf("%d\n", i);
}
return 0; // Indicate successful execution
} Amruthasree V M, Assistant Professor, NIE 79
3. Write a C program to print even numbers between 1 and 20, but exit the
loop when the number is greater than 12.
#include <stdio.h>
int main()
{
int i;
for (i = 1; i <= 20; i++)
{
if (i > 12)
{
break;
}
if (i % 2 == 0)
{
printf("%d\n", i);
}
}
return 0;
}

Amruthasree V M, Assistant Professor, NIE 80


4. Write a C program to take numbers as input continuously and stop when the user enters 0.
#include <stdio.h>
int main()
{
int number;
printf("Enter numbers continuously (enter 0 to stop):\n");
do
{
printf("Enter a number: ");
scanf("%d", &number);
if (number != 0)
{
printf("You entered: %d\n", number);
}

} while (number != 0);

printf("0 entered. Program terminated.\n");

return 0;
Amruthasree V M, Assistant Professor, NIE 81
}
The exit( ) Function
• The exit() function is a standard library function used to immediately
terminate the calling process (the program).
• The general form of the exit( ) function is
void exit(int return_code);
• The exit( ) function requires the header <stdlib.h>.

Amruthasree V M, Assistant Professor, NIE 82


1. Write a C program to read a number from the user and exit the program if the
number is negative.

#include <stdio.h>
#include <stdlib.h> // Required for the exit() function
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d", &number);
if (number < 0)
{
printf("You entered a negative number. Exiting program.\n");
exit(1); // Exit the program with a non-zero status, indicating an
error or specific condition
}
printf("You entered a non-negative number: %d\n", number);
return 0; // Indicate successful program execution
}

Amruthasree V M, Assistant Professor, NIE 83


The continue Statement
• When the compiler encounters a continue statement then the rest of the
statement in the loop are skipped and the control is unconditionally
transferred to the loop continuation portion of the nearest enclosing loop.
• Syntax: just type the keyword continue followed by a semicolon.
continue;
1. Write a program to print numbers from 1 to 10, but skip the number 5.
2. Write a C program to print numbers from 1 to 20, but skip all even
numbers.

#include <stdio.h>

int main()
{
printf("Numbers from 1 to 20 (excluding even numbers):\n");
for (int i = 1; i <= 20; i++)
{
if (i % 2 != 0)
{ // Check if the number is odd
printf("%d\n", i);
}
}
return 0;
}

Amruthasree V M, Assistant Professor, NIE 87


3. Write a C program to print numbers from 1 to 15, but skip numbers
divisible by 3 using continue.
#include <stdio.h>
int main()
{
for (int i = 1; i <= 15; i++)
{
if (i % 3 == 0)
{
// If divisible by 3, skip the rest of the current iteration
// and proceed to the next iteration of the loop.
continue;
}
// If not divisible by 3, print the number
printf("%d ", i);
}
printf("\n"); // Print a newline character for better formatting
return 0;
}

Amruthasree V M, Assistant Professor, NIE 88


Amruthasree V M, Assistant Professor, NIE 89
Amruthasree V M, Assistant Professor, NIE 90

You might also like