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

C Unit2 Notes

The document provides an overview of input and output statements in C programming, detailing the standard input-output library (stdio.h) and various functions for formatted and unformatted input/output operations. It includes examples of using scanf() and printf() for reading and displaying data, as well as character testing functions. Additionally, it introduces control structures, specifically decision-making and branching statements in C.

Uploaded by

sanjanashintri
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 views32 pages

C Unit2 Notes

The document provides an overview of input and output statements in C programming, detailing the standard input-output library (stdio.h) and various functions for formatted and unformatted input/output operations. It includes examples of using scanf() and printf() for reading and displaying data, as well as character testing functions. Additionally, it introduces control structures, specifically decision-making and branching statements in C.

Uploaded by

sanjanashintri
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
You are on page 1/ 32

C Programming

UNIT 2: Input and Output statements AndControl structures & Array

Input and Output statements

To perform the input-output operations C provides a library of functions.


This library is called a standard input-output library. It is denoted by stdio. The header file
containing such library functions is called stdio.h.
The file name stdio.h is an abbreviation for standard input-output header file. The instruction
#include<stdio.h> tells the compiler to search for a file named stdio.h and place its contents at this
point in the program.

Input Statements Output Statements

Formatted scanf() printf()

UnFormated getchar() putchar()

gets() puts()

Formatted Input Statements

The scanf( )is used to read the values from the Keyboard.
General form of scanf( ) is: scanf(“control string” , arg1,arg2,….argn);
Where,
 control string: It is a sequence of one or more character groups. Each character group is a
combination of the % symbol.
 arg1,arg2,….: It specifies the address of memory locations where the values of input variables
should be stored.
Example: scanf (“%d%d”, &num1,&num2);
scanf (“%f%f%f”, &principal,&time,&rate);
//Program to demonstrate formatted input reading integers
#include<stdio.h>
void main()
{

int num1,num2,num3,num4,num5;
int n1,n2,n3;
printf("Enter three integer numbers\n");
scanf("%d %d %d",&num1,&num2,&num3);
printf("%d %d %d \n\n",num1,num2,num3);
printf("Enter two 4-digit numbers\n");
scanf("%d %d",&num4,&num5);
printf("%d %d\n\n", num4,num5);
printf("Enter two integers\n");
scanf("%d %d", &num1,&num4);
printf("%d %d \n\n",num1,num4);
printf("Enter a nine digit number\n");
scanf("%3d %4d%3d",&n1,&n2,&n3);
printf("%d %d %d \n\n",n1,n2,n3);
}

