Module 1 C Programming JDecisionMakingStructureArrays
Module 1 C Programming JDecisionMakingStructureArrays
Module-1
C was developed by Dennis Ritchie in early 1970’s at “AT & T’s Bell Labs”.
C was first developed for UNIX operating system. Latter C becomes very popular with DOS.
Before C , some other languages were used like BCPL which were further enhanced to produce
language B. B led to the development of C.
What is an identifier?
Identifiers are names of programming elements such as variables and functions. Identifier in C is
made up of letters, digits, and underscore. An identifier may start with either letter or an
underscore.
• Identifiers are used to name
o Variables, Constants, Functions, structures, enum, etc.
Rules to construct identifiers:→
1. An identifier must start with either letter or underscore.
2. An identifier can be a combination of any letter, digit, or an underscore.
3. An identifier can contain both uppercase or lower case letters.
4. An identifier may be of any length (Depends on architecture or compiler).
What is a keyword?
Every C word is classified as either keyword or an identifier. All keywords have fixed meaning
and these meanings can not be changed. Keywords serve as basic building blocks for program
statements. Examples:
int char float goto break continue
if else sizeof while for register
do const static auto extern double
Data types
What is a variable?
“A variable is a logical location in a computer memory which can take any values of the
specified type”. Or
“A variable is an object that may take on any values of specified type”.
A variable must be declared by specifying the data type and the identifier.
Syntax Example
DataType id1, id2, … idn; int val, num;
int %d or %i 2 or 4 Bytes
float %f 4 Bytes
double %x 8 Bytes
What is modifier?
C allows you to modify the size of the data type by affixing one of the following:
void main( )
{ Main function
printf ( “hello”); section
}
Some Examples.
• Convert the equation in C language format and Identify Operators and Operands.
1. C = 2 X2 + 5XY + Z where X = 2, Y = 3, Z = 1.
• Similarly Convert the following equations into C language form and Identify Operators,
variables and constants.
2. D = 2 X3 + 5 X2 + Y where X = 2, Y = 2.
3. C = 2 A3 – 3 AB2 + 4 A2B + B where A = 1, B = 2.
4. Z = X3 + Y3X + XY where X = 1, Y = 1.
printf function can handle any basic data type and offers several facilities to specify the
format of data display. printf performs formatted output to the standard output device.
printf performs following actions:
Example:
printf (“Total is : %d %d \n”, a, b) ;
Which contain %d a format specifier and \n a escape character. printf function converts
the argument a and b into integer format as specified by %d, and at the last it converts \n
as line feed.
Module-1 7
Example:
• Example:
void main()
{
char ch;
printf(“Enter the character: “);
ch = getch();
printf(“character by getch: %c ”, ch);
ch = getche();
printf(“character by getche: %c”, ch);
ch = getchar();
printf(“character by getchar: %c”, ch);
}
Output:
Module-1 9
ii) gets()
function gets() used to reads a character string from console and stores it into the
given character array.
• Format:
char* gets(char *str)
- Argument: str – is a pointer to an array of character where the string is stored.
- Return value: str on success, NULL on failure.
- This function returns str on success, and NULL on error or when end of file occurs,
while no characters have been read.
• Example
void main()
{
char str[50];
Output:
Enter a string : RNSIT
You entered: RNSIT
• Example:
#include <stdio.h>
void main()
{
char str[50]= “RNSIT”;
puts(str);
}
Output:
RNSIT
Exampl2:
#include <stdio.h>
void main()
{
char ch;
printf(“Enter character”)
ch = getchar();
printf(“data read =”);
putchar(ch);
}
Output:
Enter character : R
Data read : R
Module-1 11
1. a. Simple if statement.
Syntax:
if (test-condition)
{
statements;
}
main ( )
{
int a, b, big ;
printf (“Enter value for a & b : \n”) ;
scanf (“%d %d”, &a, &b) ;
if (a > b )
big = a ;
if (b > a )
big = b ;
1. b. if - else statement.
Syntax:
if (test-condition)
{
Statements;
}
else / /if above condition is not true
{
Statements;
}
Flowchart:
False
Test
True
Body of if for true Body of else for false
Next statement
Module-1 14
main ( )
{
int a, b, big ;
printf (“Enter value for a & b : \n”) ;
scanf (“%d %d”, &a, &b) ;
if (a > b )
big = a ;
else
big = b ;
main ( )
{
int n ;
printf (“Enter any number : \n”) ;
scanf (“%d ”, &n) ;
if ( n % 2 == 0 )
{
printf (“the number %d is even”, n) ;
}
else
{
printf (“the number %d is odd”, n) ;
}
getch ( ) ;
}
main ( )
{
int a, b, ch, result ;
printf (“Enter two values :”);
scanf (“%d %d”, &a, &b) ;
if (ch = = 2 )
result = a - b ;
if (ch = = 3 )
result = a * b ;
if (ch = = 4 )
result = a / b ;
1. c. Switch statement.
“The control statement which allows us to make a decision from the number of choices at
once is called a switch statement.”
If the number of alternatives are too many then using if control statement increases
complexity and program becomes difficult to read and understand. C has a built in multi
way decision statement known as a switch.
The switch statement tests the value of a given variable (or expression) against the list of
case values, and when a match is found, a block of statements associated with that case is
executed.
Syntax:
switch ( expression )
{
case value-1: block ;
break ;
case value-2: block ;
break ;
… …
… …
… …
default: default block ;
break ;
}
• The break statement at the end of each block signals the end of particular case, and
control exits from the switch statement.
• The default is an optional case. Default will be executed if the value of the expression
does not match with any of the case values.
Module-1 17
Example: Accept day number of a week and display the corresponding week day
main ( )
{ int N ;
printf (“Enter The Day number :”);
scanf (“%d ”, &N) ;
switch ( N )
{
case 1 : printf (“Sunday”) ; break ;
case 2 : printf (“Monday”) ; break ;
case 3 : printf (“Tuesday”) ; break ;
case 4 : printf (“Wednesday”) ; break ;
case 5 : printf (“Thursday”) ; break ;
case 6 : printf (“Friday”) ; break ;
case 7 : printf (“Saturday”) ; break ;
default : printf (“Invalid No”) ; break ;
}
}
Module-1 18
Sr.
switch if – else
No
Switch offers a better way of writing In very few situations we are
1. programs than if. It leads to more left with no choice but to use if
structured program.
Even if there are multiple statements Every if or else part has to be
to be executed in each case, there is included in braces if they
2.
no need to enclose them within a contain more than one
pair of braces { }. statement.
Switch will not work with logical Any logical operators can be
3. operators can not be used as case used as if-else conditions.
labels. e.g. case i <= 20 : e.g. if (i <=20)
The constants in the case statements The constants in the test
of switch can be either ‘char’ or condition of if-else statements
4.
‘int’ data type only. ‘float’ or can of any data type.
‘double’ doesn’t work.
No two case values may be the Even though two if conditions
5. same. can be same, logically we
should not use it.
Nested switch are very rarely used. Nested if-else are more used
6.
than nested switch.
Example: Example:
int N = 15 ; int N = 15 ;
switch ( N % 2 ) if ( N%2 = = 0)
7. { printf(“Even”);
case 0: printf(“Even”); break; else
case 1: printf(“Odd”); break; printf(“Odd”);
}
Module-1 19
Syntax:
Result = ( exp1 ) ? exp2 : exp3 ;
if (x > 0 )
flag = 0 ;
else
flag = 1 ;
This statement can be replaced by conditional operator as:
flag = ( x > 0 ) ? 0 : 1 ;
1. e. The go – to statement.
C supports the go to statement to branch unconditional from one point to another in the
program.
The goto requires a label in order to identify the place where the branch is to be made. A label
is any valid variable name, which must be followed by a colon (:). The label is placed
immediately before the statement where the control is to be transferred.
Label can be any where in the program, either before or after the goto.
main ( )
{
int age ;
AGAIN :
printf ( “Enter Age :”) ;
scanf(“%d”, &age);
Loop Constructs.
1. while loop.
The while loop is used to execute a statement (or block of statements) multiple times. It is the
simplest of all looping constructs.
Syntax: Flowchart:
while ( test-condition) False
{ Test Next statement
body of while-loop ;
} True
Body of while loop
The test-condition is evaluated first. If the condition is TRUE then only the body of loop is
executed. After the execution of body, the test-condition is once again evaluated and if it is
true, that body is executed once again. This process is repeated until the test-condition finally
becomes false and the control is transferred out of the loop.
The while loop is more powerful when ‘the number of times the loop is to be executed is not
known in advance’.
main ( )
{
int sum = 0, i ;
i = 1; /* Assignment */
while ( i <= 10 ) /* Condition */
{
sum += i ;
i ++ ; /* Increment */
}
main ( )
{
int a, b, result ;
char ch = ‘y’ ; // initialization.
while ( ch = = ‘y’ )
{
printf ( “Enter Two Numbers \n”) ;
scanf(“%d %d”, &a, &b);
result = a + b ;
printf ( “Total of %d and %d is %d \n”, a, b, result) ;
Buffer is a temporary memory. When a c program begins execution the following data streams
will automatically opened.
1. stdin: standard input device (opened for input).
2. stdout: standard output device(opened for output).
Both the streams are termed as buffers. The output of the function like printf goes to stdout.
Input through keyboard will be buffered in stdin, which will be read by functions like scanf,
getch, gets etc.
In the above example for statement: scanf(“%d %d”, &a, &b); we have to input two integer
values and then we have to press enter key(Return key). Here in tern we are entering a new line
i.e. ‘\n’ character by pressing a enter key in following order.
12 6 ‘\n’
scanf will scan 12 into ‘a’ variable and 6 into ‘b’ variable. Whereas ‘\n’ character still remains
in the input buffer. Next statement scanf (“%c”, &ch); will scan that ‘\n’ character instead of
scanning entered character. Hence to clear the input buffer from such a characters before
scanning fflush function is used in the above example. fflush clears the buffer.
Module-1 23
2. do - while loop.
The Statements within do - while loop will be executed at least once. The do–
while loop is called as bottom tested loop.
Syntax: Flowchart:
do
{
body of do-loop ; Body of do-while
}
while ( test-condition); False
True Test Next statement
main ( )
{
int a, b, result ;
char ch ; // No need of initialization.
do
{
printf ( “Enter Two Numbers ”) ;
scanf(“%d %d”, &a, &b);
result = a + b ;
printf ( “Total of %d and %d is %d \n”, a, b, result) ;
Sr.
while loop. do – while loop.
No
while loop is ‘Top tested’ loop. do - while loop is ‘Bottom tested’
1.
loop.
If the test condition is false at the Even if the condition is false at the
2. first test, then body of while loop first test, body of do-while
never executes. executes at least once.
This loop is also termed as This loop is also termed as
3.
“Entry controlled” loop. “Exit controlled” loop.
Syntax: Syntax:
while (condition) do
{ {
4.
body of while; body of while;
} }
while (condition);
No semicolon after while Semicolon should be given at the
5.
condition. end of do-while condition.
Flowchart: Flowchart:
False
Test Next statement Body of do-while
6.
True False
True Test
Body of while loop Next statement
Example: Example:
a=1; a=1;
While (a <= 10) do
{ {
7.
sum += a; sum += a;
a ++ ; a ++ ;
} }
While (a < 10);
Module-1 25
3. for loop.
When we in advance exactly how many times we want to execute the statements in a loop, in
such case, the for loop can be used.
Syntax:
for ( loop initialization ; test-condition ; increment )
{
body of loop;
}
main ( )
{
int N, i, fact = 1 ;
for ( i = N ; i > 0 ; i - -)
fact = fact * i ;
main ( )
{
int N, i ;
1. break statement:
The break statement terminates the execution of the loop and the control is transferred
to the statement immediately following the loop.
2. continue statement:
A continue statement does not terminate the loop but skips the remaining statements of
that loop and control transfers at the beginning.
3. exit statement:
A exit( ) function terminates the process. Program suddenly stops the execution as soon
as it encounters exit.
Output:
012
Before Exit
In above example The statement continue will skip the statement printf (“After Continue\n”)
and transfers the control back to the condition statement. As if condition satisfies for i = 3 the
statement break terminates the loop by transferring the control to the next statement followed
by loop. Control will never reach the last statement printf (“After Exit\n”) as the exit
statement will terminate the program.
Module-1 28
The above example will output always: TRUE even the initial value of x is 5. The reason is we
are not comparing x with 6, In fact assigns the value 6 to variable x in if condition which
executes successfully. If statement in if executes successfully, compiler return 1 which makes
the condition true. In other case output is FALSE.
Module-1 29
Array
• Types of array:
1. One dimensional (1D)
2. Two dimensional (2D)
3. Multi dimensional (nD)
• Definition:
- It is collection of similar data type elements. All Elements of array are stored in
contiguous memory locations.
• Syntax:
data-type name[size];
Where, data-type: tells kind of values it can store ( like int , char , float etc..), name: to
identify the array and size :indicate maximum number of values the array can hold
• Example:
int num[3];
• Memory representation:
Num 0 1 2 index
Foo ? ? ?
Base f00 f02 f04 address
pointer
Module-1 30
• Array initialization
o Full initialization
Num 0 1 2 index
Foo 10 20 30
f00 f02 f04 address
o Partial initialization
Num 0 1 2 3 4
Foo 10 20 30 0 0
f00 f02 f04 f06 f08
• Reading and displaying Array values from user
void main()
{
int num[3] = {10, 20, 30}; /* Initialized array */
printf (“Displaying array :”); /* displaying Array */
for(i=0;i<3;i++)
printf(“%d”,num[i]);
}
void main()
{
int num[3];
printf (“Enter nos to array :”); /* reading Array */
for(i=0;i<3;i++)
scanf(“%d”,&num[i]);
printf (“Displaying array :”); /* displaying Array */
for(i=0;i<3;i++)
printf(“%d”,num[i]);
}
Module-1 31
Where,
data type: what kind of values it can store Ex: int , char , float etc..
Name: to identify the array
row: the maximum number of rows the array can hold
col: the maximum number of columns the array can hold
• Example:
int Num[3][3];
Num 0 1 2
. Num[0] . 0 10 20 30
Num[1] . 1 4 5 6
Num[2] . 2 50 60 70
void main()
{
int num[3][];
printf (“Enter 3x3 matrix :”); /* reading Array */
for(i=0;i<3;i++)
for(j=0;j<3;j++)
scanf(“%d”,&num[i][j]);
printf (“Displaying array Matrix:”); /* displaying Array */
for(i=0;i<3;i++)
for(j=0;j<3;j++)
printf(“%d”, num[i][j]);
}
Module-1 32
case 2: binarySearch();
break;
case 3: exit(0);
break;
default: printf("\nInvalid choice:\n");
} /* end of switch */
}
}
void linearSearch ()
{ int a[10], size, key, i;
printf("Enter size :");
scanf("%d", &size);
printf("Enter Array Elements :");
for(i=0; i< size; i++)
scanf("%d", &a[i]);
printf ("Enter the search element : ");
scanf ("%d", &key);
for( i=0; i<size; i++)
{
if ( key == a[i] )
{
printf("Element found at position 5d", i+1); return;
}
}
printf ("\n..Element not found..\n"); getch();
}
Module-1 34
void binarySearch ( )
{
int a[10], size, mid, key, i, low, high;
printf("Enter size :");
scanf("%d", &size);
printf("Enter Array Elements :");
for(i=0; i< size; i++)
scanf("%d", &a[i]);
printf ("Enter the search element : ");
scanf ("%d", &key);
low = 0; high = size;
while (low < high)
{ mid = (low + high) / 2;
if ( key == a[mid] )
{
printf("Element found at position : %d", mid+1); return;
}
if( key < a[mid] )
high = mid-1;
else
low= mid+1;
}
printf("\n Element Not found .. \n");
}