0% found this document useful (0 votes)
0 views18 pages

C Programming unit I

C Programming unit I notes

Uploaded by

iswarnav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views18 pages

C Programming unit I

C Programming unit I notes

Uploaded by

iswarnav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Unit-I: Introduction to C

C is a general-purpose, high-level language that was originally developed by Dennis M.


Ritchie to develop the UNIX operating system at Bell Labs. C was originally first
implemented on the DEC PDP-11 computer in 1972.
In 1978, Brian Kernighan and Dennis Ritchie produced the first publicly available description
of C, now known as the K&R standard.
The UNIX operating system, the C compiler, and essentially all UNIX application programs
have been written in C. C has now become a widely used professional language for various
reasons −

 Easy to learn
 Structured language
 It produces efficient programs
 It can handle low-level activities
 It can be compiled on a variety of computer platforms

Facts about C

 C was invented to write an operating system called UNIX.


 C is a successor of B language which was introduced around the early 1970s.
 The language was formalized in 1988 by the American National Standard Institute
(ANSI).
 The UNIX OS was totally written in C.
 Today C is the most widely used and popular System Programming Language.
 Most of the state-of-the-art software have been implemented using C.
 Today's most popular Linux OS and RDBMS MySQL have been written in C.
Uses of C
C is a language that is used to program a wide variety of systems. Some of the uses of C are
as follows:
Major parts of Windows, Linux, and other operating systems are written in C.
C is used to write driver programs for devices like Tablets, Printers, etc.
C language is used to program embedded systems where programs need to run faster in
limited memory.
C is used to develop games, an area where latency is very important, i.e., a computer has to
react quickly to user input.
Chapter 1: Variables, Constants, and Keywords:
Variables
A variable is a container that stores a ‘value.’ In the kitchen, we have containers storing rice,
dal, sugar, etc. Similar to that variable in c stores the value of a constant. Example:
a = 3 a is assigned “3”
b = 4.7 b is assigned “4.7”
c = 'A' c is assigned “A”
Rules for naming variables in c:
1. The first character must be an alphabet or underscore(_).
2. No commas or blanks are allowed.
3. No special symbol other than underscore is allowed
4. Variable names are case sensitive.

Constants
An entity whose value doesn’t change is called a constant.
Types of constant
Primarily there are 3 types of constant:
1. Integer Constant -1,6,7,9
2. Real Constant -322.1,2.5,7.0
3. Character Constant ‘a’,’$’,’@’(must be enclosed within single inverted commas)

Keywords
These are reserved words whose meaning is already known to the compiler. There are 32
keywords available in c:

auto double int struct


break long else switch
case return enum typedef
char register extern union
const short float unsigned
continue void default sizeof
signed for volatile while
do static if goto

Our first C program


#include<stdio.h>
int main() {
printf(“Hello, I am learning C with Harry”);
return 0;
}

Types of variables
Integer variables int a=3;
Real variables int a=7.7 (wrong as 7.7 is real) ; float a=7.7;
Character variables char a=’B’;
Receiving input from the user
In order to take input from the user and assign it to a variable, we use scanf function.
The syntax for using scanf:
scanf(“%d”,&i); // [This & is important]
& is the “address of” operator, and it means that the supplied value should be copied to the
address which is indicated by variable i.

Data Type
Data types in c refer to an extensive system used for declaring variables or functions of
different types. The type of a variable determines how much space it occupies in storage and
how the bit pattern stored is interpreted.
The types in C can be classified as follows −

S.No. Types & Description

1 Basic Types
They are arithmetic types and are further classified into: (a) integer types and (b)
floating-point types.
2 Enumerated types
They are again arithmetic types and they are used to define variables that can
only assign certain discrete integer values throughout the program.
3 The type void

The type specifier void indicates that no value is available.


4 Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types, (d) Union
types and (e) Function types.
The array types and structure types are referred collectively as the aggregate types. The type
of a function specifies the type of the function's return value. We will see the basic types in
the following section, where as other types will be covered in the upcoming chapters.
Integer Types
The following table provides the details of standard integer types with their storage sizes and
value ranges −

