Professional Documents
Culture Documents
1. while loop
2. do-while loop.
3. for loop.
The statement of the loop may have one or more statements. The statements
in the while loop is executed zero or more times depending on the test condition. If
the test condition evaluates to false at the first time, then the statements are never
executed.
Ex:
int i=1;
while(i<=10)
{
printf(“\n C Language”);
i++;
}
In the above example the variable ‘i’ starts with the value 1. The statements in
the while loop will be executed 10 times.
OUTPUT
2 4 6 8 10 12 14 16 18 20
22 24 26 28 30 32 34 36 38 40
42 44 46 48 50
The do-while is a exit – controlled loop. The while loop makes a test of
condition before the loop is executed. Therefore, the statements of the loop may not
be executed at all if the condition is not satisfied at the very first attempt. 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-while statement.
do
{
loop statements
}while (test-condition);
Since the test-condition is evaluated at the bottom of the loop, the do-while
construct provides an exit-controlled loop and therefore the statements of the loop is
always executed at least once.
Ex:
i=1;
do
{
printf(“\n C Language”);
i++;
}while(i<=10);
# include “stdio.h”
# include “conio.h”
main()
{
int i=1, range;
clrscr();
printf(“\n Enter range”);
scanf(“%d”,&range);
do
{
if(i%2!=0)
printf(“\t %d”, i);
i++;
}while(i<=range);
getch( );
}
The for loop is entry-controlled loop that provides a more concise loop
control structure. The general form of the for loop is
The for loop in ‘C’ has several capabilities that are not found in other loop
constructs.
i) More than one variable can be initialized at a time in the for statement.
Ex: for(p=1,n=0;n<17;n++)
Like the initialization section, the updation section may also have more than
one part.
The multiple arguments in the initialization section and increment section are
separated by commas.
i) Test-condition may have any compound relation and the testing need not
be limited to the loop control variable.
Ex: sum=0;
Ex: for(x=(m+n)/2;x>0;x=x/2)
iv) Another unique aspect of for loop is that one or more sections can be
omitted, if necessary.
Ex: m=5;
for(;m!=100;)
{
printf(“%d”,m);
m=m+5;
}
vi) We can set up time delay loops using the null statement as follows
for(j=1000; j>0; j=j-1);
This loop is executed 1000 times without producing any output; it simply
causes a time delay. The body of the loop contains only a semicolon, known as a
null statement.
Nesting of loops:
In the above example the printf() statement will be executed 100 times.
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,r,t;
clrscr();
printf("Enter no.of rows:");
scanf("%d",&r);
t=0;
for(i=1;i<=r;i++)
{
for(j=1;j<=i;j++)
{
if(t%2==0)
printf("0");
else
printf("1");
t++;
}
printf("\n");
}
getch();
}
OUTPUT
#include<stdio.h>
#include<conio.h>
void main()
{
int i,j,rows;
clrscr();
printf("Enter no.of rows:");
scanf("%d",&rows);
for(i=1;i<=rows;i++)
{
for(j=1;j<=i;j++)
{
printf("*");
}
printf("\n");
}
getch();
}
OUTPUT
Syntax:
goto label_name;
..
..
label_name: C-statements
EX:
#include<stdio.h>
#include<conio.h>
void main()
{
int sum=0;
for(int i = 0; i<=10; i++)
{
sum = sum+i;
if(i==5)
{
goto addition;
}
}
ARRAYS
An array is a set of similar data items that share a common name. The
individual values in an array are called elements. The elements of an array can be of
any data type. All the elements in an array must be of the same type. Array
elements are variables. A particular value is indicated by writing a number called
index number (or) subscript in brackets after the array name. There are two types of
arrays :
1. One-dimensional arrays.
2. Multi-dimensional arrays.
One-dimensional arrays
If a list of items are given one variable name using only one subscript, then it is
called a one-dimensional array.
Where data type should be a valid data type. array_name is the name of the
array and size is the number of elements of the array.
In the above declaration ‘a’ is the name of the array, 20 is size of the array.
Initialising of Arrays : The elements of the array may be initialised when they are
declared. The general form of initialisation of array is :
type array_name[size] = { list of values };
This will declare the variable ‘number’ as an array of size 3 and will assign
zero to each element.
Will initialise the first three elements to 0.0, 15.75, –10.0 and the remaining
two elements to garbage values.
The size may be omitted, in such cases, the compiler allocates enough space
for all initialised values. The above example declares the counter array to contain
Four elements with initial values 1.
Ex: main()
{
int a[10];
int i;
for(i=0;i<10;i++)
scanf(“%d”,&a[i]);
}
The ‘for’ loop in the above example assigns values from keyboard to array elements.
Values can also be assigned to individual elements of an array, just like any other
elements.
Ex: main ()
{
float b[10];
int i;
clrscr();
for(i=0; i<10; i++)
scanf(“%f”, &b[i]);
printf(“Array elements are:\n”);
for(i=0; i<10; i++)
printf(“%f\t”,b[i]);
getch();
}
In the above example first for loop assigns the values to elements of array b
from keyboard second for loop displays the elements of array b on console.
Displays as follows
10 20 30 40 ……………………… 100
If required element is 85
Element not found in the array.
Ex: Searching for an element
#include <stdio.h>
void main()
{
int a[100], n, i,el;
int flag;
clrscr();
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter Array elements:”);
for (i = 0; i< n; i++)
scanf("%d", &array[i]);
printf("Enter a number to search:");
scanf("%d", &el);
for (i = 0;i < n;i++)
{
if (a[i] == el)
{
flag==1;
break;
}
}
if (flag ==1)
printf(“elements is found”);
else
printf({“element is not found”);
getch();
}
a 3 6 9 10 12 - - - - -
0 1 2 3 4 5 6 7 8 9
Inserting element 8 after 9 will rearray gets as shown
a 3 6 9 8 10 12 - - - -
0 1 2 3 4 5 6 7 8 9
Similarly we can delete an element from the array.
Ex:
If int a[6]={8,9,10,4,7,12};
a 8 9 10 4 7 12
0 1 2 3 4 5
After deleting an element ‘4’ from array
a 8 9 10 7 12 --
0 1 2 3 4 5
6. Merging Arrays:
We can merge arrays i.e we can append second array form the last element of the
first array.
Ex: int a[10]={4,5,6,7};
Int b[6] ={8,9,10,11};
After merging ‘b’ with ‘a’, array a become
a 4 5 6 7 -- -- -- -- -- --
0 1 2 3 4 5 6 7 8 9
b 8 9 10 11 -- --
0 1 2 3 4 5
After merging
a 4 5 6 7 8 9 10 11 -- --
b 8 9 10 11 -- --
0 1 2 3 4 5 6 7 8 9
Character Arrays
Ex : main ()
{
char word [ ] = {‘H’, ‘e’, ‘l’, ‘l’, ‘o’ , ‘!’};
int i;
for(i=0; i<10; i++)
printf(“%c”, word[i]);
getch();
}
word
H e l l o !
word[0] word[1] word[2] word[3] word[4] word[5]
The for loop displays each character in the array and output will be “Hello!”
#include<stdio.h>
#include<conio.h>
void main()
{
char str[10];
int i,j;
char temp;
printf("Enter characters :");
for(i=0;i<10;i++)
scanf("%c",&str[i]);
for(i=0;i<10;i++)
{
for(j=i+1;j<10;j++)
{
if(str[i]>str[j])
{
temp=str[i];
str[i]=str[j];
str[j]=temp;
}
}
}
printf("\nAfter sorting:\n”);
for(i=0;i<10;i++)
printf(“%c”,str[i]);
getch();
}
The const Qualifier : ‘const’ qualifier is associated with variable whose value will
not be changed by the program. Using ‘const’ qualifier, we can tell the complier that
the specified variable has a constant value throughout the program’s execution.
The above statement declares the const variable pi. If we try to assign a value
to a ‘const’ variable after initialising it, the complier might issue an error message.
The complier places the ‘const’ variables into read-only memory.
Array elements and array itself can be used in inter function communication.
Like an ordinary variables and values, it is also possible to pass the value of an array
element and even an entire array as an argument to a function.
In the above example the function disp() is called by passing first two
elements of an array as arguments and are received in similar type of arguments.
To pass an array to a function, it is only necessary to list the name of the array,
without any subscripts, inside the call to the functions.
Ex : main ()
{
int gradescores [100];
int minscore;
….. ….. ….
….. ….. ….
minscroe = minimum (gradescores);
}
int minimum (int values [100])
{
…… ……. ……
…… …….. ……
return (min value);
}
Ex : main ()
{
int a[50];
int *p1, i,n;
printf(“\n Enter no.of elements :”);
scanf(“%d”,&n);
printf(“\n Enter array elements :”);
for (i=0; i<n;i++)
scanf (“%d” & a[i]);
p1=&a[0];
display (p1,n);
getch();
}
void display (int *p2, int n)
{
int i;
for (i=0; i<n;i++)
{
printf(“\t %d”, * p2);
p2++;
}
}
In the above program array pointer and no.of elements in array are passed to
function display (). In function the arguments are received into formal arguments
(i) an integer pointer (ii) and integer value. The for loop in the function display ()
will access the array elements of array ‘a’ declared in main () using pointers.
Variable length arrays enables us to work with array without giving a constant size.
Ex : int a[20];
Ex : main ()
{
int size, i;
float sample[size];
printf(“Enter the size:”);
scanf(“%d”, &size);
for(i=0; i<size; i++)
scanf(“%f”, & sample[i]);
prinf(“Array Elements are:\n”);
for(i=0; i<size; i++)
printf(“\t%f”, sample[i]);
getch();
}
In the above example the array sample is declared to contain ‘size’ elements.
This is called a variable length array because the size of the array is specified by a
variable and not by a constant expression.
Where row-size refers to no. of rows and column-size refers to no. of columns.
Each dimension of the two dimensional array is indexed from zero to its maximum
size minus one. The individual elements of a two dimensional array can be referred
by two indexes (or) subscripts. The first index selects the row and the second index
selects the column within that row. The individual elements of the two dimensional
array will be stored in continuous memory locations.
This initialises the elements of the first row to zero and the second row to one.
The above statement can be written as
int table[2][3]={{0,0,0}, {1,1,1}};
(or)
int table[2][3]={
{0,0,0},
{1,1,1},
};
Ex: a[0][0]=25;
scanf (“%d”, & a[0][0]);
#include<stdio.h>
#include<conio.h>
main()
{
int a[10][10],i,j,r,c;
clrscr();
printf("Enter order of matrix:");
scanf("%d%d",&r,&c);
printf("Enter %d values",r*c);
for(i=0;i<r;i++)
for(j=0;j<c;j++)
scanf("%d",&a[i][j]);
printf("\nElements of array a:");
for(i=0;i<r;i++)
{
printf("\n");
for(j=0;j<c;j++)
{
printf("%d\t",a[i][j]);
}
}
getch();
}
OUTPUT
Enter order of matrix:2 2
Enter 4 values1
2
3
4
Elements of array a:
1 2
3 4
Character Strings
Array of Characters:
To print out the contents of the array ‘name’, we can run through each
element in the array and display it using the %c format characters.
C O M P U T E R \0
char string_name[size];
Where string_name is the name of the string and size is the size of the string.
char A[10]=” “;
scanf() and gets() functions are used to input values to string variables. printf() and
puts() functions are used to output values of string variables.
Scanf() function can be used to assign value to a string variable. By using scanf(),
multiword strings can’t be assigned to variables.
Ex: printf(“%s”,sname);
Ex:
#include “stdio.h”
#include “conio.h”
main()
{
char name[25];
printf(“Enter name:\n”);
scanf(“%s”, name);
printf(“The name is: %s”, name);
getch();
}
Input using gets():
Ex: gets(name);
main()
{
char str[20];
gets(str);
printf(“%s”, str);
getch();
}
Ex: puts(name);
puts (“strings”);
Above statement displays value of string variable name on monitor puts() can
output only one string at a time. puts() places the cursor automatically on the next
line.
Ex: main()
{
char name[25];
gets(name);
puts(name);
getch();
}
String Functions
String handling library functions are contained in the header file string.h. The
following list shows the more commonly used functions.
Function Meaning
strlen() Finds length of a string
strlwr() Converts a string to lower case
strupr() Converts a string to uppercase
strcat() Appends one string at the end of another
strncat() Appends first ‘n’ characters of a string at the end of another.
strcpy() Copies a string into another
strncpy() Copies first ‘n’ characters of one string into another
strcmp() Compares two strings
strncmp() Compares first ‘n’ characters of two strings
strchr() Finds first occurrence of a given character in a string.
strrchr() Finds last occurrence of a given character in a string.
strstr() Finds first occurrence of a given string in another string
strset() Sets all characters of string to a given character
strnset() Sets first n characters of a string to a given character
strrev() Reverses a string.
strlen():
This function return the length of the string i.e. the number of characters in the
string.
Ex: int c;
char name[20] = “location”;
c = strlen(name);
The above statement returns ‘8’ and assigns to C.
strcmp():
This function is used for comparison of two strings. If two strings are equal
strcmp() would return a value 0, otherwise it would return a non-zero value. This
function compares the string character by character.
strncmp():
strncmp(str1, str2, 4)
This function compares first 4 characters of str1 and str2 and returns 0 if they
equal and non zero if they are not equal.
int c;
c = strncmp(str1, str2, 3);
This statement returns < 0 and assigns to C, since characters of str2 is large
than characters of str1.
strcpy():
strncpy():
strcat():
strncat():
This function concatenates the string str1 with first 4 characters of s2.
strrev():
Ex: main()
{
char arr[25];
gets(arr);
strrev(arr);
printf(“\n String after reverse: %s”, arr);
}
strupr():
Ex: main()
{
char arr[25];
gets(arr);
strupr(arr);
printf(“\n After conversion: %s”, arr);
}
strlwr():
Ex: strlwr(str1);
strstr():
This function is used to find the occurrence of the given string in another
string.
strchr():
strrchr(): This function finds the last occurrence of a given character in a string.
strset():
strnset():
This function sets the first ‘n’ characters of the string to a given character.
Escape Characters
The first seven characters listed in the table perform the indicated function on
most output devices when they are displayed. The audible alert character, \a,
sounds a “bell” in most terminal windows.
Including the backspace character ‘\b’ inside a character string causes the
terminal to backspace one character at the point at which the character appears in
the string, provided that it is supported by the terminal window.
The statement
displays the value of a, spaces over to the next tab position, displays the value
of b, spaces over to next tab position, and then displays the value of C. The
horizontal tab character is particularly useful for lining up data in columns.
printf(“\”Hello\” ”);
prints the message “Hello”
c=’\’; assigns a single quotation to variable ‘c’.
Ex : struct book
{
char bookname [20];
char publisher [30];
};
Defines a variable book1 of type struct book and initialises bookname and
publisher to the specified values.
Ex : scanf(“%s”, book1.bookname);
Scanf(“%s”,book1.publisher);
Ex: gets(book1.bookname);
scanf(book1.bookname);
This definition declares an array book2 of type struct book and consists 10
elements. Following example illustrates array of structures combined with strings.
main()
{
struct book
{
char bookname[20];
char publisher[30];
};
struct book book1[10];
int i;
clrscr();
printf(“Enter books detail:\n”);
for (i = 0; i < 10; i++)
{
printf(“\n Enter Book No : “);
gets(book1[i].bookname);
printf(“\n Enter Publisher:”);
gets(book1[i].publisher);
}
printf(“\n Books Details \n”);
for(i = 0; i < 10; i++)
{
printf(“\n Book Name : %s”, book1[i].bookname);
printf(“\n Publisher :%s”, book1[i].publisher);
}
getch();
}
In the above program variable book1 is declared as array of type struct book.
The first for loop will assign values to array elements. The second for loop displays
the array elements. Since each array element is structure they can be accessed as
book1[0].bookname, book1[0].publisher
book1[1].bookname, book1[1].publisher and so on.
Character Operations
The expression
C1 > = ’a’ & & C1< = ’z’ could by replaced by C1>=97 && C1<=122, if ‘C1’ is
lowercase letter.
Ex : The character ‘0’ is not same as the integer 0, the character ’1’ is not same
as the integer1, and so an.
#include “stdio.h”
main()
{
char str[10];
int value, i;
int result=0;
printf(“\n Enter String:”);
scanf(“%s”, str);
for(i=0;str[i]>=’0’ && str[i]<=’9’; i++)
{
value = str[i]-‘0’;
result=result*10+value;
}
printf(“\n Integer value : %d”, result);
}
Character Functions in C
“ ctype.h”, header file support all the below character functions in ‘C’.
Function Description
isalpha() This function checks whether character is
alphabet
isdigit() This function checks whether character is
digit
isalnum() This function checks whether character is
alpha-numeric
isspace() This function checks whether character is
space
islower() This function checks whether character is
lowercase
isupper() This function checks whether character is
Uppercase
isxdigit() This function checks whether character is
hexadecimal
iscntrl() This function checks whether character is
a control character
isprint() This function checks whether character is
a printable character
ispunct() This function checks whether character is
a punctuation
isgraph() This function checks whether character is
a graphical character
tolower() This function checks whether character is
alphabetic & converts to lower case
toupper() This function checks whether character is
alphabetic & converts to upper case