C Launguage 2 Unit
C Launguage 2 Unit
Precedence:
If there is more than one operator in an expression, which operation we need to perform first
is specified by precedence.
Associativity:
If more than one operator has the same precedence which operation we need to perform is
specified by associativity.
Arithmetic operators:
Note: Modulo division operator (%) is used only for integral values and cannot be used on
floating point data.
If either operand is of the real type, then only the real operation is performed and the result is
always a real number.
Example: 15.0/4=3.75 or
15/4.0=3.75
Example program:
#include<stdio.h> main()
{
int a,b;
floatc,d;
printf("enter 2 integer values\n");
scanf("%d%d",&a,&b);
printf("enter 2 float values\n");
scanf("%f%f",&c,&d);
printf("Integer Arithmetic %d/%d=%d\n",a,b,a/b);
printf("real Arithmetic %f/%f=%f\n",c,d,c/d);
printf("Mixed mode Arithmetic %f/%d=%f\n",c,b,c/b);
Relational operators:
Operator Meaning
< is less than
<= is less than or equal
> is greater than
>= is greater than or equal
== is equal to
!= is not equal to
Form:
Where ae-1 and ae-2 are arithmetic expressions, which may be simple constants, variables,
or combination of them.
Relational expressions are used in decision statements such as, if and while to decide the
course of a running program.
Rao’s Degree and PG College Page |3
M.Vaishnavi
Arithmetic operators have a higher priority than relational operators. Associativity is
from Left to Right.
Example program:
#include<stdio.h> main()
{
int a,b; printf("enter a,b\n");
scanf("%d%d",&a,&b); printf("%d<
%d=%d\n",a,b,a<b); printf("%d<=%d=
%d\n",a,b,a<=b); printf("%d>%d=%d\
n",a,b,a>b); printf("%d>=%d=%d\
n",a,b,a>=b); printf("%d==%d=%d\
n",a,b,a==b); printf("%d!=%d=%d\
n",a,b,a!=b);
}
Logical operators:
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
The logical operators && and || are used when we want to test more than one condition and
make decisions.
Logical expression yields a value of one or zero, according to the truth table.
Truth Table:
Assignment operators:
Assignment operators are used to assign the result of an expression to a variable. Assignment
operator is '='.
Example: a=10;
Left hand side must be a variable; Right hand side may be a variable/constant or combination
of these two.
v op=exp;
Example program:
#include<stdio.h> main()
{
int a,n;
printf("enter a,n values\n");
scanf("%d%d",&a,&n); a +=
100; printf("a=%d\n",a); a -=
20; printf("a=%d\n",a); a *=
(n+1); printf("a=%d\n",a);
a /= (n+1); printf("a=
%d\n",a); a %= n;
printf("a=%d\n",a);
}
Increment and Decrement operators:
• 'C' has two very useful operators not generally found in other languages. These are
increment and decrement operators: ++ and --
• The operator ++ adds 1 to the operand.
• The operator -- subtracts 1 from the operand.
• Both are unary operators.
• We use the increment and decrement statements in for and while loops extensively.
Statement with
Meaning
Operator
++a Pre increment
a++ Post increment
--a Pre decrement
a-- Post decrement
Rao’s Degree and PG College Page |6
M.Vaishnavi
• Both ++a and a++ mean the same thing when they form statements independently.
• They behave differently when they are used in expressions on the R.H.S. of an
assignment statement.
Statement with
Operator used in Meaning Explanation
assignment
First adds1 to a and then the
b = ++a Pre increment
result is assigned value of a to b
First assigns the value of a to b
b = a++ Post increment
and then add 1 to a
First subtracts 1 to a and then the
b = --a Pre decrement result is assigned value of a
to b
First assigns the value of a to b
b = a-- Post decrement
and then subtract 1 to a
Example Program:
#include<stdio.h> main()
{
int a,n;
printf("enter a value\n");
scanf("%d",&a); n=a++;
printf("a=%d\tn=%d\n",a,n);
n=++a;
printf("a=%d\tn=%d\n",a,n); n=a--;
printf("a=%d\tn=%d\n",a,n); n=--a;
printf("a=%d\tn=%d\n",a,n);
}
Output:
enter a value
4 a=5 n=4
a=6 n=6 a=5
n=6 a=4 n=4
Conditional operator:
Example:
int a=10, b=15, x; x=(a<b) ?
a : b;
Result:
x=10
Associativity is from Right -> Left.
//Program to find whether the given number is even or odd using conditional operator
#include<stdio.h> main()
{ int n;
printf("enter n value\n"); scanf("%d",&n);
(n%2==0)?printf("%d is even number\n",n):printf("%d is odd number\n",n);
}
Output 1: enter n
value
4
4 is even number
Output 2: enter n
value
5
5 is odd number
Example: #include<stdio.h>
main()
{
Output 1:
entera,b,c,d values
3
4
5
2
2.333333 Output 2:
entera,b,c,d values
3
4
5 5 c-d is
0
Bitwise operators:
• For manipulation of data at bit level, a special operators known as bitwise operators
are introduced.
• These operators are used for testing the bits or shifting them right or left.
• Bitwise operators may not be applied to float or double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
<< Shift Left
>> Shift Right
~ One’s Complement
Truth table for Bitwise AND, Bitwise OR and Bitwise Exclusive OR:
Example 1:
x=9
y=7
First convert given decimal number to binary number and then perform bitwise operation.
x=1001 y=0111
---------- z=
0001
Next convert the binary number to decimal number to get final result
z = 9 & 7=1
Example2:
x=4
y=14
x=0100 y=1110
----------
z=0100 = 4
z = 4 & 14=4
Bitwise OR (|):
x=1000 y=0111
----------
z=1111
Next convert the binary number to decimal number to get final result
z = 8| 7=15
Example2:
x=4
y=14
x=0100 y=1110
----------
z=1110 = 14
z = 4 | 14=4
Example 1:
x=5
y=7
First convert given decimal number to binary number and then perform bitwise operation.
x=101 y=111
---------- z=010
Next convert the
binary number to
decimal number
to get final result
z = 5 ^ 7=2
Example2:
x=0100 y=1110
----------
z=1010 = 10
z = 4 ^ 14=4
Example 1:
Find complement of 5 (~5)
Step1:
Convert decimal 5 into binary and take 8 bits.
0000 0101
First perform bits complement means change 1’s as 0’s and 0’s as 1’s (1’s complement).
1111 1010
MSB LSB
Step2:
If the MSB bit of result of bits complement is 1, then the final result contains –ve sign.
Always negative numbers in the system are represented using 2’s complement form.
Note:
(In binary addition 1+1 = 10 means 1 as carry and 0 as sum, 1+0=1, 0+0=0)
Example 2:
Find complement of -5 (~-5)
0000 0101
1111 1010
+1
--------------
1111 1011 ------------- -5 binary equivalent
Step2:
The shift operators are used to move bit patterns either to the left or to the right.
Where v is the integer expression (value) that is to be shifted and n is the number of bit
positions to be shifted.
Left shift:
Left shift means given number multiply by 2 per each shift.
Example:
6<<1 or x=6, x<<1
First convert decimal 6 to binary and take 8 bits.
MSB LSB
87654321
0000 0110
0000 0 110
87654321
0000 1110
87654321
This is the final bit result. Convert binary to decimal and it is equal to decimal 12.
6 << 1 = 12
Special operators:
Comma operator:
• This can be used to link the related expressions together.
• Comma liked lists of expressions are evaluated from left to right. And the value of
right most expression is the value of the combined expression.
• Comma operator has the lowest precedence of all operators, the parenthesis are
necessary.
Example:
Expressions:
Arithmetic expressions:
Examples:
Evaluation of expressions:
Expressions are evaluated using an assignment statement.
variable = expression
Where variable is any valid 'C' variable name.
Example:
a=9, b=12, c=3 x = a – b / 3 + c *
2 – 1 x = 9 – 12 / 3 + 3 * 2 – 1
Here, /, * having the same priority and highest priority, so follow the associativity, it is Left -
> Right.
Step1: evaluate 12 / 3 = 4
x=9–4+3*2–1
Step 2: evaluate 3 * 2 = 6
Next, -, + having the same priority, so follow the associativity, it is from Left -> Right.
Step3: 9 – 4 = 5
x=5+6–1
Step4: 5 + 6 = 11
x = 11 – 1
Step5: 11 – 1 = 10
Finally x = 10
Type conversion:
char
shortint int
longint float
double
long double
Example:
#include<stdio.h> main()
{
int a;
floatb,c;
printf("enter a,b values\n");
scanf("%d%f",&a,&b); c=a/b;
printf("c=%f\n",a/b);
}
Output:
entera,b values
4
5
c=0.800000
Explicit type conversion or casting a value:
For example,
#include<stdio.h> main()
{
int a,b;
float c;
printf("enter a,b values\n");
scanf("%d%d",&a,&b); c=a/b;
printf("c=%f\n",a/b);
}
Output:
entera,b values
4
5
c=0.000000
Consider the statement c=a/b;
• Here a, b are integer data type, so integer division is performed. The result of this
division is 0. So, the decimal part of the division would be lost and the result is not
correct.
• This problem can be solved by converting locally one of the variables to the floating
point.
• The operator (float) converts the 'a' to floating point for the purpose of evaluation of
the expression.
• Then automatically conversion is done and then the division is performed in floating
point mode.
• This process of such a local conversion is known as casting a value.
• Form is
Where type name is one of the valid ‘C’ data types and the expression may be a constant,
variable or an expression.
Example Action
x = (int) 4.78 4.78 is converted to integer by
#include
int main() {
int a = 10, b = 20, c = 5, result;
result = a + b * c / 2;
printf("Result: %d\n", result);
1. b * c is executed: 20 * 5 = 100
2. The result is divided by 2: 100 / 2 = 50
3. The result is added to a: 10 + 50 = 60
So, the final result is 60, following the precedence rules mentioned above.
Understanding the precedence of C arithmetic operators is essential for accurate and
efficient calculations in your programs.
4) getche( )
5) fgets( ) 4)fputs( )
6)fscanf( ) 5)fprint( )
Input means to provide the program with some data to be used in the program
Output means to display data on screen or write the data to a printer or a file.
input- getchar()
output- putchar()
The int getchar(void) function reads the next available character from the screen and returns it as an
integer. This function reads only single character at a time.
The int putchar(int c) function puts the passed character on the screen and returns the same
character. This function puts only single character at a time.
program
#include <stdio.h> int main( )
{
int c;
output $./a.out
Enter a value : this is DS class
printf( "Enter a value :"); c = You entered: t
getchar( );
return 0;
}
The gets( ) function reads a line from stdin into the buffer pointed to by s until either a terminating
newline or EOF (End of File).
The puts( ) function writes the string 's' and 'a' trailing newline to stdout.
Program
scanf()
scanf() is a predefined function in "stdio.h" header file. It can be used to read the input value from the
keyword.
Syntax of scanf() function
1. & ampersand symbol is the address operator specifying the address of the variable
2. control string holds the format of the data
3. variable1, variable2, ... are the names of the variables that will hold the input value.
Example
Example
double d; char c;
long int l;
scanf("%c%lf%ld",&c&d&l);
o Printf
o Printf is a predefined function in "stdio.h" header file, by using this function, we can print the data or user defined
message on console or monitor. While working with printf(), it can take any number of arguments but
first argument must be within the double cotes (" ") and every argument should separated with comma
( , ) Within the double cotes, whatever we pass, it prints same, if any format specifies are there, then
value is copied in that place.
Program
return 0; Output
The fgets() function takes three arguments, first is the string read from the file, second is size of
string(character array) and third is the file pointer from where the string will be read.
Example
File*fp; Str[80];
fgets(str,80,fp)
Example
#include<stdio.h> void
main()
{
FILE *fp; char
str[80];
hile((fgets(str,80,fp))!=NULL) printf("%s",str);
//reads content from file
fclose(fp);
}
Data in file...
C is a general-purpose programming language.
It is developed by Dennis Ritchie.
Output :
The fputs() function takes two arguments, first is the string to be written to the file and
second is the file pointer where the string will be written. Syntax:
fputs(char str[], FILE *fp);
# int include < stdio.h >
main
()
{
FILE *fp;
fp = fopen("proverb.txt", "w+"); //opening file in write mode
fputs("Cleanliness is next to godliness.", fp); fputs("Better
late than never.", fp); fputs("The pen is mightier than the
sword.", fp); fclose(fp); return(0);
}
Output
Cleanliness is next to godliness.
Better late than never.
The pen is mightier than the sword.
4. File string input and output using fgets( )and
fputs( ) The fscanf() function
The fscanf() function is used to read mixed type(characters, strings and integers) form the file. The fscanf() function is
similar to scanf() function except the first argument which is a file pointer that specifies the file to be read. Syntax:
Example program
void main()
{
FILE *fp; char ch;
int roll;
char name[25];
Output :
fprintf(FILE *fp,"format-string",var-list);
Examp
le
progr am #incl
ude<s tdio. h>
void main()
{ FILE *fp; introll; char name[25]; Output fp =
fopen("file.txt","w"); scanf("%d",&roll);
scanf("%s",name); fprintf(fp,"%d%s%",roll,name); 6666 john
close(fp);
}
The simplest of the console I/O functions are getche (), which reads a character from the keyboard,
and putchar (), which prints a character to the screen.
The getche () function works on until a key is pressed and then, returns its value. The key pressed is
also echoed to the screen automatically.
The putchar () function will write its character argument to the screen at the current cursor position.
The declarations for getche () and putchar () are −
int getche (void);
int putchar (int c);
The header file for getche () and putchar () is in CONIO.H.
Example
Here is an example which reads characters from the keyboard and prints them in
reverse case. This means that the uppercase prints as lowercase and the lowercase
prints as uppercase.
The program halts whenever a period is typed. The header file CTYPE.H is required by
the islower() library function, which returns true if its argument is lowercase and false
if it is not.
The trouble with getchar() is that it buffers input until a carriage return is entered.
The getchar() function uses the STDIO.H header file.
A second, more useful, variation on getche() is getch(), which operates precisely like getche () except
that the character you type is not echoed to the screen. It uses the CONIO.H header.
Formatted I/O functions are essential for handling user inputs and displaying
outputs in a user-friendly way. They enable programmers to:
S.NO Format
Type Description
. Specifier
5 %ld long int Used for I/O long signed integer value
These functions are called formatted I/O functions as they can use format specifiers
in these functions. Moreover, we can format these functions according to our needs.
1. printf()
2. scanf()
3. sprintf()
4. sscanf()
1. printf():
In C, printf() is a built-in function used to display values like numbers, characters,
and strings on the console screen. It’s pre-defined in the stdio.h header, allowing
easy output formatting in C programs.
Syntax 1
Example
// C program to implement
// printf() function
#include <stdio.h>
// Driver code
int main()
int a;
a = 20;
printf("%d", a);
return 0;
Output
20
Syntax 2:
Example
// C program to implement
// printf() function
#include <stdio.h>
int main()
printf("This is a string");
return 0;
Output
This is a string
2. scanf():
scanf(): In C, scanf() is a built-in function for reading user input from the
keyboard. It can read values of various data types like integers, floats,
characters, and strings. scanf() is a pre-defined function declared in
the stdio.h header file. It uses the & (address-of operator) to store user input
in the memory location of a variable.
Syntax
Example
// C program to implement
// scanf() function
#include <stdio.h>
int main()
int num1;
// Printing a message on
// from keyboard
scanf("%d", &num1);
return 0;
Output
3. sprintf():
sprintf(): Short for “string print,” sprintf() is similar to printf() but it stores the
formatted string into a character array instead of displaying it on the console screen.
Syntax
// C program to implement
#include <stdio.h>
// Driver code
int main()
char str[50];
int a = 2, b = 8;
a, b);
printf("%s", str);
return 0;
Output
4. sscanf():
sscanf(): Abbreviated for “string scanf,” sscanf() resembles scanf() but reads
data from a string or character array rather than from the console screen.
Syntax
Example
// C program to implement
// sscanf() function
#include <stdio.h>
// Driver code
int main()
char str[50];
int a = 2, b = 8, c, d;
// character array
a, b);
// c and d
&c, &d);
return 0;
Output
c = 2 and d = 8
Unformatted I/O Functions: These functions are used exclusively for character data types or
character arrays/strings. They are designed for reading single inputs from the user at the console
and for displaying values on the console.
1. getch()
2. getche()
3. getchar()
4. putchar()
5. gets()
6. puts()
7. putch()
1. getch():
getch(): In C, getch() reads a single character from the keyboard without
displaying it on the console screen. It immediately returns without requiring the
user to press the Enter key. This function is declared in the conio.h header file and
is often used for controlling screen display.
Syntax
getch();
or
variable-name = getch();
Example
// C program to implement
// getch() function
#include <stdio.h>
// Driver code
int main()
// not displays
getch();
return 0;
Output
2. getche():
In C, getche() reads a single character from the keyboard, displays it on the console
screen, and immediately returns without requiring the user to press the Enter key.
This function is declared in the conio.h header file.
Syntax
or
variable_name = getche();
Example
// C program to implement
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
// displays immediately
getche();
return 0;
3. getchar():
In C, getchar() reads a single character from the keyboard and waits until the Enter
key is pressed. It processes one character at a time. This function is declared in
the stdio.h header file
Syntax
Variable-name = getchar();
Example
// C program to implement
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
char ch;
ch = getchar();
printf("%c", ch);
return 0;
Output
4. putchar():
Syntax
putchar(variable_name);
Example
// C program to implement
#include <stdio.h>
// Driver code
int main()
char ch;
// Reads a character
ch = getchar();
putchar(ch);
return 0;
Output
5. gets():
In C, gets() reads a group of characters or strings from the keyboard, and these
characters are stored in a character array. It allows you to input space-separated
texts or strings. This function is declared in the stdio.h header file. However,
Syntax
char str[length of string in number]; //Declare a char type variable of any length
gets(str);
Example
// C program to implement
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
// of length 50 characters
char name[50];
gets(name);
// or a string
name);
return 0;
Output
6. puts():
In C programming, puts() is used to display a group of characters or strings that are already stored in a
character array. This function is declared in the stdio.h header file.
Syntax
puts(identifier_name );
Example
// C program to implement
#include <stdio.h>
// Driver code
int main()
char name[50];
gets(name);
// Displays string
puts(name);
return 0;
Output
7. putch():
In C, putch() is used to display a single character provided by the user, and it prints
the character at the current cursor location. This function is declared in
the conio.h header file
Syntax
putch(variable_name);
Example
// C program to implement
#include <conio.h>
#include <stdio.h>
// Driver code
int main()
char ch;
ch = getch();
putch(ch);
return 0;
Output
S
Formatted I/O functions Unformatted I/O functions
No.
2 They will support format specifiers. They will support format specifiers.
3 These will store data more user-friendly These functions are notuser-friendly.