Output
Enter three integer numbers
123
123
Enter two 4-digit numbers
1234 5678
1234 5678
Enter two integers
45 23
45 23
Enter a nine digit number
123456789
123 4567 89
//Program to demonstrate formatted input reading real numbers
#include<stdio.h>
void main()
{
float num1,num2;
double n1,n2;
printf("Values of num1 and num2:");
scanf("%f %e", &num1, &num2);
printf("\n");
printf (“num1 = %f\n%num2 =%f\n\n",num1,num2);
printf("Values of n1 and n2:");
scanf("%lf %1f", &n1, &n2);
printf ("\nn1=% 0.121f \nn2=%.12e" ,n1,n2) ;
}

Output
Values of num1 and num2:
12.3456
0.175000
num1 = 12.345600
num2 =0.175000
Values of n1 and n2:
12.12345678901234
90.12345678899000123
n1=12.1234567890123410000000
n2=5.393060591784e-315

//Program to demonstrate formatted input reading characters

#include<stdio.h>
void main()
{
int no;
char namel [15], name2 [15], name3[15];
printf("Enter serial number and name one\n");
scanf("%d %15c", &no, namel);
printf("%d %15s\n\n", no, namel);
printf("Enter serial number and name two\n");
scanf("%d %s", &no, name2);
printf("%d %15s\n\n", no, name2);
printf("Enter serial number and name three\n");
scanf("%d %15s", &no, name3);
printf("%d %15s\n\n", no, name3);
}

Output 1: Output 2:
Enter serial number and name one Enter serial number and name one
1 123456789012345 1 123456789012345
1 123456789012345 1 123456789012345
Enter serial number and name two Enter serial number and name two
2 New York 2 NewYork
2 New 2 NewYork
Enter serial number and name three Enter serial number and name three
2 § 3 London
3 London

Table 1: Character groups

Character group Meaning


%c Read a single character
%hd Read short integer
%d Read a decimal integer
%ld Read long decimal integer
%f Read a floating-point number
%lf Read double
%s Read a string
%o Read octal integers
%x Read hexadecimal integers
Formatted Output Statements
printf( )is used to display the data on the screen or monitor.
The general form of printf( ) function is: printf (“ control string” , arg1,arg2,…..argn);
Where,
 control stringà specifies the type and format of the values to be displayed.
 arg1,arg2…..à is a list of variables to be displayed on the monitor.
Examples: printf (“C is a Programming language”);
printf (“Sum of a and b = %d”, sum);

//Program to demonstrate formatted output of integers


#include<stdio.h>
void main()
{
int num1 = 12345;
long num2 = 987654; Output
printf (“\n%d \n”,num1) ; 12345
printf(“%10d\n”,num1); 12345
printf(“%010d\n”,num1); 0000012345
printf (“%-10d\n”,num1) ; 12345
printf (“% 10ld \n” ,num2) ; 987654
printf(“%10ld\n”,-num2); -987654
}

//Program to demonstrate Formatted output of real numbers

#include<stdio.h>
void main()
{
float num=98.7654; Output:

printf(“%7.4f\n”, num); 98.7654

printf(“%f\n”, num); 98.765404

printf(“%7.2f\n”, num); 98.77

printf(“%-7.2f\n”, num); 98.77

printf(“%07.2f\n”, num); 0098.77

printf(“%*.*f”, 7, 2, num); 98.77

}
//Program to demonstrate formatted output of characters
#include<stdio.h>
void main()
{
char name [20] = “ANIL KUMAR GUPTA”;
char x = ‘A’;
printf(“OUTPUT OF CHARACTERS\n\n”);
printf(“%c\n%3c\n%5c\n”, x,x,x);
printf(“%3c\n\%c\n”, x,x);
printf(“\n”);
printf(“OUTPUT OF STRINGS\n\n”);
printf(“%s\n”, name);
printf(“%20s\n”, name);
printf(“%20.10s\n”, name);
printf(“%.5s\n”, name);
printf(“%-20.10s\n”, name);
printf(“%5s\n”,name);
}

Output:
OUTPUT OF CHARACTERS
A
A
A
A
A
OUTPUT OF STRINGS
ANIL KUMAR GUPTA
ANIL KUMAR GUPTA
ANIL KUMAR
ANIL
ANIL KUMAR
ANIL KUMAR GUPTA
UnFormatted Input Statements

getchar( ): The getchar( ) is used to read a single character from the keyboard(Reading a
character).
General form is: variable_name = getchar( );
where:variable_name is type char variable containing a character.
Example: char character;
character = getchar()
// C program to implement getchar()// function to read single character
#include <stdio.h>
int main()
{
char character;
printf(“Enter a character:\n”);
Output:
/* input a character */
Enter a character:
character = getchar();
y
printf("The entered character is : %c", character);
The entered character is : y
return 0;
}

gets( ): The gets( ) is used to read everything you can enter from the keyboard until the ENTER key
pressed.
General form is: gets(string );
where: string is sequence of character to be displayed on screen
Example: char name[5];
gets(name)
// C program to implement gets() reading your name
#include <stdio.h>
int main()
{ Output:
char name[10]; Enter your name: Riya
printf("Enter a your name: "); You entered: Riya
/* Enter your name */
gets(name);
printf("You entered: %s\n", name);
return 0;
}
UnFormatted Output Statements
putchar( ): The putchar( ) is used to display single character on the screen or writing characters one at
a time to the terminal(Writing a Character).

General form is: putchar(variable_name );


where:variable_name is type char variable containing a character.
Example 1: Example 2:
answer = ‘Y’;
putchar(‘\n’)
putchar(answer)

// A program that reads a character from keyboard and then prints it in reverse case
#include <stdio.h>
#include<ctype.h> Output 1:
void main()
Enter an alphabet
{
char alphabet; a
printf("Enter an alphabet"); A
putchar('\n'); /* move to next line */
alphabet = getchar();
if (islower (alphabet)) Output 2:
putchar (toupper(alphabet));/* Reverse and display */
Enter an alphabet
else
putchar (tolower(alphabet));/* Reverse and display */ D
} d

puts( ): The puts( ) is used to prints a string of characters on the screen.


General form is: puts(string );
where:string is sequence of characterto be displayed on screen
Example 1: Example 2:
answer = ‘Yes’; puts(“Hello word”)
puts(answer)

// C program to illustrate the use of puts() function

#include <stdio.h>
int main()
{
// using puts to print hello world Output:
char answer = "Hello world";
Hello world
puts(answer);
puts("Welcome to KLE"); Welcome to KLE
return 0;
}
Functions used in character test are:
Function Test
isalnum(c) Is c an alphanumeric character?
isalpha(c) Is c an alphabetic character?
isdigit(c) Is c digit?
islower(c) Is c lower case letter?
isprint(c) Is c printable character?
ispunct(c) Is c punctuation mark?
isspace(c) Is c white space character?
isupper(c) Is c upper case letter?

The prototypes of character functions are contained in the file ctype.hand the statement.
#include<ctype.h>
Function Description Return Values
isalnum() This function identifies the Returns 0 if the passed argument is non –
alphanumeric characters alphanumeric character
Returns non zero value if the passed argument is
alphanumeric character
isalpha() This function identifies the Returns 0 if the passed argument is not an alphabet
alphabets from other characters Returns non zero value if the passed argument is an
alphabet
isdigit() This function identifies numbers Returns 0 if the passed argument is not a number
in character. Returns nonzero value if the passed argument is a
number
islower() This function identifies the Returns 0 if the passed argument is not a lowercase
lowercase alphabets. alphabet
Returns nonzero value if the passed argument is a
lowercase alphabet
isprint() This function identifies the Returns 0 if the passed argument is a non printable
printable characters. character
Returns nonzero value if the passed argument is a
printable character
ispunct() This function identifies Returns 0 if the passed argument is not a punctuation
punctuation characters (characters character
that are neither alphanumeric nor Returns nonzero value if the passed argument is a
space). punctuation character
isspace() This function identifies white- Returns 0 if the passed argument is not a white-space
space characters. character
Returns nonzero value if the passed argument is a
white-space character
isupper() This function identifies the Returns 0 if the passed argument is not an uppercase
uppercase alphabets. alphabet
Returns nonzero value if the passed argument is an
uppercase alphabet
// C program to demonstrate built in functions for character test

#include <stdio.h>
#include <ctype.h> // for character functions

int main()
{
char c = 'A';

// Check if alphanumeric
if (isalnum(c)) {
printf("'%c' is alphanumeric.\n", c);
} else {
printf("'%c' is not alphanumeric.\n", c);
}

// Check if alphabetic
if (isalpha(c)) {
printf("'%c' is alphabetic.\n", c);
} else {
printf("'%c' is not alphabetic.\n", c);
}

// Check if digit
if (isdigit(c)) {
printf("'%c' is a digit.\n", c);
} else {
printf("'%c' is not a digit.\n", c);
}

// Check if lowercase
if (islower(c)) {
printf("'%c' is lowercase.\n", c);
} else {
printf("'%c' is not lowercase.\n", c);
}

// Check if printable
if (isprint(c)) {
printf("'%c' is printable.\n", c);
} else {
printf("'%c' is not printable.\n", c);
}

// Check if punctuation
if (ispunct(c)) {
printf("'%c' is punctuation.\n", c);
} else {
printf("'%c' is not punctuation.\n", c);
}

// Check if whitespace
if (isspace(c)) {
printf("'%c' is a whitespace character.\n", c);
} else {
printf("'%c' is not a whitespace character.\n", c);
}

// Check if uppercase
if (isupper(c)) {
printf("'%c' is uppercase.\n", c);
} else {
printf("'%c' is not uppercase.\n", c);
}

return 0;
}
Output:
'A' is alphanumeric.
'A' is alphabetic.
'A' is not a digit.
'A' is not lowercase.
'A' is printable.
'A' is not punctuation.
'A' is not a whitespace character.
'A' is uppercase.

Control Structures
• There may be situations where the programmer requires to alter normal flow of execution of
program or to perform the same operation a number of times.
• Various control statements supported by C are
o Decision making and Branching
o Decision making and Looping

Decision Making and Branching


• Decision control statements alter the normal sequential execution of the statements of the program
depending upon the test condition to be carried out at a particular point in program.
• Decision control statements supported by c are
o if statement
o if-else statement
o Else if Ladder
o Nested If
o switch statement
 if statement
Most simple and powerful decision control statement. It executes a statement or block of statements
only if the condition is true.

In above syntax: ifcondition is true only then the statements within the block of ifare executed
otherwise next statement in sequence is executed.

// Program to demonstrate simple if statement


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

// Input age
printf("Enter the age:\n");
scanf("%d",&age);

if(age>= 18)
printf("Your allowed to vote");
}

