Unit1-C
Unit1-C
Unit1-C
In C programming language, printf() function is used to print the “character, string, float, integer,
octal and hexadecimal values” onto the output screen.
We use printf() function with %d format specifier to display the value of an integer variable.
Similarly %c is used to display character, %f for float variable, %s for string variable, %lf for
double and %x for hexadecimal variable.
The printf() and scanf() functions are used for input and output in C language. Both functions are
inbuilt library functions, defined in stdio.h (header file).
printf() function
The printf() function is used for output. It prints the given statement to the console.
printf("format string",argument_list);
In C programming language, scanf() function is used to read character, string, numeric data from
keyboard
Consider below example program where user enters a character. This value is assigned to the
variable “ch” and then displayed.
Then, user enters a string and this value is assigned to the variable “str” and then displayed.
The scanf() function is used for input. It reads the input data from the console.
scanf("format string",argument_list);
3.WHAT AR E THE Comments in C?
Comments in C language are used to provide information about lines of code. It is widely used
for documenting code. There are 2 types of comments in C language.
Single line comments are represented by double slash \\. Let's see an example of single line
comment in C.
#include<stdio.h>
void main( )
{
//printing information
printf("Hello C");
Output:
Hello C
Example:
Multi line comments are represented by slash asterisk \* ... *\. It can occupy many lines of code
but it can't be nested. Syntax:
/*
code
to be commented
*/
Example of multi line comment in C.
#include<stdio.h>
void main()
{
/*printing information
Multi Line Comment*/
printf("Hello C");
Output:
Hello C
3. DEFINE KEYWORDS IN C?
Keywords are preserved words that have special meaning in C language. The meaning of C
language keywords has already been described to the C compiler. These meaning cannot be
changed. Thus, keywords cannot be used as variable names because that would try to change the
existing meaning of the keyword, which is not allowed. C Keywords are also called as reserved
words.
Do if static while
o Integer types
o Floating type
o Character type
Integers are whole numbers that can have both positive and negative values but no decimal
values. Example: 0, -5, 10
In C programming, keyword int is used for declaring integer variable. For example:
int id;
Floating type variables can hold real numbers such as: 2.34, -9.382, 5.0 etc. You can declare a
floating point variable in C by using either float or double keyword. For example:
float accountBalance;
double bookPrice;
The size of float (single precision float data type) is 4 bytes. And the size of double (double
precision float data type) is 8 bytes. Floating point variables has a precision of 6 digits whereas
the precision of double is 14 digits.
Keyword char is used for declaring character type variables. For example:
A constant is a value or an identifier whose value cannot be altered in a program. For example: 1,
2.5, "C programming is easy", etc.
Syntax:
Here, PI is a constant. Basically what it means is that, PI and 3.14 is same for this program.
Example:
#include<stdio.h>
main()
{
const int SIDE = 10;
int area;
area = SIDE*SIDE;
printf("The area of the square with side: %d is: %d sq. units"
, SIDE, area);
}
List of Constants in C:
1. Integer constants
An integer constant is a numeric constant (associated with number) without any fractional or
exponential part. There are three types of integer constants in C programming:
For example:
In C programming, octal constant starts with a 0 and hexadecimal constant starts with a 0x.
2. Floating-point constants
A floating point constant is a numeric constant that has either a fractional form or an exponent
form. For example:
-2.0
0.0000234
-0.22E-5
3. Character constants
A character constant is a constant which uses single quotation around characters. For example:
'a', 'l', 'm', 'F'.
4.String constants
String constants are the constants which are enclosed in a pair of double-quote marks. For
example:
Sometimes, it is necessary to use characters which cannot be typed or has special meaning in C
programming. For example: newline(enter), tab, question mark etc. In order to use these
characters, escape sequence is used.
For example: \n is used for newline. The backslash ( \ ) causes "escape" from the normal way the
characters are interpreted by the compiler.
Escape Sequences
\b Backspace
\f Form feed
\n Newline
\r Return
\t Horizontal tab
\v Vertical tab
\\ Backslash
\? Question mark
Escape Sequences
\0 Null character
C operators are symbols that are used to perform mathematical or logical manipulations. C
programming language is rich with built-in operators. Operators take part in a program for
manipulating data and variables and form a part of the mathematical or logical expressions.
C operators can be classified into following types:
Arithmetic operators
Relational operators
Logical operators
Bitwise operators
Assignment operators
Conditional operators
Special operators
Arithmetic Operators:
5 arithmetic operators are shown in the following table. Arithmetic operators are used to perform
arithmetic operations in c programming.
Operator Meaning Example
+ Addition Operator 10 + 20 = 30
- Subtraction Operator 20 – 10 = 10
/ Division Operator 20 / 10 = 2
% Modulo Operator 20 % 6 = 2
#include <stdio.h>
void main()
{
int num1,num2;
int sum,sub,mult,div,mod;
Output :
Addition is : 15
Subtraction is : 5
Multiplication is : 50
Division is : 2
Modulus is : 0
RELATIONAL OPERATOR:
Relational operators in c programming is used for specifying the relation between two operands
such as greater than, less than and equals.
In C Programming we can compare the value stored between two variables and depending on
the result we can follow different blocks using Relational Operator in C.
== Equal to 5 == 3 returns 0
#include <stdio.h>
void main()
int a, b;
a = 10;
b = 20;
if( a == 10 ) {
if( b == 10 )
{
if( a < b ) {
if( a != b ) {
a is equal to 10
a is less than b
a is not equal to b
Logical Operators
#include <stdio.h>
int main()
int a = 1;
int b = 0;
if ( a && b )
if ( a || b )
if ( !(a && b) )
When you compile and execute the above program, it produces the following result −
BITWISE OPERATORS:
Bitwise operators perform manipulations of data at bit level. These operators also
perform shifting of bits from right to left. Bitwise operators are not applied to float or double
Operator Description
| Bitwise OR
^ Bitwise exclusive OR
0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0
Assignment Operators
4. Assignment Operator have Two Values – L-Value and R-Value.Operator copies R-Value
into L-Value.
5. Assignment Operator have lower precedence than all available operators but has higher
= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result to left a+=b is same as
a=a+b
-= subtracts right operand from the left operand and assign the result to a-=b is same as a=a-b
left operand
*= mutiply left operand with the right operand and assign the result to left a*=b is same as a=a*b
operand
/= divides left operand with the right operand and assign the result to left a/=b is same as a=a/b
operand
%= calculate modulus using two operands and assign the result to left a%=b is same as a=a
operand %b
Conditional operator
The conditional operators in C language are known by two more names
1. Ternary Operator
2. ? : Operator
It is actually the if condition that we use in C language decision making, but using conditional
operator, we turn the if condition statement into a short and simple operator.
The syntax of a conditional operator is :
expression 1 ? expression 2: expression 3
A conditional operator is a ternary operator, that is, it works on 3 operands.
Output
sizeof operator
The sizeof is an unary operator which returns the size of data (constant, variables, array, structure
etc).
#include <stdio.h>
int main()
{
int a, e[10];
float b;
double c;
char d;
printf("Size of int=%lu bytes\n",sizeof(a));
printf("Size of float=%lu bytes\n",sizeof(b));
printf("Size of double=%lu bytes\n",sizeof(c));
printf("Size of char=%lu byte\n",sizeof(d));
printf("Size of integer type array having 10 elements = %lu bytes\n", sizeof(e));
return 0;
}
Output
Comma operator:
It is special kind of operator which is widely used in programming to separate the declaration of
multiple variable.
We have listed some of the hidden secrets of Comma operator and how it can be used in
programming in efficient manner.
It is special kind of operator which is widely used in programming to separate the declaration of
multiple variable.
We have listed some of the hidden secrets of Comma operator and how it can be used in
programming in efficient manner.
Precedence of Operators in C
The precedence of operator species that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right to
left
CONDITIONAL STATEMENTS:
C conditional statements allow you to make a decision, based upon the result of a condition.
In c programming, decision making is used to specify the order in which statements are
executed.
Decision making structures require that the programmer specifies one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the
condition is determined to be false.
C programming language assumes any non-zero and non-null values as true, and if it is
either zero or null, then it is assumed as false value.
o if statement
o if-else statement
o if-else-if ladder
o nested if statement
o switch statement
If Statement
The single if statement in C language is used to execute the code if condition is true.
if(expression)
{
statement inside;
}
statement outside;
If the expression returns true, then the statement-inside will be executed, otherwise statement-
inside is skipped and only the statement-outside is executed.
Example:
#include <stdio.h>
void main( )
{
int x, y;
x = 15;
y = 13;
if (x > y )
{
printf("x is greater than y");
}
}
x is greater than y
example 2:
if (c==11)
printf("Execute me 1");
printf("Execute me 2");
}
Output :
Execute me 1
If Statement :
if(conditional)
{
Statement No 1
Statement No 2
Statement No 3
.
.
.
Statement No N
}
Note :
if(conditional)
Statement No 1
Statement No 2
Statement No 3
if(100)
printf("True Condition");
structure of if:
if (condition/expression)
{
Statement 3;
}
Statement n;
An if statement can be followed by an optional else statement, which executes when the Boolean
expression is false.
or
The if...else statement executes some code if the test expression is true (nonzero) and some other code
if the test expression is false (0).
if(conditional)
{
//True code
}
else
{
//False code
}
Syntax of if...else
if (testExpression) {
else {
}
If test expression is true, codes inside the body of if statement is executed and, codes inside the
body of else statement is skipped.
If test expression is false, codes inside the body of else statement is executed and, codes inside
the body of if statement is skipped.
Example:
if(num == 20)
{
printf("True Block");
}
else
{
printf("False Block");
}
if(num == 20)
{
printf("True Block");
}
else
{
printf("False Block");
}
Example :
void main()
{
int marks=50;
if(marks>=40)
{
printf("Student is Pass");
}
else
{
printf("Student is Fail");
}
}
Output :
Student is Pass
Example:
#include <stdio.h>
int main()
{
int number;
printf("Enter an integer: ");
scanf("%d",&number);
// True if remainder is 0
if( number%2 == 0 )
printf("%d is an even integer.",number);
else
printf("%d is an odd integer.",number);
return 0;
}
Output
Enter an integer: 7
7 is an odd integer.
Example:
#include <stdio.h>
int main () {
int a = 100;
if( a < 20 ) {
} else {
return 0;
When the above code is compiled and executed, it produces the following result −
a is not less than 20;
value of a is : 100
example:
Example:
#include <stdio.h>
void main( )
{
int x, y;
x = 15;
y = 18;
if (x > y )
{
printf("x is greater than y");
}
else
{
printf("y is greater than x");
}
}
y is greater than x
example:
#include<stdio.h>
main() {
int num;
printf("Enter the number:");
scanf("%d", num);
/* check whether the number is negative number */ if (num < 0)
printf("The number is negative.");
else
printf("The number is positive.");
Out put:
Example:
int main()
{
int year;
printf("Enter a year to check if it is a leap year\n");
scanf("%d", &year);
if ( year%400 == 0)
printf("%d is a leap year.\n", year);
else if ( year%100 == 0)
printf("%d is not a leap year.\n", year);
else if ( year%4 == 0 )
printf("%d is a leap year.\n", year);
else
printf("%d is not a leap year.\n", year);
return 0;
2012
Leap year
example of even and odd number using if-else statement in C language.
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
else{
printf("%d is odd number",number);
}
return 0;
}
Output
enter a number:4
4 is even number
The if...else statement executes two different codes depending upon whether the test expression
is true or false. Sometimes, a choice has to be made from more than 2 possibilities.
The nested if...else statement allows you to check for multiple test expressions and execute
different codes for more than two conditions.
if (testExpression1)
else if(testExpression2)
else if (testExpression 3)
else
return 0;
}
Output
Enter two integers: 12
23
Result: 12 < 23
Example:
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number==10){
printf("number is equals to 10");
}
else if(number==50){
printf("number is equal to 50");
}
else if(number==100){
printf("number is equal to 100");
}
else{
printf("number is not equal to 10, 50 or 100");
}
return 0;
}
Output
enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50
SWITCH:
The if..else..if ladder allows you to execute a block code among many alternatives. If you are
checking on the value of a single variable in if...else...if, it is better to use switchstatement. In
nested if else when n statements are there n-1 times condition has to be checked. To avoid this
we use switch statement.
Switch statement is a control statement that allows us to choose only one choice among the many
given choices. The expression in switch evaluates to return an integral value, which is then
compared to the values present in different cases. It executes that block of code which matches
the case value. If there is no match, then default block is executed(if present). The general form
of switch statement is,
switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
case value-3:
block-3;
break;
case value-4:
block-4;
break;
default:
default-block;
break;
}
Rules for using switch statement
1. The expression (after switch keyword) must yield an integer value i.e the expression should
be an integer or a variable or an expression that evaluates to an integer.
2. The case label values must be unique.
3. The case label must end with a colon(:)
4. The next line, after the case statement, can be any valid C statement.
Points to Remember
1. We don't use those expressions to evaluate switch case, which may return floating point
values or strings or characters.
2. break statements are used to exit the switch block. It isn't necessary to use break after each
block, but if you do not use it, then all the consecutive blocks of code will get executed after
the matching block.
3. int i = 1;
4. switch(i)
5. {
6. case 1:
7. printf("A"); // No break
8. case 2:
9. printf("B"); // No break
10. case 3:
11. printf("C");
12. break;
}
ABC
The output was supposed to be only A because only the first case matches, but as there is
no break statement after that block, the next blocks are executed too, until it
a break statement in encountered or the execution reaches the end of the switch block.
13. default case is executed when none of the mentioned case matches the switch expression.
The default case can be placed anywhere in the switch case. Even if we don't include the
default case, switch statement works.
14. Nesting of switch statements are allowed, which means you can have switch statements
inside another switch block. However, nested switch statements should be avoided as it
makes the program more complex and less readable.
switch(choice)
{
case 1:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a + b;
printf("%d", c);
break;
case 2:
printf("Enter 2 numbers");
scanf("%d%d", &a, &b);
c = a - b;
printf("%d", c);
break;
default:
printf("you have passed a wrong key");
printf("\n press any key to continue");
}
}
}
#include<stdio.h>
int main(){
int number=0;
printf("enter a number:");
scanf("%d",&number);
switch(number){
case 10:
printf("number is equals to 10");
break;
case 50:
printf("number is equal to 50");
break;
case 100:
printf("number is equal to 100");
break;
default:
printf("number is not equal to 10, 50 or 100");
}
}
Output
enter a number:4
number is not equal to 10, 50 or 100
example:
#include<stdio.h>
main()
int a;
scanf("%d",&a);
switch(a)
case 1:
break;
case 2:
case 3:
break;
case 4:
break;
case 5:
break;
default :
break;
Example:
Example: switch Statement
# include <stdio.h>
int main() {
char operator;
double firstNumber,secondNumber;
switch(operator)
{
case '+':
printf("%.1lf + %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber+secondNumber);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf",firstNumber, secondNumber, firstNumber-secondNumber);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf",firstNumber, secondNumber,
firstNumber*secondNumber);
break;
case '/':
printf("%.1lf / %.1lf = %.1lf",firstNumber, secondNumber, firstNumber/firstNumber);
break;
return 0;
}
Output
12.4
Example
#include <stdio.h>
int main () {
switch(grade) {
case 'A' :
printf("Excellent!\n" );
break;
case 'B' :
case 'C' :
printf("Well done\n" );
break;
case 'D' :
printf("You passed\n" );
break;
case 'F' :
break;
default :
printf("Invalid grade\n" );
When the above code is compiled and executed, it produces the following result −
Well done
Your grade is B
C Loops
The loops in C language are used to execute a block of code or a part of the program several
times.
Suppose that you have to print table of 2, then you need to write 10 lines of code.
By using the loop statement, you can do it by 2 or 3 lines of code only.
Advantage of loops in C
1) It saves code.
while loops
do while loops
for loops
While loop:
while loop is a most basic loop in C programming. while loop has one control condition, and
executes as long the condition is true. The condition of the loop is tested before the body of the
loop is executed, hence it is called an entry-controlled loop.
Syntax:
While (condition)
statement(s);
Incrementation;
#include<stdio.h>
int main ()
{
/* local variable Initialization */ int n = 1,times=5;
Out put : 1 2 3 4 5
void main( )
{
int x;
x = 1;
while(x <= 10)
{
printf("%d\t", x);
/* below statement means, do x = x+1, increment x by 1*/
x++;
}
}
1 2 3 4 5 6 7 8 9 10
Example
Live Demo
#include <stdio.h>
int main () {
int a = 10;
/* while loop execution */
while( a < 20 ) {
a++;
return 0;
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
do...while loop
The do..while loop is similar to the while loop with one important difference. The body
of do...while loop is executed once, before checking the test expression. Hence, the do...while
loop is executed at least once.
or
C do while loops are very similar to the while loops, but it always executes the code block at
least once and furthermore as long as the condition remains true. This is an exit-controlledloop.
Syntax:
do
statement(s);
}while( condition );
Note :
Example
Live Demo
#include <stdio.h>
int main () {
int a = 10;
/* do loop execution */
do {
a = a + 1;
}while( a < 20 );
return 0;
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
#include <stdio.h>
int main()
{
double number, sum = 0;
printf("Sum = %.2lf",sum);
return 0;
}
Output
Enter a number: 0
Sum = 4.70
Example:
#include<stdio.h>
void main()
{
int a, i;
a = 5;
i = 1;
do
{
printf("%d\t", a*i);
i++;
}
while(i <= 10);
}
5 10 15 20 25 30 35 40 45 50
for loop in C
for loop
for loop is used to execute a set of statements repeatedly until a particular condition is satisfied.
We can say it is an open ended loop.. General format is,
for(initialization; condition; increment/decrement)
{
statement-block;
}
In for loop we have exactly two semicolons, one after initialization and second after the
condition. In this loop we can have more than one initialization or increment/decrement,
separated using comma operator. But it can have only one condition.
The for loop is executed as follows:
1 2 3 4 5 6 7 8 9 10
void main( )
{
int i, j;
/* first for loop */
for(i = 1; i < 5; i++)
{
printf("\n");
/* second for loop inside the first */
for(j = i; j > 0; j--)
{
printf("%d", j);
}
}
}
1
21
321
4321
54321
Comparison Chart
BASIS FOR
WHILE DO-WHILE
COMPARISON
} while( Condition );
Controlling Condition In 'while' loop the controlling In 'do-while' loop the controlling
condition appears at the start of the condition appears at the end of the
loop. loop.
Iterations The iterations do not occur if, the The iteration occurs at least once
example, if you want to store a long value into a simple integer then you can typecast long to int.
You can convert values from one type to another explicitly using the cast operator.
New data type should be mentioned before the variable name or value in brackets which to be
typecast.
A type cast is basically a conversion from one type to another. There are two types of type
conversion:
1. Implicit Type Conversion Also known as ‘automatic type conversion’.
Done by the compiler on its own, without any external trigger from the user.
Generally takes place when in an expression more than one data type is present. In
such condition type conversion (type promotion) takes place to avoid lose of data.
All the data types of the variables are upgraded to the data type of the variable with
largest data type.
bool -> char -> short int -> int ->
unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
It is possible for implicit conversions to lose information, signs can be lost (when
signed is implicitly converted to unsigned), and overflow can occur (when long long
is implicitly converted to float).
Example of Type Implicit Conversion:
// An example of implicit conversion
#include<stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // character c
x = 107, z = 108.000000
2. Explicit Type Conversion– This process is also called type casting and it is user defined.
Here the user can type cast the result to make it of a particular data type.
The syntax in C:
(type) expression
Type indicated the data type to which the final result is converted.
// C program to demonstrate explicit type casting
#include<stdio.h>
int main()
{
double x = 1.2;
return 0;
}
Output:
sum = 2