1. 1
UNIT I BASICS OF C PROGRAMMING
Problem formulation – Problem Solving - Introduction to ‘ C’
programming –fundamentals – structure of a ‘C’ program –
compilation and linking processes – Constants, Variables –
Data Types – Expressions using operators in ‘C’ – Managing
Input and Output operations – Decision Making and
Branching – Looping statements – solving simple scientific
and statistical problems.
Structure of a “C” program
/*
Documentation section
C programming basics & structure of C programs
Author: I-ECE
Date : 01/01/2016
*/
#include <stdio.h> /* Link section */
int total = 0; /* Global declaration, definition section */
int sum (int, int); /* Function declaration section */
int main () /* Main function */
{
printf ("This is a C basic program n");
total = sum (1, 1);
printf ("Sum of two numbers : %d n", total);
}
int sum (int a, int b) /* User defined function */
{
return a + b; /* definition section */
}
OUTPUT:
This is a C basic program
Sum of two numbers: 2
1. Documentation section
2. Link Section
3. Definition Section
4. Global declaration section
5. Function prototype declaration section
6. Main function
7. User defined function definition section
2. 2
Documentation section: The documentation section consists
of a set of comment lines giving the name of the program, the
author and other basic details.
Link section: The link section provides instructions to the
compiler to link functions from the system library such as using
the #include directive.
Definition section: The definition section defines all symbolic
constants such as using the #define directive.
Global declaration section: There are some variables that are
used in more than one function. Such variables are called
global variables and are declared in the global declaration
section that is outside of all the functions. This section also
declares all the user-defined functions.
main () function section: Every C program must have one
main function section. This section contains two parts;
declaration part and executable part
Declaration part: The declaration part declares all
the variables used in the executable part.
Executable part: The program execution begins at the
opening brace and ends at the closing brace. All
statements in the declaration and executable part end
with a semicolon.
Subprogram section: If the program is a multi-function
program then the subprogram section contains all the user-
defined functions that are called in the main () function.
Calculator Program:
/*
Documentation section
C programming basics & structure of C programs
Author: I-ECE
Date : 01/01/2016
*/
#include<stdio.h> /* Link section */
#include<conio.h>
main() /* Main function */
{ /* Execution Begins*/
int a,b,c,d; /* Declaration Part*/
printf("Enter the values of a and b:");
scanf("%d %d",&a,&b);
printf(" Enter your choice between 1 to 5 n");
printf(" 1 - Addition n");
printf(" 2 - Substraction n");
printf(" 3 - Multiplication n");
printf(" 4 - Divide n");
printf(" 5 - Remainder n");
scanf("%d", &d);
switch(d) /* Switch Case */
{
case 1:
c=a+b;
printf(" Addition=%d", c);
break;
3. 3
case 2:
c=a-b;
printf(" Subtraction=%d" , c);
break;
case 3:
c=a*b;
printf(" Multiplication=%d", c);
break;
case 4:
c=a/b;
printf(" Divide=%d", c);
break;
case 5:
c=a%b;
printf(" Remainder=%d",c );
break;
default:
printf(" Invalid Result");
break;
}
getch();
} /* Execution Ends*/
OUTPUT:
Enter the values of a and b:4 2
Enter your choice between 1 to 5
1 - Addition
2 - Subtraction
3 - Multiplication
4 - Divide
5 – Remainder
Enter your choice between 1 to 5
1
Addition=6
Enter your choice between 1 to 5
3
Multiplication=8
Enter your choice between 1 to 5
4
Divide=2
Enter your choice between 1 to 5
5
Remainder=0
Enter your choice between 1 to 5
9
Invalid Result
4. 4
Compilation and Linking Process
C language needs a compiler to convert its source code into an
executable code. Compiling a C program is a multi-stage
process. The process can be split into four separate stages:
1. Pre-processing
2. Compilation
3. Assembly
4. Linking
Preprocessing
This is the first phase through which source code is passed.
This phase includes:
Removal of Comments
Expansion of Macros
Expansion of the included files.
Compilation
The C compiler translates source to assembly code. In this
stage, the preprocessed code is translated to assembly
instructions
Assembly
The assembler creates object code. During the assembly stage,
an assembler is used to translate the assembly instructions to
machine code, or object code.
Linking
This is the final phase in which all the linking of function calls
with their definitions are done. Linker knows where all these
functions are implemented.
5. 5
/*
Documentation section
C programming basics & structure of C programs
Author: I-ECE
Date : 01/01/2016
*/
#include <stdio.h> /* Link section */
int total = 0; /* Global declaration, definition section */
int sum (int, int); /* Function declaration section */
int main () /* Main function */
{
printf ("This is a C basic program n");
total = sum (1, 1);
printf ("Sum of two numbers : %d n", total);
}
int sum (int a, int b) /* User defined function */
{
return a + b; /* definition section */
}
OUTPUT:
This is a C basic program
Sum of two numbers: 2
6. 6
Constants
C Constants are also like normal variables. But, only difference
is, their values cannot be modified by the program once they are
defined. These fixed values are also called literals.
Constant means “Whose value cannot be changed“
SYNTAX
const data_type variable_name;
Constant type data type (Example)
Integer constants
int (Example: 53)
unsigned int (Example: 5000u)
Real or Floating point
constants
float (Example: 10.456789)
doule (Example: 600.123456789)
character constants char (Example: ‘A’, ‘B’, ‘C’)
string constants char (Example: “ABCD”, “Hai”)
INTEGER CONSTANTS IN C:
An integer constant must have at least one digit.
It must not have a decimal point.
It can either be positive or negative.
No commas or blanks are allowed within an integer
constant.
If no sign precedes an integer constant, it is assumed to
be positive.
REAL CONSTANTS IN C:
A real constant must have at least one digit
It must have a decimal point
It could be either positive or negative
If no sign precedes an integer constant, it is assumed to
be positive.
No commas or blanks are allowed within a real constant.
CHARACTER AND STRING CONSTANTS IN C:
A character constant is a single alphabet enclosed within
single quotes.
The maximum length of a character constant is 1
character.
String constants are enclosed within double quotes.
BACKSLASH CHARACTER CONSTANTS IN C:
( Escape Sequences )
Character should be preceded by backslash symbol to
make use of special function of them.
Backslash
character
Meaning
b Backspace
n New line
t Horizontal tab
” Double quote
’ Single quote
Backslash
7. 7
HOW TO USE CONSTANTS IN A C PROGRAM?
We can define constants in a C program in the following ways.
1. By “const” keyword
2. By “#define” preprocessor directive
EXAMPLE PROGRAM USING CONST KEYWORD IN C:
#include<stdio.h>
#include<conio.h>
main()
{
const int height = 100; /*int constant*/
const float number = 3.14; /*Real constant*/
const char letter = 'A'; /*char constant*/
const char letter_sequence[10] = "ABC"; /*string constant*/
const char backslash_char = '?'; /*special char cnst*/
printf("value of height :%d n", height );
printf("value of number : %f n", number );
printf("value of letter : %c n", letter );
printf("value of letter_sequence : %s n", letter_sequence);
printf("value of backslash_char : %c n", backslash_char);
getch();
}
OUTPUT:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
EXAMPLE PROGRAM USING #DEFINE PREPROCESSOR
DIRECTIVE IN C:
#include<stdio.h>
#include<conio.h>
#define height 100
#define number 3.14
#define letter 'A'
#define letter_sequence "ABC"
#define backslash_char '?'
main()
{
printf("value of height : %d n", height );
printf("value of number : %f n", number );
printf("value of letter : %c n", letter );
printf("value of letter_sequence : %s n",letter_sequence);
printf("value of backslash_char : %c n",backslash_char);
getch();
}
OUTPUT:
value of height : 100
value of number : 3.140000
value of letter : A
value of letter_sequence : ABC
value of backslash_char : ?
8. 8
Variables
A variable is a container (storage area) to hold data. A Variable
is a name given to the memory location where the actual data is
stored. The value of a variable can be changed, hence the name
'variable’.
RULES FOR NAMING C VARIABLE:
1. Variable name must begin with letter or underscore.
2. Variables are case sensitive
3. They can be constructed with digits, letters.
4. No special symbols are allowed other than underscore.
DECLARING & INITIALIZING C VARIABLE:
Variables should be declared in the C program before to
use.
Variable initialization means assigning a value to the
variable.
Type Syntax
Variable
declaration
data_type variable_name;
Example:
int x, y, z;
char flat, ch;
Variable
initialization
data_type variable_name = value;
Example:
int x = 50, y = 30;
char flag = ‘x’, ch=’l’;
TYPES OF VARIABLES IN C PROGRAM (SCOPE)
1. Local variable
2. Global variable
EXAMPLE PROGRAM FOR LOCAL VARIABLE IN C:
The scope of local variables will be within the function
only. These variables are declared within the function
and can’t be accessed outside the function.
In the below example, m and n variables are having
scope within the main function only. These are not
visible to test function.
Likewise, a and b variables are having scope within the
test function only. These are not visible to main function.
#include<stdio.h>
#include<conio.h>
void increment();
main()
{
int a=5;
++a;
printf("%d n",a);
increment();
}
void increment()
{
++a;
printf("%d n",a);
getch();
}
9. 9
OUTPUT
In the above program, an error will occur as in the function
increment() we are trying to access variable “a” which is not
known to it. It should be noted that the variable “a” is local to the
function main().
EXAMPLE PROGRAM FOR GLOBAL VARIABLE IN C:
The scope of global variables will be throughout the
program. These variables can be accessed from anywhere
in the program.
This variable is defined outside the main function. So
that, this variable is visible to main function and all
other sub functions.
#include<stdio.h>
#include<conio.h>
int a=5;
void increment();
main()
{
++a;
printf("%d n",a);
increment();
getch();
}
void increment()
{
++a;
printf("%d n",a);
}
OUTPUT
6
7
10. 10
Data Types
The type of data that variables may hold in a programming
language is known as data type.
C data types are defined as the data storage format that a
variable can store a data.
BASIC DATA TYPES IN C:
CHARACTER DATA TYPE:
Character data type allows a variable to store only one
character.
“char” keyword is used to refer character data type.
INTEGER DATA TYPE:
Integer data type allows a variable to store numeric
values. “int” keyword is used to refer integer data type.
11. 11
FLOATING POINT DATA TYPE:
Float data type allows a variable to store decimal values.
Floating types are used to store real numbers.
VOID TYPE:
Void is an empty data type that has no value.
This can be used in functions and pointers.
EXAMPLE:
#include<stdio.h>
#include<conio.h>
main()
{
int a; //Integer Data Type
char b; //Char Data Type
float c; //Float Data Type
double d; //Double Float Data Type
printf("Storage size for int data type:%d n",sizeof(a));
printf("Storage size for char data type:%d n",sizeof(b));
printf("Storage size for float data type:%d n",sizeof(c));
printf("Storage size for double data type:%dn",sizeof(d));
getch();
}
OUTPUT:
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8
12. 12
Expressions using Operators
An operator is a symbol that tells the compiler to perform
specific mathematical or logical functions.
Operators are symbols which take one or more operands and
perform arithmetic or logical computations
Operands are entity on which an operation is to be performed.
Combination of operands and operators form an Expression.
Consider the expression A + B * 5
Where, +, * are operators, A, B are variables, 5 is constant and
A + B * 5 is an expression.
TYPES OF C OPERATORS:
1. Arithmetic operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bit wise operators
6. Conditional operators (ternary operators)
7. Increment/decrement operators
8. Special operators
Types of Operators Description
Arithmetic_operators
These are used to perform
mathematical calculations like
addition, subtraction,
multiplication, division and
modulus
Assignment operators
These are used to assign
the values for the variables in
C programs.
Relational operators
These operators are used
to compare the value of two
variables.
Logical operators
These operators are used to
perform logical operations on
the given two variables.
Bit wise operators
These operators are used to
perform bit operations on
given two variables.
Conditional (ternary)
operators
Conditional operators return
one value if condition is true
and returns another value is
condition is false.
Increment/decrement
operators
These operators are used to
either increase or decrease the
value of the variable by one.
Special operators
&, *, sizeof( ) and ternary
operators.
13. 13
ARITHMETIC OPERATORS IN C:
C Arithmetic operators are used to perform mathematical
calculations like addition, subtraction, multiplication, division
and modulus in C programs.
Arithmetic
Operators/Operation Example
+ (Addition) A+B
– (Subtraction) A-B
* (multiplication) A*B
/ (Division) A/B
% (Modulus) A%B
#include<stdio.h>
#include<conio.h>
main()
{
int a=40,b=20, add,sub,mul,div,mod;
add = a+b;
sub = a-b;
mul = a*b;
div = a/b;
mod = a%b;
printf("Addition of a, b is : %dn", add);
printf("Subtraction of a, b is : %dn", sub);
printf("Multiplication of a, b is : %dn", mul);
printf("Division of a, b is : %dn", div);
printf("Modulus of a, b is : %dn", mod);
getch();
}
OUTPUT:
Addition of a, b is : 60
Subtraction of a, b is : 20
Multiplication of a, b is : 800
Division of a, b is : 2
Modulus of a, b is : 0
ASSIGNMENT OPERATORS IN C:
In C programs, values for the variables are assigned using
assignment operators. There are 2 categories of assignment
operators in C language. They are:
Simple assignment operator (Example: = )
Compound assignment operators / Shorthand Operators
(Example: +=, -=, *=, /=, %=, &=, ^= )
# include<stdio.h>
#include<conio.h>
main()
{
int total=0,i;
for(i=0;i<10;i++)
{
total+=i; // This is same as total = total+i
}
printf("total = %d", total);
getch();
}
OUTPUT:
Total = 45
14. 14
Operators Example/Description
=
sum = 10;
10 is assigned to variable sum
+=
sum += 10;
This is same as sum = sum + 10
-=
sum -= 10;
This is same as sum = sum – 10
*=
sum *= 10;
This is same as sum = sum * 10
/=
sum /= 10;
This is same as sum = sum / 10
%=
sum %= 10;
This is same as sum = sum % 10
&=
sum&=10;
This is same as sum = sum & 10
^=
sum ^= 10;
This is same as sum = sum ^ 10
RELATIONAL OPERATORS IN C:
Relational operators are used to find the relation between two
variables. i.e. to compare the values of two variables in a C
program.
Operator Meaning of Operator Example
== Equal to 5 == 3 returns 0
> Greater than 5 > 3 returns 1
< Less than 5 < 3 returns 0
!= Not equal to 5 != 3 returns 1
>= Greater than or equal to 5 >= 3 returns 1
<= Less than or equal to 5 <= 3 return 0
#include<stdio.h>
#include<conio.h>
main()
{
int m=40,n=20;
if (m == n) //Equal to
{
printf("m and n are equal");
}
else
{
printf("m and n are not equal");
}
getch();
}
OUTPUT:
m and n are not equal
15. 15
LOGICAL OPERATORS IN C:
These operators are used to perform logical operations on the
given expressions.
#include<stdio.h>
#include<conio.h>
main()
{
int a = 5, b = 5, c = 10, result;
result = (a = b) && (c > b);
printf("(a = b) && (c > b) equals to %d n", result);
result = (a = b) && (c < b);
printf("(a = b) && (c < b) equals to %d n", result);
result = (a = b) || (c < b);
printf("(a = b) || (c < b) equals to %d n", result);
result = (a != b) || (c < b);
printf("(a != b) || (c < b) equals to %d n", result);
result = !(a != b);
printf("!(a != b) equals to %d n", result);
result = !(a == b);
printf("!(a == b) equals to %d n", result);
getch();
}
OUTPUT:
(a = b) && (c > b) equals to 1
(a = b) && (c < b) equals to 0
(a = b) || (c < b) equals to 1
(a != b) || (c < b) equals to 0
!(a != b) equals to 1
!(a == b) equals to 0
Operators Example/Description
&& (logical AND)
(x>5)&&(y<5)
It returns true when both conditions
are true
|| (logical OR)
(x>=10)||(y>=10)
It returns true when at-least one of the
condition is true
! (logical NOT)
!((x>5)&&(y<5))
If ((x>5) && (y<5)) is true, logical NOT
operator makes it false
BIT WISE OPERATORS IN C:
These operators are used to perform bit operations. Decimal
values are converted into binary values which are the sequence
of bits and bit wise operators work on these bits.
16. 16
TRUTH TABLE FOR BIT WISE OPERATION & BIT WISE
OPERATORS:
& – Bitwise AND
| – Bitwise OR
^ – XOR
<< – Left Shift
>> – Right Shift
#include<stdio.h>
#include<conio.h>
main()
{
int m = 2,n = 3,AND,OR,XOR,LSHIFT,RSHIFT;
AND = (m&n);
OR = (m|n);
XOR = (m^n);
LSHIFT = (m<<1);
RSHIFT = (m>>1);
printf("AND value = %dn",AND);
printf("OR value = %dn",OR);
printf("XOR value = %dn",XOR);
printf("left_shift value = %dn",LSHIFT);
printf("right_shift value = %dn",RSHIFT);
getch();
}
OUTPUT:
AND value = 2
OR value = 3
XOR value = 1
left_shift value = 4
right_shift value = 1
Bit wise left shift and right shift:
In left shift operation x<<1 means that the bits will be left
shifted by one place. In right shift operation x>>1 means that
the bits will be right shifted by one place.
Original Number m 0000 0000 0000 0010
Left Shift by 1 0000 0000 0000 0100
Original Number m 0000 0000 0000 0010
Right Shift by 1 0000 0000 0000 0001
CONDITIONAL OR TERNARY OPERATORS IN C:
Conditional operators return one value if condition is true and
returns another value is condition is false. This operator is also
called as ternary operator.
Syntax: Condition? true_value: false_value;
17. 17
#include<stdio.h>
#include<conio.h>
main()
{
int num;
printf("Enter the Number : ");
scanf("%d",&num);
(num%2==0)?printf("Even"):printf("Odd");
getch();
}
OUTPUT:
Enter the Number: 5
Odd
C – INCREMENT/DECREMENT OPERATORS:
Increment operators are used to increase the value of the
variable by one and decrement operators are used to decrease
the value of the variable by one in C programs.
Increment operator : ++ i ; i ++ ;
Decrement operator : – – i ; i – – ;
Operator Description
Pre increment
operator (++i)
value of i is incremented
before assigning it to the variable i
Post increment
operator (i++)
value of i is incremented
after assigning it to the variable i
Pre decrement
operator (–i)
value of i is decremented
before assigning it to the variable i
Post decrement
operator (i–)
value of i is decremented
after assigning it to variable i
#include<stdio.h>
#include<conio.h>
main()
{
int a=5;
printf("Initial Value: %dn",a);
// 5 is displayed then, a is increased to 6.
printf("Post Increment: %dn",a++);
int b=5;
printf("nInitial Value: %dn",b);
// Initially, b = 5. It is increased to 6 then, it is displayed.
printf("Pre Increment: %d",++b);
getch();
}
OUTPUT:
Initial Value: 5
Post Increment: 5
Initial Value: 5
Pre Increment: 6
18. 18
#include<stdio.h>
#include<conio.h>
main()
{
int a=5;
printf("Initial Value: %dn",a);
// 5 is displayed then, a is decreased to 4.
printf("Post Decrement: %dn",a--);
int b=5;
printf("nInitial Value: %dn",b);
// Initially, b = 5. It is decreased to 4 then, it is displayed.
printf("Pre Decrement: %d",--b);
getch();
}
OUTPUT:
Initial Value: 5
Post Decrement: 5
Initial Value: 5
Pre Decrement: 4
SPECIAL OPERATORS IN C:
Operators Description
&
This is used to get the address of the
variable.
Example : &a will give address of a.
*
This is used as pointer to a variable.
Example : *a
where * is pointer to the variable a.
sizeof()
This gives the size of the variable.
Example: sizeof (char) will give us 1.
#include<stdio.h>
#include<conio.h>
main()
{
int i = 5;
int *ptr;
ptr = &i;
printf("nValue of i : %d",i);
printf("nAddress of i : %u",&i);
printf("nValue of ptr is : %u",*ptr);
getch();
}
OUTPUT:
Value of i : 5
Address of i : 2293572
Value of ptr is : 5
19. 19
#include<stdio.h>
#include<conio.h>
main()
{
int a;
char b;
float c;
double d;
printf("Storage size for int data type:%d n",sizeof(a));
printf("Storage size for char data type:%d n",sizeof(b));
printf("Storage size for float data type:%d n",sizeof(c));
printf("Storage size for double data type:%dn",sizeof(d));
getch();
}
OUTPUT:
Storage size for int data type:4
Storage size for char data type:1
Storage size for float data type:4
Storage size for double data type:8
20. 20
Managing Input and Output Operations
Input Output operations are useful for program that interact
with user, take input from the user and print messages.
Standard input is a data stream for taking input from devices
such as the keyboard. Standard output is a data stream for
sending output to a device such as a monitor console.
The getchar() and putchar() Functions
Reading a single character can be done by using the
function getchar. It reads a single character from a standard
input device keyboard till the user press the enter key.
variable_name = getchar();
The putchar function can be used for writing single characters
at a time to the output terminal.
putchar (variable name);
EXAMPLE:
#include<stdio.h>
#include<conio.h>
main( )
{
char c;
printf( "Enter a value :");
c = getchar( );
printf( "nYou entered: ");
putchar( c );
getch();
}
OUTPUT:
Enter a value: k
You entered: k
21. 21
The getch() and putch() Functions
The getch function reads a single character from the standard
input unit. When this statement is executed, the entered
character is not displayed on the screen. This function
immediately returns that character to the program without
waiting for the enter key.
variable_name = getch();
The putch function can be used for writing characters one at a
time to the output terminal.
putch (variable name);
EXAMPLE:
#include<stdio.h>
#include<conio.h>
main( )
{
char c;
printf( "Enter a value :");
c = getch( );
printf( "nYou entered: ");
putch( c );
getch();
}
OUTPUT:
Enter a value:
You entered: r
The getche() Function
The getche function reads a single character from the standard
input unit. When this statement is executed, the entered
character is displayed on the screen. This function immediately
returns that character to the program without waiting for the
enter key.
variable_name = getche();
EXAMPLE:
#include<stdio.h>
#include<conio.h>
main( )
{
char c;
printf( "Enter a value :");
c = getche( );
printf( "nYou entered:%c",c);
getch();
}
OUTPUT:
Enter a value: k
You entered: k
22. 22
The gets() and puts() Functions
The function gets accepts the name of the string as input from
the keyboard till newline character is encountered.
gets(str);
The puts function displays the contents on the standard
screen.
puts(str);
EXAMPLE:
#include<stdio.h>
#include<conio.h>
main( )
{
char s[80];
printf("Type a string less than 80 characters:");
gets(s);
printf("The string types is:");
puts(s);
getch();
}
OUTPUT:
Type a string less than 80 characters: computer
The string types is: computer
The scanf() and printf() Functions
C provides standard functions scanf() and printf(), for
performing formatted input and output .These functions accept
a format specification string and a list of variables.
The format specification string is a character string that
specifies the data type of each variable to be input or output
and the size or width of the input and output.
The scanf() function reads the input from the standard input
stream and scans that input according to the format provided.
The printf() function writes the output to the standard output
stream and produces the output according to the format
provided.
FORMAT SPECIFIER:
Conversion
Character
Meaning
%d Integer / Decimal
%c Character
%s String
%f floating point values – Float / Double
Symbols Meaning
n For new line
t For tab space
23. 23
EXAMPLE:
#include<stdio.h>
#include<conio.h>
main()
{
char ch;
char str[100];
printf("Enter any character: ");
scanf("%c", &ch);
printf("Entered character: %c ", ch);
printf("nEnter any string: ");
scanf("%s", &str);
printf("Entered string: %s n", str);
getch();
}
OUTPUT:
Enter any character: c
Entered character: c
Enter any string: computer
Entered string: computer
#include<stdio.h>
#include<conio.h>
main( )
{
char alphabe='A';
int number1= 55;
float number2=22.34;
printf("char= %cn",alphabe);
printf("int= %dn",number1);
printf("float= %fn",number2);
getch();
}
OUTPUT:
char= A
int= 55
float= 22.340000
24. 24
Decision Making and Branching
Decision Making /Branching statements are used to execute
a statement or a group of statement based on certain
conditions.
IF
IF-ELSE
IF-ELSE-IF
NESTED-IF-ELSE
SWITCH
Jump on Branch (GOTO)
IF
If the condition is true, the statements inside the parenthesis { },
will be executed, else the control will be transferred to the next
statement after if.
SYNTAX:
if(condition)
{
Valid C Statements;
}
#include<stdio.h>
#include<conio.h>
main()
{
int a,b;
a=10;
b=5;
if(a>b)
{
printf("a is greater");
}
getch();
}
OUTPUT:
a is greater
25. 25
IF-ELSE
If the condition is true, the statements between if and else is
executed. If it is false, the statement after else is executed.
SYNTAX:
if(condition)
{
Valid C Statements;
}
else
{
Valid C Statements;
}
#include<stdio.h>
#include<conio.h>
main()
{
int num;
printf("Enter a integer numbers:");
scanf("%d",&num);
if(num >= 0)
printf("Number is positiven");
else
printf("Number is Negativen");
getch();
}
OUTPUT:
Enter a integer numbers:5
Number is positive
26. 26
IF-ELSE-IF
If the condition is true, the statements between if and else-if is
executed. If it is false, the condition in else-if is checked and if it
is true, it will be executed. If none of the condition is true the
statement under else is executed.
SYNTAX:
if(condition)
{
Valid C Statements;
}
else if(condition 1)
{
Valid C Statements;
}
-
-
-
else
{
Valid C Statements;
}
27. 27
#include<stdio.h>
#include<conio.h>
main()
{
int num;
printf("Enter a integer numbers:");
scanf("%d",&num);
if(num > 0)
printf("Number is positiven");
else if(num < 0)
printf("Number is Negativen");
else
printf("Number is Zeron");
getch();
}
OUTPUT:
Enter a integer numbers:3
Number is positive
NESTED IF-ELSE
If if-else statement is present inside if statement or/and else
statement, it is called nested if-else statement.
SYNTAX:
if(condition is true)
{
if(condition is true)
{
Valid C Statements;
}
else
{
Valid C Statements;
}
}
else
{
if(condition is true)
{
Valid C Statements;
}
else
{
Valid C Statements;
}
}
28. 28
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c;
printf("n Enter any 3 numbers :");
scanf("%d%d%d",&a,&b,&c);
if(a>b){
if(a>c)
printf("n Biggest =%d",a);
else
printf("n Biggest =%d",c);
}
else{
if(b>c)
printf("n Biggest =%d",b);
else
printf("n Biggest =%d",c);
}
getch();
}
OUTPUT:
Enter any 3 numbers: 9 6 8
Biggest =9
29. 29
SWITCH
Switch statements can also be called matching case statements.
If the value in variable (switch(variable)) matches with any of the
case inside, the statements under the case that matches will be
executed. If none of the case is matched the statement under
default will be executed. This Multi-way decision statement is
known as switch statement.
SYNTAX:
switch(expression)
{
case value1 :
body1
break;
case value2 :
body2
break;
case value3 :
body3
break;
default :
default-body
break;
}
next-statement;
#include<stdio.h>
#include<conio.h>
main()
{
int a,b,c,d;
printf("Enter the values of a and b:");
scanf("%d %d",&a,&b);
printf(" Enter your choice between 1 to 5 n");
printf(" 1 - Addition n");
printf(" 2 - Substraction n");
30. 30
printf(" 3 - Multiplication n");
printf(" 4 - Divide n");
printf(" 5 - Remainder n");
scanf("%d", &d);
switch(d)
{
case 1:
c=a+b;
printf(" Addition=%d", c);
break;
case 2:
c=a-b;
printf(" Subtraction=%d" , c);
break;
case 3:
c=a*b;
printf(" Multiplication=%d", c);
break;
case 4:
c=a/b;
printf(" Divide=%d", c);
break;
case 5:
c=a%b;
printf(" Remainder=%d",c );
break;
default:
printf(" Invalid Result");
break;
}
getch();
}
OUTPUT:
Enter the values of a and b:4 2
Enter your choice between 1 to 5
1 - Addition
2 - Subtraction
3 - Multiplication
4 - Divide
5 – Remainder
Enter your choice between 1 to 5
1
Addition=6
Enter your choice between 1 to 5
3
Multiplication=8
Enter your choice between 1 to 5
4
Divide=2
Enter your choice between 1 to 5
5
Remainder=0
Enter your choice between 1 to 5
9
Invalid Result
31. 31
Jump on Branch:
goto – branch unconditionally from one point to another
GOTO
The goto statement is used to alter the normal sequence of
program execution by transferring control to some other part of
the program unconditionally.
go to label;
…….
…….
LABEL:
#include<stdio.h>
#include<conio.h>
main()
{
int age;
printf("Enter you age:n");
scanf("%d", &age);
if(age<18)
goto ineligible;
else
printf("You are eligible to vote!n");
ineligible:
printf("You are not eligible to vote!n");
getch();
}
OUTPUT:
Enter you age:
21
You are eligible to vote!
32. 32
Looping Statements
Looping / Iteration statements are used to perform looping
operations until the given condition is true. Control comes out
of the loop statements once condition becomes false.
FOR
WHILE
DO..WHILE
Jump Out of Loop (BREAK & CONTINUE)
FOR (ENTRY CONTROLLED LOOP)
In for loop control statement, loop is executed until condition
becomes false. For loop contains 3 parts Initialization,
Condition and Increment or Decrements.
#include<stdio.h>
#include<conio.h>
main()
{
int i;
for(i=0;i<10;i++)
{
printf("%d ",i);
}
getch();
}
OUTPUT:
0 1 2 3 4 5 6 7 8 9
33. 33
WHILE (ENTRY CONTROLLED LOOP)
In while loop, first check the condition. If condition is true,
then control goes inside the loop body otherwise goes outside
the body.
Loop is executed only when condition is true.
#include<stdio.h>
#include<conio.h>
main()
{
int i=0;
while(i<10)
{
printf("%d ",i);
i++;
}
getch();
}
OUTPUT:
0 1 2 3 4 5 6 7 8 9
34. 34
DO..WHILE (EXIT CONTROLLED LOOP)
In do..while loop statement, loop is executed irrespective of the
condition for first time. Then 2nd time onwards, loop is executed
until condition becomes false.
Loop is executed for first time irrespective of the condition. After
executing while loop for first time, then condition is checked.
#include<stdio.h>
#include<conio.h>
main()
{
int i=0;
do
{
printf("%d ",i);
i++;
}while(i<10);
getch();
}
OUTPUT:
0 1 2 3 4 5 6 7 8 9
35. 35
Jump Out Of Loops
break -- exit form loop or switch.
continue -- skip 1 iteration of loop.
BREAK:
Break statement is used to terminate the while loops, switch
case loops and for loops from the subsequent execution.
Syntax:
break;
#include<stdio.h>
#include<conio.h>
main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("nComing out of for loop when i = 5");
break;
}
printf("%d ",i);
}
getch();
}
OUTPUT:
0 1 2 3 4
Coming out of for loop when i = 5
CONTINUE:
Continue statement is used to continue the next iteration of for
loop, while loop and do-while loops. So, the remaining
statements are skipped within the loop for that particular
iteration.
Syntax:
continue;
#include<stdio.h>
#include<conio.h>
main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("nSkipping %d from display n",i);
continue;
}
printf("%d ",i);
}
getch();
}
OUTPUT:
0 1 2 3 4
Skipping 5 from display
6 7 8 9
36. 36
UNIVERSITY QUESTIONS: PART - A
What is the main feature and applications of C language?
Feature of C language:
Application of C language:
What is a data type? What are the three classes of data
types supported by C?
The type of data that variables may hold in a programming
language is known as data type.
C data types are defined as the data storage format that a
variable can store a data.
Write ruler for defining Real Constants.
A real constant must have at least one digit
It must have a decimal point
It could be either positive or negative
If no sign precedes an integer constant, it is assumed to
be positive.
No commas or blanks are allowed within a real constant.
What are the difference between constant and variable?
CONSTANT:
C Constants are also like normal variables. But, only difference
is, their values cannot be modified by the program once they are
defined. These fixed values are also called literals.
Constant means “Whose value cannot be changed“
SYNTAX
const data_type variable_name;
37. 37
VARIABLE:
A variable is a container (storage area) to hold data. A Variable
is a name given to the memory location where the actual data is
stored. The value of a variable can be changed, hence the name
'variable’.
SYNTAX
data_type variable_name;
What is the importance of keywords in C?
Keywords are predefined words used in programming, whose
meaning is already defined by Compiler. C Keywords are also
called as reserved words.
They must be written in lower case. There are 32 keywords
available in C.
EXAMPLE:
List the various input and output statements in C.
What is meant by Compilation and linking process?
Compilation
The C compiler translates source to assembly code. In this
stage, the preprocessed code is translated to assembly
instructions
Linking
This is the final phase in which all the linking of function calls
with their definitions are done. Linker knows where all these
functions are implemented.
38. 38
Define implicit and explicit type conversion
The process of converting one predefined data type into another
is called type conversion.
Implicit Type Conversion
When the type conversion is performed automatically by the
compiler without programmer’s intervention, such type of
conversion is known as implicit type conversion or type
promotion.
The compiler converts all operands into the data type of the
largest operand.
Explicit Type Conversion
The type conversion performed by the programmer by posing
the data type of the expression of specific type is known as
explicit type conversion. The explicit type conversion is also
known as type casting.
Type casting in c is done in the following form:
(data_type)expression;
What do you mean by “C” tokens?
C tokens are the basic buildings blocks in C language which are
constructed together to write a C program.
Each and every smallest individual units in a C program are
known as C tokens.
C tokens are of six types. They are,
Keywords (eg: int, while),
Identifiers (eg: main, total),
Constants (eg: 10, 20),
Strings (eg: “total”, “hello”),
Special symbols (eg: (), {}),
Operators (eg: +, /,-,*)
List the rules for defining variables in C.
Variable name must begin with letter or underscore.
Variables are case sensitive
They can be constructed with digits, letters.
No special symbols are allowed other than underscore.
39. 39
What is an identifier? Give example
In C language identifiers are the names given to variables,
constants, functions and user-define data.
Example:
int x, y, total; // x, y, total – identifier
List out the rules to be followed in forming an identifier
Name of identifier includes alphabets, digit and
underscore.
The first character in an identifier must be an alphabet
or an underscore
Identifiers are case sensitive
Keywords cannot be used as an identifier
What is Scope of a variable? List the types.
A scope in any programming is a region of the program where a
defined variable can have its existence and beyond that variable
it cannot be accessed.
Inside a function or a block which is
called local variables.
Outside of all functions which is called global variables.
What is the purpose of main()?
In C, program execution starts from the main() function. Every
C program must contain a main() function. The main function
may contain any number of statements. These statements are
executed sequentially in the order which they are written.
int main(); //main with no arguments
int main(int argc, char *argv[]); //main with arguments
Write any four escape sequence in C?
Backslash
character
Meaning
b Backspace
n New line
t Horizontal tab
” Double quote
’ Single quote
Backslash
Escape sequences always begin with a backslash. They are non-
printable characters.
Categorize operators used in C
Operators are symbols which take one or more operands and
perform arithmetic or logical computations
Arithmetic operators
Assignment operators
Relational operators
Logical operators
Bit wise operators
Conditional operators (ternary operators)
Increment/decrement operators
Special operators
40. 40
What are Bit wise operators in C? Give example
Bit wise
operators
These operators are used to perform bit
operations on given two variables.
Decimal values are converted into binary values which are the
sequence of bits and bit wise operators work on these bits.
& – Bitwise AND
| – Bitwise OR
^ – XOR
<< – Left Shift
>> – Right Shift
What is a ternary operator (Conditional Operator)? Give
an example
Ternary Operator (Conditional operator) return one value if
condition is true and returns another value is condition is false.
This operator is also called as ternary operator.
Syntax: Condition? true_value: false_value;
(num%2==0)?printf("Even"):printf("Odd");
What is the main advantage of conditional operators?
Shorter and more concise when dealing with direct value
comparisons and assignments
Syntax: Condition? true_value: false_value;
(num%2==0)?printf("Even"):printf("Odd");
Differentiate between Relational and Logical Operators.
Give example.
Logical
operators
These operators are used to perform
logical operations on the given two
variables.
Operators Example/Description
&& (logical AND)
(x>5)&&(y<5)
It returns true when both conditions
are true
|| (logical OR)
(x>=10)||(y>=10)
It returns true when at-least one of the
condition is true
! (logical NOT)
!((x>5)&&(y<5))
If ((x>5) && (y<5)) is true, logical NOT
operator makes it false
41. 41
Relational
operators
These operators are used to compare
the value of two variables.
Operator Meaning of Operator Example
== Equal to 5 == 3 returns 0
> Greater than 5 > 3 returns 1
< Less than 5 < 3 returns 0
!= Not equal to 5 != 3 returns 1
>= Greater than or equal to 5 >= 3 returns 1
<= Less than or equal to 5 <= 3 return 0
List any four short-hand assignment operator.
Compound assignment operators / Shorthand Operators
(Example: +=, -=, *=, /=, %=, &=, ^= )
Operators Example/Description
+=
sum += 10;
This is same as sum = sum + 10
-=
sum -= 10;
This is same as sum = sum – 10
*=
sum *= 10;
This is same as sum = sum * 10
/=
sum /= 10;
This is same as sum = sum / 10
%=
sum %= 10;
This is same as sum = sum % 10
&=
sum&=10;
This is same as sum = sum & 10
^=
sum ^= 10;
This is same as sum = sum ^ 10
What is the significance of WHILE statement in C?
In while loop, first check the condition. If condition is true,
then control goes inside the loop body otherwise goes outside
the body.
Loop is executed only when condition is true.
#include<stdio.h>
#include<conio.h>
main()
{
int i=0;
while(i<10)
{
printf("%d ",i);
i++;
}
getch();
}
OUTPUT:
0 1 2 3 4 5 6 7 8 9
42. 42
What is the significance of DO...WHILE statement in C?
In do..while loop statement, loop is executed irrespective of the
condition for first time. Then 2nd time onwards, loop is executed
until condition becomes false.
Loop is executed for first time irrespective of the condition. After
executing while loop for first time, then condition is checked.
#include<stdio.h>
#include<conio.h>
main()
{
int i=0;
do
{
printf("%d ",i);
i++;
}while(i<10);
getch();
}
OUTPUT:
0 1 2 3 4 5 6 7 8 9
Differentiate between getchar() and scanf() functions for
reading strings.
Write the limitations of using getchar() and scanf()
functions for reading strings.
Function getchar reads a single character from a standard
input device keyboard till the user press the enter key. The
getchar function can be used to read sequence of characters by
repeated use of the function.
#include<stdio.h>
#include<conio.h>
main()
{
char c;
printf("Enter string:");
do
{
c=getchar();
putchar(c);
}while(c!='n');
getch();
}
Enter string: computer
computer
The scanf() function reads the input from the standard input
stream and scans that input according to the format provided.
#include<stdio.h>
#include<conio.h>
main()
{
char str[100];
printf("Enter string:");
scanf("%s", &str);
printf("Entered string: %s n", str);
getch();
}
Enter string: computer
Entered string: computer
43. 43
What is the use of “break” statement in C?
Break statement is used to terminate the while loops, switch
case loops and for loops from the subsequent execution.
Syntax:
break;
#include<stdio.h>
#include<conio.h>
main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("nComing out of for loop when i = 5");
break;
}
printf("%d ",i);
}
getch();
}
OUTPUT:
0 1 2 3 4
Coming out of for loop when i = 5
What is the use of “continue” statement in C?
Continue statement is used to continue the next iteration of for
loop, while loop and do-while loops. So, the remaining
statements are skipped within the loop for that particular
iteration.
Syntax:
continue;
#include<stdio.h>
#include<conio.h>
main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("nSkipping %d from display n",i);
continue;
}
printf("%d ",i);
}
getch();
}
OUTPUT:
0 1 2 3 4
Skipping 5 from display
6 7 8 9
44. 44
Define looping / iteration.
Looping / Iteration statements are used to perform looping
operations until the given condition is true. Control comes out
of the loop statements once condition becomes false.
FOR
WHILE
DO..WHILE
Jump Out of Loop (BREAK & CONTINUE)
Write a code segment using while statement to print
numbers from 10 down to 1
#include<stdio.h>
#include<conio.h>
main()
{
int i=10;
while(i>0)
{
printf("%d ",i);
i--;
}
getch();
}
OUTPUT
10 9 8 7 6 5 4 3 2 1
Write a for loop statement to print numbers from 10 to 1
#include<stdio.h>
#include<conio.h>
main()
{
int i;
for(i=10;i>0;i--)
{
printf("%d ",i);
}
getch();
}
OUTPUT
10 9 8 7 6 5 4 3 2 1
Write a C program to determine whether a number is
“odd” or “even” and print the message
#include<stdio.h>
#include<conio.h>
main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
if(number%2 == 0)
printf("%d is even.", number);
else
printf("%d is odd.", number);
getch();
}
45. 45
OUTPUT:
Enter an integer: 4
4 is even
How does the break statement provide a better control of
loops?
Break statement is used to terminate the while loops, switch
case loops and for loops from the subsequent execution.
Syntax:
break;
#include<stdio.h>
#include<conio.h>
main()
{
int i;
for(i=0;i<10;i++)
{
if(i==5)
{
printf("nComing out of for loop when i = 5");
break;
}
printf("%d ",i);
}
getch();
}
OUTPUT:
0 1 2 3 4
Coming out of for loop when i = 5
Give the output of the following code:
float c=34.78650;
printf("%6.2f",c);
OUTPUT:
34.79
Write a “C” program to implement the expression
((m+n)/p-m)*m), where m=4, n=6, p=8.
#include<stdio.h>
#include<conio.h>
main()
{
int m,n,p,result;
m=4;
n=6;
p=8;
result=((m+n)/(p-m)*m);
printf("Result:%d",result);
getch();
}
OUTPUT:
Result:8
46. 46
What will be the outputs for the following program, when
the value of i is 5 and 10
void main()
{
int i;
scanf("%d",&i);
if(i=5)
printf("Five");
}
OUTPUT:
Five
In both cases, word Five is printed
What does the following fragment print?
for(int i=0;i<10;i++)
{
if(!(i%2))
continue;
printf("%d ",i);
}
OUTPUT:
1 3 5 7 9
Describe the purpose of the qualifiers constant and
volatile.
const is used with a datatype declaration or definition to specify
an unchanging value
Examples:
const int five = 5;
When any variable has qualified by volatile keyword in
declaration statement then value of variable can be changed by
any external device or hardware interrupt (due to volatile).
Examples:
const volatile int a=6;
Explain any four format string with examples.
FORMAT SPECIFIER:
Conversion
Character
Meaning
%d Integer / Decimal
%c Character
%s String
%f floating point values – Float / Double
Symbols Meaning
n For new line
t For tab space
47. 47
Differentiate between signed and unsigned integer.
Is main() a keyword in c language?
Yes, main() is a keyword.
In C, program execution starts from the main() function. Every
C program must contain a main() function. The main function
may contain any number of statements. These statements are
executed sequentially in the order which they are written.
int main(); //main with no arguments
int main(int argc, char *argv[]); //main with arguments