Output:
Enter the age:
20
Your allowed to vote
 if-else statement
If specific statements are to be executed in both cases (either condition is true or false)
then if – else statement is used.

In if – elsestatement a block of if statements are executed if the condition is true, else different
block of else statements are executed when the condition is false.

// Program to demonstrate if-else statement


#include<stdio.h>
void main()
{
int age;
// Input age
printf("Enter your the age:\n");
scanf("%d",&age);
if(age>18)
printf("Your allowed to vote");
else
printf("Your not allowed to vote")
}

Output 1: Output 2:
Enter your the age: Enter your the age:
4 40
Your not allowed to vote Your allowed to vote
 Nested If
When an entire if-else is enclosed within the body of if statement or/and in the body of else statement,
it is known as nested if-else statement.The ways of representing nested if –else are-

The logic of execution is, If the condition-1 is false, the 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 next
statement.

// Program to demonstrate Nested if statement


#include<stdio.h>
void main()
{
// Initialization of 3 numbers
int num1,num2,num3;

printf("Enter three numbers\n");

// Input numbers
scanf("%d%d%d",&num1,&num2,&num3);

// Comparing num1 and num3 which is largest


if(num1>num3)
{
// Comparing num1 and num2 which is largest number
if(num1>num2)
{
// Printing num1 as largest number
printf("num1 is largest number");
}
else
{
// Printing num2 as largest number
printf("num2 is largest number");
}
}
// Comparing num2 and num3 which is largest number
else
{
if(num2>num3)
// Printing num2 as largest number
printf("num2 is largest number");
else
// Printing num3 as largest number
printf("num3 is largest number");
}
}