Type Storage size Value range


char 1 byte -128 to 127 or 0 to 255
unsigned char 1 byte 0 to 255
signed char 1 byte -128 to 127
int 2 or 4 bytes -32,768 to 32,767 or -2,147,483,648 to 2,147,483,647
unsigned int 2 or 4 bytes 0 to 65,535 or 0 to 4,294,967,295
short 2 bytes -32,768 to 32,767
unsigned short 2 bytes 0 to 65,535
long 8 bytes -9223372036854775808 to 9223372036854775807
unsigned long 8 bytes 0 to 18446744073709551615

Floating-Point Types
The following table provide the details of standard floating-point types with storage sizes and
value ranges and their precision −
Type Storage size Value range Precision
float 4 byte 1.2E-38 to 3.4E+38 6 decimal places
double 8 byte 2.3E-308 to 1.7E+308 15 decimal places
long double 10 byte 3.4E-4932 to 1.1E+4932 19 decimal places

Variable Definition in C
A variable definition tells the compiler where and how much storage to create for the
variable. A variable definition specifies a data type and contains a list of one or more
variables of that type as follows −
type variable_list;
Here, type must be a valid C data type including char, w_char, int, float, double, bool, or any
user-defined object; and variable_list may consist of one or more identifier names separated
by commas. Some valid declarations are shown here −
int i, j, k;
char c, ch;
float f, salary;
double d;
The line int i, j, k; declares and defines the variables i, j, and k; which instruct the compiler to
create variables named i, j and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The initializer
consists of an equal sign followed by a constant expression as follows −
type variable_name = value;
Some examples are −
extern int d = 3, f = 5; // declaration of d and f.
int d = 3, f = 5; // definition and initializing d and f.
byte z = 22; // definition and initializes z.
char x = 'x'; // the variable x has the value 'x'.

Defining Constants
There are two simple ways in C to define constants −
 Using #define preprocessor.
 Using const keyword.
The #define Preprocessor
Given below is the form to use #define preprocessor to define a constant –