Output 1: Output 2: Output 3:


Enter three numbers Enter three numbers Enter three numbers
80 50 35
30 80 87
20 72 88
num1 is largest number num2 is largest num3 is largest number
number
 Else if Ladder
In a program involving multiple conditions, the nested if else statements make the program very
difficult to write and understand if nested more deeply.

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 it is executed and the
control is transferred to the next statement (skipping the rest of the ladder). When all the n conditions
become false, then the final else containing the default statement will be executed.
Rules for Indentation
• Indent statements that are dependent on the previous statements; provide at least three spaces of
indentation.
• Align vertically else clause with their matching if clause.
• Use braces on separate lines to identify a block of statements.
• Align the opening and closing braces.
• Indent the statements in the block by at least three spaces to the right of the braces.
• Use appropriate comments to signify the beginning and end of blocks.
• Indent the nested statements as per the above rules.
• Code only one clause or statement on each line

// Program to demonstrate else-if ladder statement

#include<stdio.h>
void main()
{
int num;
// Input a number
printf("Enter a number: ");
scanf("%d", &num);

// Check if the number is positive


if (num > 0)
{
printf("%d is a positive number.\n", num);
}

// Check if the number is negative


else if (num < 0)
{
printf("%d is a negative number.\n", num);
}
else
{
printf("The number is zero.\n");
}
}

Output 1: Output 2: Output 3:


Enter a number: 90 Enter a number: -90 Enter a number: 0
90 is a positive number. -90 is a negative number. The number is zero.
num

 
switch statement
 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 are
known as case variables.
 When the switch is executed, the value of the expression is successfully 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.
 The break statement at the end of each block signals 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 matches fail
and the control goes to the statement-x.

// Program to demonstrate switch statement


#include <stdio.h>
void main()
{
int percent;
printf("Enter your percentage: ");

// Input percentage
scanf("%d",&percent);

// Print grade of student using switch statement


switch (percent)
{
// Print Grade A if percentage is above 75
case 75 ... 100:
printf("Grade A: First class with distinction\n");
break;

// Print Grade B if percentage is between 60 to 74


case 60 ... 74:
printf("Grade B: First class\n");
break;

// Print Grade C if percentage is between 50 to 59


case 50 ... 59:
printf("Grade C: Second class\n");
break;

// Print Grade D if percentage is between 35 to 49


case 35 ... 49:
printf("Grade D: Pass class\n");
break;

// Print Grade F if percentage is below 34


case 0 ... 34:
printf("Grade F: Fail");
break;

// Print invalid if percentage is not valid


default:
printf("Invalid percentage");
break;
}
}

Output 1: Output 2: Output 3:


Enter your percentage: Enter your percentage: Enter your percentage:
54 70 54
Grade C: Second class Grade B: First class Grade C: First class with
num distinction

Go-To Statement
An unconditional control statement that causes the control to jump to a different location in the
program without checking any condition. It is normally used to alter the normal sequence of program
execution by transferring control to some other part of the program.So it is also called jump statement.
Label variable name, and must be followed by a colon. The label is placed immediately before the
statement where the control is to be transferred.

// Program to demonstrate go-to statement


#include <stdio.h>
#include <math.h>
void main()
{
double x, y;
read: // label
printf("Enter a number (0 to exit): ");
scanf("%lf", &x);
if (x < 0)
{
printf("Negative number, please enter a positive number.\n");
goto read;
}
if (x == 0)
{
return; // Exit the program when 0 is entered Output:
}
Enter a number (0 to exit): 9
y = sqrt(x);
printf("Square root of %f is %f\n", x, y); Square root of 9.000000 is 3.000000
goto read; // Jump back to read for new input
Enter a number (0 to exit): 16
}
Square root of 16.000000 is 4.000000
Enter a number (0 to exit): 0

Decision Making and Looping


When we want to repeat a group of statements a number of times, loops are used.These loops are
executed until the condition is true.When condition becomes false, control terminates the loop and
moves on to next instruction immediately after the loop.
Various looping structures are-
 while (entry-controlled loop)
 do – while (exit controlled loop)
 for (entry-controlled loop)

A looping process
In general, would include the following four steps:
1. Setting and initialization of a condition variable.
2. Execution of the statements in the loop.
3. Test for a specified value of the condition variable for execution of the loop.
4. Incrementing or updating the condition variable.
 while (entry-controlled loop)
The while is an entry-controlled loop statement. The test-condition is evaluated and if the condition is
true, then the body of the loop is executed.

After execution of the body, the test-condition is once again evaluated and if it is true, the body is
executed once again. This process of repeated execution of the body continues until the test-condition
finally becomes false and the control is transferred out of the loop.

// Program to demonstrate while statement

#include <stdio.h>
void main()
{
int n, sum = 0, i = 1;
// Input the value of n
printf("Enter a positive integer: ");
scanf("%d", &n);

// While loop to calculate the sum of first n numbers


while (i <= n)
{
sum += i; // Add i to sum
i++; // Increment i
}
printf("Sum of first %d numbers is: %d\n", n, sum);
}

Output:
Enter a positive integer: 5
Sum of first 5 numbers is: 15
 do – while (exit controlled loop)