Syntax
#define identifier value
The following example explains it in detail −
#include <stdio.h>
#define LENGTH 10
#define WIDTH 5
#define NEWLINE '\n'
int main() {
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result −

Output:
value of area : 50
The const Keyword
You can use const prefix to declare constants with a specific type as follows −
const type variable = value;
The following example explains it in detail −
#include <stdio.h>
int main() {
const int LENGTH = 10;
const int WIDTH = 5;
const char NEWLINE = '\n';
int area;
area = LENGTH * WIDTH;
printf("value of area : %d", area);
printf("%c", NEWLINE);
return 0;
}
When the above code is compiled and executed, it produces the following result −
Output:
value of area : 50

Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
functions. C language is rich in built-in operators and provides the following types of
operators.
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators
We will, in this chapter, look into the way each operator works.

Arithmetic Operators
The following table shows all the arithmetic operators supported by the C language. Assume
variable A holds 10 and variable B holds 20 then −
Show Examples
Operator Description Example
+ Adds two operands. A + B = 30
− Subtracts second operand from the first. A − B = 10
* Multiplies both operands. A * B =200
/ Divides numerator by de-numerator. B/A=2
% Modulus Operator and remainder of after an integer division. B%A=0
++ Increment operator increases the integer value by one. A++ = 11
-- Decrement operator decreases the integer value by one. A-- = 9
Relational Operators
The following table shows all the relational operators supported by C. Assume variable A
holds 10 and variable B holds 20 then –
Show Examples

Operator Description Example


== Checks if the values of two (A == B) is not true.
operands are equal or not. If
yes, then the condition
becomes true.
!= Checks if the values of two (A != B) is true.
operands are equal or not. If
the values are not equal,
then the condition becomes
true.
> Checks if the value of left (A > B) is not true.
operand is greater than the
value of right operand. If
yes, then the condition
becomes true.
< Checks if the value of left (A < B) is true.
operand is less than the
value of right operand. If
yes, then the condition
becomes true.
>= Checks if the value of left (A >= B) is not true.
operand is greater than or
equal to the value of right
operand. If yes, then the
condition becomes true.
<= Checks if the value of left (A <= B) is true.
operand is less than or equal
to the value of right operand.
If yes, then the condition
becomes true.
Logical Operators
Following table shows all the logical operators supported by C language. Assume variable A
holds 1 and variable B holds 0, then −
Show Examples

Operator Description Example


&& Logical AND operator. (A && B) is false.
If both the operands are non-
zero, then the
conditionbecomes true.
|| Logical OR Operator. If any (A || B) is true.
of the two operands is non-
zero, then the condition
becomes true.
! Logical NOT Operator. It is !(A && B) is true.
used to reverse the logical
state of its operand.
Bitwise Operators
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |, and
^ is as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1

Assume A = 60 and B = 13 in binary format, they will be as follows −

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011
The following table lists the bitwise operators supported by C. Assume variable 'A' holds 60
and variable 'B' holds 13, then −
Show Examples
Operator Description Example

& Binary AND Operator copies (A & B) = 12, i.e., 0000 1100
a bit to the result if it exists in
both operands.

| Binary OR Operator copies a (A | B) = 61, i.e., 0011 1101


bit if it exists in either
operand.

^ Binary XOR Operator copies (A ^ B) = 49, i.e., 0011 0001


the bit if it is set in one
operand but not both.

~ Binary One's Complement (~A ) = ~(60), i.e,. -0111101


Operator is unary and has
the effect of 'flipping' bits.

<< Binary Left Shift Operator.


The left operands value is
moved left by the number of A << 2 = 240 i.e., 1111 0000
bits specified by the right
operand.

>> Binary Right Shift Operator.


The left operands value is
moved right by the number of A >> 2 = 15 i.e., 0000 1111
bits specified by the right
operand.

Assignment Operators
The following table lists the assignment operators supported by the C language −
Show Examples
Operator Description Example

= Simple assignment operator. Assigns values C = A + B will assign the value of


from right side operands to left side operand A + B to C

+= Add AND assignment operator. It adds the right


operand to the left operand and assign the C += A is equivalent to C = C + A
result to the left operand.

-= Subtract AND assignment operator. It subtracts


the right operand from the left operand and C -= A is equivalent to C = C - A
assigns the result to the left operand.
*= Multiply AND assignment operator. It multiplies
the right operand with the left operand and C *= A is equivalent to C = C * A
assigns the result to the left operand.

/= Divide AND assignment operator. It divides the


left operand with the right operand and assigns C /= A is equivalent to C = C / A
the result to the left operand.

%= Modulus AND assignment operator. It takes


modulus using two operands and assigns the C %= A is equivalent to C = C % A
result to the left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= Bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= Bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Conditional Operator in C
The Conditional Operator in C, also called a Ternary operator, is one of the Operators, which
used in the decision-making process. The C Programming Conditional Operator returns the
statement depends upon the given expression result.
The basic syntax of a Ternary Operator in C Programming is as shown below:

Test expression? statement1: statement2

#include<stdio.h>
int main()
{
int age;
printf(" Please Enter your age here: \n ");
scanf(" %d ", &age);
(age >= 18) ? printf(" You are eligible to Vote ") : printf(" You are not eligible to
Vote ");
return 0;
}
OUTPUT:

Please Enter your age here:


19
You are eligible to Vote
Special Operator
C provides following special operator.
Operator Description Example
sizeof Returns the size of an variable sizeof(x) return size of the
variable x
& Returns the address of an &x ; return address of the
variable variable x
* Pointer to a variable *x ; will be pointer to a
variable x

INCREMENT AND DECREMENT OPERATORS

Increment Operators:
The increment operator is used to increment the value of a variable in an expression. In the Pre-
Increment, value is first incremented and then used inside the expression. Whereas in the Post-
Increment, value is first used inside the expression and then incremented.
Syntax:

// PREFIX
++m

// POSTFIX
m++

where m is a variable
Example:

#include <stdio.h>

int increment(int a, int b)


{
a = 5;

// POSTFIX
b = a++;
printf("%d", b);

// PREFIX
int c = ++b;
printf("\n%d", c);
}

// Driver code
int main()
{
int x, y;
increment(x, y);

return 0;
}
Decrement Operators:
The decrement operator is used to decrement the value of a variable in an expression. In the
Pre-Decrement, value is first decremented and then used inside the expression. Whereas in the
Post-Decrement, value is first used inside the expression and then decremented.
Syntax:

// PREFIX
--m

// POSTFIX
m--

where m is a variable
Example:

#include <stdio.h>

int decrement(int a, int b)


{
a = 5;

// POSTFIX
b = a--;
printf("%d", b);

// PREFIX
int c = --b;
printf("\n%d", c);
}

// Driver code
int main()
{
int x, y;
decrement(x, y);

return 0;
}
ARITHMETIC EXPRESSIONS IN C
PROGRAMMING – I

C has a wide range of operators. An arithmetic expression is composed ofoperators and


operands. Operators act on operands to yield a result. Commonly used arithmetic operators are
+, -, *, / and %.The plus sign (+) is used to add two values, the minus sign (-) to subtract one
value from another, the asterisk(*) to multiply two values, the division (/) to divide a value and
the modulus (%) to obtain the reminder of integer division. These are known as binary operators
since they operate on two values or variables.
Following are examples of arithmetic expressions :
result = x - y;
total = principle + interest;
numsquare = x * x;
celcius = (fahrenheit - 32) / 1.8

 Notice the equal sign (=) in the above expressions, it is known as the assignment
operator. It assigns the value on the right hand side of the equal sign to the variable on
the left hand side.
 In the last expression, parentheses are used to perform a certain operation first. This is
because in C, operators follow a precedence rule. *, / and % have a higher precedence
over + and -. Hence to override the precedence, parentheses should be used.
Expressions having operators of the same precedence are generally evaluated from left
to right.
 Another point to note is that in an expression which involves division, care should be
taken to avoid a division by zero, since this results in infinity or an abnormal value.

#include <stdio.h>
Void main()
{
int var1 = 10;
int var2 = 2;
int var3 = 35;
int var4 = 8;
int result;
result = var1 + var2;
printf("Sum of var1 and var2 is %d\n", result);
result = var3 * var3;
printf("Square of var3 is %d\n", result);
result = var2 +var3 * var4; /* precedence */
printf("var2 + var3 * var4 =%d\n", result);
}
Evaluation of Expression
In the C programming language, an expression is evaluated based on the operator precedence
and associativity. When there are multiple operators in an expression, they are evaluated
according to their precedence and associativity. The operator with higher precedence is
evaluated first and the operator with the least precedence is evaluated last.An expression is
evaluated based on the precedence and associativity of the operators in that expression.
To understand expression evaluation in c, let us consider the following simple example
expression...

10 + 4 * 3 / 2

In the above expression, there are three operators +, * and /. Among these three operators,
both multiplication and division have the same higher precedence and addition has lower
precedence. So, according to the operator precedence both multiplication and division are
evaluated first and then the addition is evaluated. As multiplication and division have the
same precedence they are evaluated based on the associativity. Here, the associativity of
multiplication and division is left to right. So, multiplication is performed first, then division
and finally addition. So, the above expression is evaluated in the order of * / and +. It is
evaluated as follows...

4 * 3 ====> 12
12 / 2 ===> 6
10 + 6 ===> 16
The expression is evaluated to 16.

Operators Precedence in C
Operator precedence determines the grouping of terms in an expression and decides how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has a higher precedence than the addition operator.

For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has a higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

Unary + - ! ~ ++ - - (type)* & sizeof Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left


Assignment = += -= *= /= %=>>= <<= &= Right to left
^= |=

Comma , Left to right

Mathematical functions
The math.h header defines various mathematical functions and one macro. All
the functions available in this library take double as an argument and return
double as the result. Let us discuss some important functions one by one.
1. double ceil(double x): The C library function double ceil (double x) returns the
smallest integer value greater than or equal to x.

Syntax: double ceil(double x)

// C code to illustrate
// the use of ceil function.
#include <stdio.h>
#include <math.h>

int main ()
{
float val1, val2, val3, val4;

val1 = 1.6;
val2 = 1.2;
val3 = -2.8;
val4 = -2.3;
printf ("value1 = %.1lf\n", ceil(val1));
printf ("value2 = %.1lf\n", ceil(val2));
printf ("value3 = %.1lf\n", ceil(val3));
printf ("value4 = %.1lf\n", ceil(val4));
return(0);
}
Output:
value1 = 2.0
value2 = 2.0
value3 = -2.0
value4 = -2.0

2. double floor(double x): The C library function double floor(double x) returns


the largest integer value less than or equal to x.
syntax : double floor(double x)
C - File Handling - Read and Write Characters
The getchar() and putchar() Functions
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. You can
use this method in the loop in case you want to read more than one character from the
screen.
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. You can use this
method in the loop in case you want to display more than one character on the screen.
Check the following example –

#include <stdio.h>
int main( )
{
int c;
printf( "Enter a value :");
c = getchar( );
printf( "\nYou entered: ");
putchar( c );
return 0;
}
When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then the program proceeds and reads only a
single character and displays it as follows −
Output:
Enter a value : this is test
You entered: t
The gets() and puts() Functions
The char *gets(char *s) function reads a line from stdin into the buffer pointed to by s
until either a terminating newline or EOF (End of File).
The int puts(const char *s) function writes the string 's' and 'a' trailing newline to
stdout.

#include <stdio.h>
int main( )
{
char str[100];
printf( "Enter a value :");
gets( str );
printf( "\nYou entered: ");
puts( str );
return 0;
}
When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then the program proceeds and reads the
complete line till end, and displays it as follows −
Output:
Enter a value : this is test
You entered: this is test

The scanf() and printf() Functions


The int scanf(const char *format, ...)
function reads the input from the standard input stream stdin and scans that input
according to the format provided.
The int printf(const char *format, ...) function writes the output to the standard
output stream stdout and produces the output according to the format provided.
The format can be a simple constant string, but you can specify %s, %d, %c, %f, etc.,
to print or read strings, integer, character or float respectively. There are many other
formatting options available which can be used based on requirements. Let us now
proceed with a simple example to understand the concepts better –

#include <stdio.h>
int main( )
{
char str[100];
int i;
printf( "Enter a value :");
scanf("%s %d", str, &i);
printf( "\nYou entered: %s %d ", str, i);
return 0;
}
When the above code is compiled and executed, it waits for you to input some text.
When you enter a text and press enter, then program proceeds and reads the input and
displays it as follows –
Output:
Enter a value : seven 7
You entered: seven 7
Formatted Input and Output Functions:
C provides standard functions scanf() and printf(), to perform formatted inputs and outputs.
These functions accept a format specification string and a variable list as the parameters. 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 I/O.
scanf()
The scanf() function is used for inputs formatted from standard inputs and provides numerous
conversion options for the printf() function.
Syntax:
scanf(format_specifiers, &data1, &data2,……); // & is address operator
The scanf() function reads and converts the characters from the standard input according to
the format specification string and stores the input in the memory slots represented by the
other arguments.
Example:
scanf(“%d %c”,&data1,&data2);
In the case of string data names, the data name is not prefixed with the &.

printf()
The printf() function is used for output formatted as the standard output according to a format
specification. The format specification string and the output data are the parameters of the
printf() function.

Syntax:
printf(format_specifiers, data1, data2,…..... );
Examples:
printf(“%d %c”, data1, data2);
The character specified after % is referred to as a conversion character because it allows a
data type to be converted to another type and printed.
Formatted Input and Output
The format specification string can contain text as well.
printf(“Number: %d\n”, data1);
printf(“%d\n%c”, data1, data2);
Example program:
#include <stdio.h>
void main()
{
int a;
printf(“Enter a value: ”);
scanf(“%d”,&a);
printf(“Entered Value= %d”,a);
}

You might also like