On some occasions it might be necessary to execute the body of the loop before the test is performed.
Such situations can be handled with the help of the do statement. On reaching the do statement, the
program proceeds to evaluate the body of the loop first. At the end the loop, the test-condition in the
while statement is evaluated. If the condition is true, the program continues to evaluate the body of the
loop once again. This process continues as long as the condition is true. When the condition becomes
false, the loop will be terminated.
Since the fest-condition is evaluated at the bottom of the loop, the do...while construct provides an
exit- controlled loop and therefore the body of the loop is always executed at least once.

// Program to demonstrate do-while statement


#include <stdio.h>
#include <stdio.h>

void main()
{
int n, sum = 0, i = 1;

// Input the value of n


printf("Enter a positive integer: ");
scanf("%d", &n);

// Do-while loop to calculate the sum of first n numbers


do
{
sum += i; // Add i to sum
i++; // Increment i Output:
} while (i <= n);
Enter a positive integer: 5
printf("Sum of first %d numbers is: %d\n", n, sum); Sum of first 5 numbers is: 15
}
 for (entry-controlled loop)
The for loop is another entry-controlled loop that provides a more concise loop control structure.

Example: for(i=0 ; i<10 ; i++)

The execution of the for statement is as follows:


1. Initialization of the control variables is done first, using assignment statements such as i = 1 and
count = 0, The variables i and count are known as loop-control variables.
2. The value of the control variable is tested using the test-condition. The test-condition is a relational
expression, such as i< 10 or i> 0. If the condition is true, the body of the loop is executed;
otherwise, the loop is terminated and the execution continues with the statement that immediately
follows the loop.
3. When the body of the loop is executed, the control is transferred back to the for statement after
evaluating the last statement in the loop. Now, the control variable is incremented or decremented
using an assignment statement such as i = i + 1 or i = i - 1 and the new value of the control
variable is again tested to see whether it satisfies the loop condition. If the condition is satisfied,
the body of the loop is again executed. This process continues till the value of the control variable
fails to satisfy the test-condition.

// Program to demonstrate simple for loop statement


#include <stdio.h>
void main()
{
int n, sum = 0,i;

// Input the value of n


printf("Enter a positive integer: ");
scanf("%d", &n);

// For loop to calculate the sum of first n numbers


for (i = 1; i <= n; i++)
{
sum += i; // Add i to sum
} Output:
printf("Sum of first %d numbers is: %d\n", n, sum);
Enter a positive integer: 5
}
Sum of first 5 numbers is: 15
Nesting of for Loops
Nesting of loops, that is, one for statement within another for statement, is allowed in C. For example,
two loops can be nested as follows:

// Program to demonstrate nested for loop statement


#include <stdio.h>

void main()
{ Output:
int i, j;
1 2 3 4 5

// Outer loop to print a multiplication table 2 4 6 8 10


for (i = 1; i <= 5; i++)
{ 3 6 9 12 15
// Inner loop
for (j = 1; j <= 5; j++) 4 8 12 16 20
{
printf(%d\t", i * j); 5 10 15 20 25
}
printf("\n");
}
}

Jumps in Loop
Loops perform a set of operations repeatedly until the control variable fails to satisfy the test-
condition. The number of times a loop is repeated is decided in advance and the test condition is
written to achieve this. Sometimes, when executing a loop it becomes desirable to skip a part of the
loop or to leave the loop as soon as a certain condition occurs.C permits a jump from one statement to
another within a loop as well as a jump out of a loop.
 Jumping Out of a Loop

Exit from a loop can be accomplished by using the break statement or the goto statement.

Example for goto statement


for (m=1;m<=3;m++)
{
for (n=1;n<=2;n++)
{
if (m==n)
goto error;
printf(“ m=%d n=%d”);
}
}
error;

Break statement
Break statement terminates the execution of the loop in which it is defined.The control is transferred
immediately to the next executable statement after the loop.

It is mostly used to exit early from the loop by skipping the remaining statements of loop or switch
control structures.
Example
for (m=1;m<=3;m++)
Output:
{
for (n=1;n<=2;n++) 1 2
{
if (m==n) 2 1
break; 3 1
printf(“ m=%d n=%d”);
}
}

 Skipping a Part of Loop


During the loop operations, it may be necessary to skip a part of the body of the loop under certain
conditions.C supports another similar statement called the continue statement .

Continue Statment
• Like break ,continue statement also skips the remaining statements of the body of the loop where it
is defined but instead of terminating the loop, the control is transferred to the beginning of the loop
for next iteration.

• The loop continues until the test condition of the loop become false.
Example
for (m=1;m<=3;m++) Output:
{
for (n=1;n<=2;n++) 1 2
{ 2 1
if (m==n)
continue; 3 1
printf(“ m=%d n=%d”);
3 2
}
}

 Jumping Out Of The Program

• We have just seen that we can jump out of a loop using either the break statement or goto
statement. In a similar way, we can jump out of a program by using the library function exit().
• The exit() function takes an integer value as its argument.

• Normally zero is used to indicate normal termination


• Nonzero value to indicate termination due to some error or abnormal condition. The use of exit()
function requires the inclusion of the header file <stdlib.h>.

Array
An array is a fixed-size sequenced collection of elements of the same data type.
Some examples where the concept of an array can be used:
• List of temperatures recorded every hour in a day, or a month, or a year.
• List of employees in an organization.
• List of products and their cost sold by a store.
• Test scores of a class of students.
A list of terms may be given one variable name, and the individual elements may be accessed by the
specification of their relative positions with respect to the start of the list. Such relative positions are
referred to as the index or subscript of the element.
One-dimensional Array
A list in which the elements are accessible by the variable name assigned to the list and its subscript is
known as a one- dimensional array. For instance, we use the equation.The subscripts of an array can be
integer constants, integer variables like the declared limits i, or expressions that yield integers.
Declaration of One-Dimensional Array: datatype array_name[size]
Where:
• Type specifies the type of element (int, float, char)
• Size indicate the maximum number of elements that array can hold
Tip: In C array subscripts begin at 0.

Example:
float height[50];
int number[5];
char name[5]

Memory Allocation
int number[5];

The computer reserves five The values to the array This would cause the
storage locations as shown elements can be assigned array number to store the
below: as follows: values as shown
number[0] number[0] = 10 number[0] 10
number[1] number[1] = 20 number[1] 20
number[2] number[2] = 30 number[2] 30
number[3] number[3] = 40 number[3] 40
number[4] number[4]= 50 number[4] 50

Initialization One-dimensional Array


After an array is declared, its elements must be initialized. Otherwise, they will contain "garbage".
An array can be initialized at stages:
• At compile time
• At run time
 At compile time
We can initialize the elements of arrays in the same way as the ordinary variables when they are
declared.

 Example1:int number[3]={0,0,0};
 Example2:float number[5]={0.0, 15.75, -10.0};
Will initialize the first three elements to 0.0, 15.75, and-10.0 and the remaining two elements to
zero. The size may be omitted. In such cases, the compiler allocates enough space for all initialized
elements.
 Example3:
Character arrays may be initialized in a similar manner. Thus, the statement
char name[] ={'J','o', 'h', 'n', '\0’); OR char name[5] = “John”;

// Program to demonstrate Compile Time Initialization 1D-array

#include <stdio.h>
int main()
{
// Method 1: Using character array with individual characters
int i;
char name1[] = {'J', 'o', 'h', 'n', '\0'}; // Explicitly null-terminated

// Method 2: Using string literal


char name2[5] = "John"; // Automatically null-terminated

// Displaying individual elements of name1


printf("Displaying individual elements of name1:\n"); Output:
for (i = 0; i< 4; i++)
{ Displaying individual elements of
// Looping through the first 4 characters name1:
printf("name1[%d] = '%c'\n", i, name1[i]); name1[0] = 'J'
}
name1[1] = 'o'
// Displaying the entire string name1[2] = 'h'
printf("\nFull string from name1: %s\n", name1); name1[3] = 'n'
printf("Full string from name2: %s\n", name2);
Full string from name1: John
}
Full string from name2: John

 At run time
An array can be explicitly initialized at run time. This approach is usually applied for initializing large
arrays.

Example:
for(i-0; i<100; i++)
{
if(i<50)
sum[i]=0.0;
else
sum[i]=1.0;
}
The first 50 elements of the array sum are initialized to zero while the remaining 50 elements are
initialized to 1.0 at run time.

We can also use a read function such as scanf to initialize an array.


Example:
int x [3];
scanf("%d%d%d", &x[0], &[1], &x[2]);
will initialize array elements with the values entered through the keyboard, at runtime.

// Program to demonstrate Run Time Initialization of 1D-array


void main()
{
int x[3]; // Declare an array of size 3
// Prompt the user for input
printf("Enter three integers: ");
// Read three integers into the array
scanf("%d%d%d", &x[0], &x[1], &x[2]);
// Display the entered values in the format x[0], x[1], x[2]
printf("Values of array X are:\n");
Output:
printf("x[0] = %d\n", x[0]);
Enter three integers: 3 4 6
printf("x[1] = %d\n", x[1]); Values of array X are:
printf("x[2] = %d\n", x[2]); x[0] = 3
} x[1] = 4
x[2] = 6
Two-dimensional Array
C allows us to define tables of items by using two-dimensional arrays. Two dimensional array can be
represented as table. We can think table as a matrix consisting of rows and columns.

Example:
int number[3][3];

Initialization Two-dimensional Array


Two-dimensional arrays may be initialized by following their declaration with a list of initial values
enclosed in braces.

• When the array is completely initialized with all values, explicitly, we need not specify the size of
the first dimension as shown in example 2.
• If the values are missing in an initializer, they are automatically set to zero (example3).
// Program to demonstrate Compile Time Initialization of 2D-array

#include <stdio.h>
void main()
{
// Initialization in a single line
// int table1[2][3] = { 0, 0, 0, 1, 1, 1 };
int i,j;

// Method 2: Initialization using nested curly braces


int table1[2][3] =
{
{0, 0, 0},
{1, 1, 1}
};
// Displaying the contents of table1
printf("Contents of table1:\n");
for (i = 0; i< 2; i++)
{
for (j = 0; j < 3; j++)
{
printf("table1[%d][%d] = %d\t", i, j, table1[i][j]);
}
printf("\n");
}
}

Output:
Contents of table1:
table1[0][0] = 0 table1[0][1] = 0 table1[0][2] = 0
table1[1][0] = 1 table1[1][1] = 1 table1[1][2] = 1

We can also use a read function such as scanf to initialize an array.


Example:
int table[2][2];
for (i = 0; i< rows; i++)
{
for (j = 0; j < cols; j++)
{
printf("Element at [%d][%d]: ", i, j);
scanf("%d", &table[i][j]);
}
}
will initialize array elements with the values entered through the keyboard, at runtime.
// Program to demonstrate Run Time Initialization od 2D-array
#include <stdio.h>

void main()
{
int rows, cols;
// Taking input for number of rows and columns
printf("Enter number of rows: ");
scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);

int table[rows][cols]; // Declare a 2D array with user-defined size


int i,j;

// Input values for the 2D array from the user


printf("Enter the elements of the array:\n");
for (i = 0; i< rows; i++)
{
for (j = 0; j < cols; j++)
{
printf("Element at [%d][%d]: ", i, j);
scanf("%d", &table[i][j]);
}
}
// Display the 2D array
printf("\nThe 2D array is:\n");
for (i = 0; i< rows; i++)
{
for (j = 0; j < cols; j++)
{
printf("%d\t", table[i][j]);
} Output:
printf("\n"); Enter number of rows: 2
}
Enter number of columns: 2
}
Enter the elements of the array:
Element at [0][0]: 10
Element at [0][1]: 20
Element at [1][0]: 30
Element at [1][1]: 40
The 2D array is:
10 20
30 40
Multi-dimensional Array
C allows arrays of three or more dimensions.

Example:
int survey[2][5][12];

You might also like