100% found this document useful (1 vote)
704 views76 pages

C - 1 Unit

C is a general-purpose programming language developed in 1972, known for its portability, low-level memory access, and structured syntax. Learning C is beneficial as it serves as a foundation for many modern programming languages and emphasizes procedural programming. A C program consists of several key components including documentation, preprocessor directives, global declarations, and the main function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
704 views76 pages

C - 1 Unit

C is a general-purpose programming language developed in 1972, known for its portability, low-level memory access, and structured syntax. Learning C is beneficial as it serves as a foundation for many modern programming languages and emphasizes procedural programming. A C program consists of several key components including documentation, preprocessor directives, global declarations, and the main function.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 76

Introduction to C Programming

1
What is C?
• C is a general-purpose programming language created by Dennis Ritchie at the Bell
Laboratories of AT&T Labs in 1972.

• C is strongly associated with UNIX, as it was developed to write the UNIX operating
system.

• The main features of the C language include:

 General Purpose and Portable


 Low-level Memory Access
 Fast Speed
 Clean Syntax
 Structured language 2
Why Should We Learn
C?
• It is one of the most popular programming language in the world.

• Many languages (e.g. C++, Java, JavaScript) have borrowed syntax/features directly or
indirectly from the C language.

• So, if a person learns C programming first, it will help him to learn any modern
programming language as well.

• C is modular and structured. Therefore, any computer student easily understand the
code.

• C a procedural language Because C programs follow a procedure of steps written in


it.
3
• C follows a top-down approach and much importance is given to flow of program.
Procedural == step by step
Statically Type ==type of variable is checked at the time of compilation but not at run
time 4
Structure of the C Program: -

The basic structure of a C program is divided into 6


parts

1. Documentation
2. Preprocessor Section
3. Definition
4. Global Declaration
5. Main() Function
6. Sub Programs

5
Documentation Section: -

• This section consists of the description of the program, the name of the program, and
the creation date and time of the program.
• It is specified at the start of the program in the form of comments.
// description, name of the program, programmer name, date, time etc.

/* description, name of the program, programmer name, date, time etc. */

Preprocessor Section: -

All the header files of the program will be declared in this section.
#include<stdio.h>
#include<math.h>

6
Definition:-

• Includes preprocessor directive, which contains symbolic constants.


• #define allows us to use constants in our code. It replaces all the constants with its
value in the code
#define x 5

Global Declaration: -
• It contains global variables, function declaration, and static variables.
• Variables and functions which are declared in this scope, can be used anywhere in the
program.
int y = 10;

7
Main () Function: -

• Every C program must have a main() function.


• Operations like declaration and execution are performed inside the curly braces of the
main program.
• The return type of the main() function can be int as well as void too. void() main tells
the compiler that the program will not return any value. The int main() tells the
compiler
that the program will return an integer value.
int main() { }
void main() { }
Sub Programs:-

• User-defined functions are called in this section of the program.


• The control of the program is shifted to the called function whenever they are called from the main or outside the
main() function.
• These are specified as per the requirements of the programmer. 8
/* Sum of two numbers */ ------------------------  //Documentation section

#include<stdio.h> ------------------------  // Preprocessor section

# define x 500 ------------------------  // Definition section

int c=2; - -----------------------  // Global Declaration

int main() - -----------------------  // main function


{
int a, b, sum;
printf("Enter two numbers");
scanf("%d %d", &a, &b);
sum = a + b + c +x; // calculating sum
printf("Result is %d", sum);
return 0; // return the integer value in the sum
} 9
First Look at a C Program:-

/* Program to compute addition of two number */

#include <stdio.h>
int main()
{
int number1, number2, sum;
printf("Enter two integers: ");
scanf("%d %d", &number1, &number2);
sum = number1 + number2;
printf("%d + %d = %d", number1, number2, sum);
return 0;
}

10
Variables:-
• It is a data name that can be used to store a data value. Unlike
constants, a variable may take Different values in memory during execution.

• The information represented by the variable can change during the execution of
the program. However, the data type associated with the variable cannot change.

• Variables consist of letters and digits, in any order except that the first character
must be a letter.

• Both upper- and lowercase letters are permitted. It is Case sensitive. i.e.,
variable names : [ ‘area’, ‘AREA’ and ‘Area’ ] are all different.

• The underscore character ( _) can also be included.

• Variables names should not be a keywords (like for, char, main, etc.) 11
• A variable name can be chosen by the programmer in a meaningful way
as according to the nature of the program. E.g. average, height, total.

• Normally the variables are defined in the following way:

• Check the following variable names are valid or not:


Student, a, sum1, sum1_average2, 123, %, (area), student$, int_student

12
Declaration of Variables:-
• There are two purposes:
 It tells the compiler what the variable name is.
 It specifies what type of data the variable will hold.

• General syntax: data-type variable-list;

• Examples:
 int velocity, distance;
 int a, b, c, d;
 float temp;
 char flag, option;

13
Data Types:-
• Specifies what kind of data to be stored in the variable.

• It also specifies how much memory should be allocated for the particular variable.

• Based on the data types of variables and constants, the expressions are validated
by the compiler.

• Data types are classified as:


 Fundamental or basic data types (int, char float)
 Derived data types (array, structures, functions, pointers)
 User-defined data types

14
Basic data Type:- (1) The Integer type
• An integer is a continuous collection of digits without a decimal point.

• C offers following types of integers:-


 int (%d)
 short int (%hd)
 long int (%ld)

• Signed and Unsigned integer:-


By default all the int types are signed.
(i.e. [int and signed int], both are same)
unsigned int: stores only positive
integers.

-=-==--=-=--=-=--=-=-=--=-=--=-=--=-=-=--
 A signed integers uses one bit for sign and remaining bits for magnitude of the number.
=-=-=-=--=-=--=-=--=-=-=--=-=-=--=-=--=-
 Unsigned integers uses all the bits for the magnitude of the number. 15
Basic data Type:- (2) The floating point type
• A floating point number (or real number) is a number with a decimal point, which
divides it into integral and fractional components.

• Different types:
 float (%f) precision upto 6 digit
 Double (%lf) precision upto 14 digit
 long double (%Lf)

• printf(“%f”, 1.123456789); output: 1.123457

(3) The character type


• Use to define characters
char (%c)
• Both signed and unsigned
16
Data Input and output:-

• Header file (#include<stdio.h>)supplies required information to the library


functions scanf and printf .

• printf(control string, arg1, arg2, . . . , argn);

• scanf(contro1 string, &argl, &arg2, . . . , &argn);

17
Details of different data types and their format specifiers:-

18
Operators in C can be classified into these categories:

• Arithmetic operators
• Relational operators
• Logical operators
• Assignment operators
• Conditional operator
• Increment and Decrement operators
• Bitwise operators

The data items that operators act upon are called operands.

19
Arithmetic operators:-
• Arithmetic operators are:-

 Addition :: +
 Subtraction :: –
 Division :: /
 Multiplication :: *
 Modulus :: %

Suppose A and B are two integer variables, whose values are 10 and 5
respectively.

20
Precedence of arithmetic operators:-

• High priority *
\
%

Low priority +-

• a+b*c–d/e
• a*–b+d%e–f a + (b * c) – (d / e)
a * (– b) + (d % e) – f

• a–b+c+d
(((a – b) + c) + d)

• x*y*z
((x * y) * z)

• a+b+c*d*e
(a + b) + ((c * d) * e) 21
Rules for evaluating expression:-

• First, parenthesized sub expression from left to right are evaluated.

• If parenthesized are nested, the evaluation begins with the innermost sub
expression.

• The precedence rule is applied in determining the order of application of


operators in evaluating sub expression

• The associativity rule is applied when two or more operators of the


same precedence level appear in a sub expression.

• Arithmetic expressions are evaluated from left to right using rules of precedence.

• When parenthesis are used the expression with in parenthesis assume highest
priority. 22
• A=9-12/3+3*2-1
A=10

• 10-3%8+6/4
8

• z=x+y*z/4%2–1
what is the order of evaluation of operators.
*/%+-=

23
Relational operators:-
• Used to compare two quantities.
< is less than
> is greater than
<= is less than or equal to
>= is greater than or equal to
== is equal to
!= is not equal to

• The result of comparison is “true” or “false”. The value 0 is considered as


“false”, and any non-zero value as “true”.

• Generally relational operators are used in the decision statements like if and while.

• When arithmetic expressions are used on either side of a relational operator, the
arithmetic expressions will be evaluated first and then the results compared. 24
Expression Interpretation Value (i=1,j=2, and k=3):-

• i<j true 1
• (1 + j) >= k true 1
• (j + k) > (i + 5) false 0
• k!= 3 false 0
• j == 2 true 1

• 10 > 20 is false
• 25 < 35.5 is true
• 12 > (7 + 5) is false
a + b > c – d is the same as (a+b) > (c+d)

25
Logical operators:-
• Used to combine two or more relational expressions.
&& Logical AND Result is true if both the operands are true.
|| Logical OR Result is true if at least one of the operands are true.
! Logical NOT

• The result of comparison is “1” or “0”.

• Used when user want to test more than one relational expression.

• Example: (i=7, f=5.5, and c=10):-


Expression Interpretation Value
(i >= 6) && (c == 6 ) false 0
(i >= 6) || (c == 10) true 1
(f < 11) && (i > 100) false 0
26
Assignment operators:-
• =
• +=
• -=
• *=
• /=
• %=
• a += b a=a+b
• a -= b a=a-b
• a *= b a=a*b
• a /= b a=a/b
• a %= b a=a%b

• x, y and z are integer variables which have been assigned the values 2, 3 and 4,
respectively. The expression. x *= -2 * (y + z) / 3
x = x * (-2 * (y + z) / 3)
Answer=-8 27
Operator associativity and precedence:-

28
(1) Increment (++) Operator :

• The increment operator causes its operand to be increased by 1.


Example: a++, ++count

• (++) Operator is divided into two types


I. Pre-increment operator
II. Post-increment operator

• The pre-increment operator first adds 1 to the operand and then the result is
assigned to the variable on left.

• The post-increment operator first assigns the value to the variable on left and
then increments the operand.
• If x and y are the two integer variables and the value of x is 10 then find out
the values of (x++), (++x), (y=x++), and (y=++x)? 29
(2) Decrement (--) Operator :

• The decrement operator causes its operand to be decreased by 1.


Example: a--, --count

• (--) Operator is divided into two types


I. Pre-decrement operator
II. Post-decrement operator

• The pre-decrement operator first subtract 1 to the operand and then the result
is assigned to the variable on left.

• The post-decrement operator first assigns the value to the variable on left and
then decrements the operand.

• If x and y are the two integer variables and the value of x is 10 then find out
the values of (x--), (--x), (y=x--), and (y=--x)? 30
Question:
Initial values :: a = 10; b = 20
(1) a=? X=?

x(2)= 50
x =+50 +
++a; a=? X=?
a--;
(3) x = 100 + -- b=? X=?
b;
(4) x = 100 + b+ b=? X=?
+;
(5) x = a++ + -- a=? b=? X=?
b;
(6) x = a-- + + a=? b=? X=?
+b;
(7) x = --a + b+ a=? b=? X=?
+;
(8) x = ++a + b+ a=? b=? X=?
31
+;
Answers:
Initial values :: a = 10; b = 20
(1) a=11 X=61

x(2)= 50
x =+50 +
++a; a=9 X=60
a--;
(3) x = 100 + -- b=19 X=119
b;
(4) x = 100 + b+ b=21 X=120
+;
(5) x = a++ + -- a=11 b=19 X=29
b;
(6) x = a-- + + a=9 b=21 X=31
+b;
(7) x = --a + b+ a=9 b=21 X=29
+;
(8) x = ++a + b+ a=11 b=21 X=31
32
+;
Question: Question:

#include <stdio.h> #include <stdio.h>


int main() int main()
{ {
int a=10; int a=10;
printf("%d \n", a); printf("%d \n", a);
printf("%d \n", printf("%d \n",
a++); a--);
printf("%d \n", printf("%d \n",
a); a);
printf("%d \n", + printf("%d \n", --
+a); a);
printf("%d \n", printf("%d \n",
a); return 0;} a); return 0;}
33
Answer: Answer:

#include <stdio.h> #include <stdio.h>


int main() int main()
{ {
int a=10; int a=10;
printf("%d \n", a); 10 printf("%d \n", a); 10
printf("%d \n", a++); 10 printf("%d \n", a--); 10
printf("%d \n", a); 11 printf("%d \n", a); 9
printf("%d \n", ++a); 12 printf("%d \n", --a); 8
printf("%d \n", a); 12 printf("%d \n", a); 8
return 0;} return 0;}

34
(3) Conditional operator:-
• Conditional operations can be carried out with the conditional operator (? :).

• An expression that makes use of the conditional operator is called a


conditional expression.

• A conditional expression is written in the form


expression 1? expression 2 : expression 3

• expression1 is evaluated first


 If expression1 is true (i.e., if its value is nonzero), then
expression2 is evaluated and this becomes the value of the
conditional expression.
 if expression1 is false (i.e., if its value is zero), then
expression3 is evaluated and this becomes the value of the
conditional expression.
35
Question:-

#include <stdio.h>
int main()
{
int x=1, y ;
y=(x
==1 ? 2 :
0);
printf("x value is %d\n", x);
printf("y value is %d", y);
}

36
Decision Making:-

• Allow different sets of instructions to be executed depending on the outcome of a


logical test.

• Whether TRUE or FALSE. This is called branching.

• How do we specify the conditions?


 Using relational operators.
Four relation operators: <, <=, >, >=
Two equality operators: ==, !=
 Using logical operators / connectives.
Two logical connectives:

&&, | | Unary negation operator: 37


Examples:-
count <= 100 (math+phys+chem)/3 >= 60
(gender==’M’) && (age>=21) (marks>=80) && (marks<90)
(balance>5000) || (no_of_trans>25) !(grade=‘A’)

• The conditions evaluate to Zero--Indicates FALSE.


• The conditions evaluate to Non-zero--Indicates TRUE. Typically the condition TRUE
is represented by the value ‘1’.

• Branching statements are:-


 If statement
 If-else statement
 If-else-if statement
 Switch statement
38
(1) Branching: The “if” Statement:-

• “if” Contains an expression that can be TRUE or FALSE.

• Single-entry / single-exit structure.

• General syntax:
if(test expression/condition)
{
Statement 1;
Statement 2;
…………….
Statement n
}
Statement
x;
39
• If there is a single statement in the
Ex-1:
if (grade>=60)
{
printf(“Passed \n”);
printf(“Good luck\n”);
}
Ex-2:

if( x <0)
printf("%f”, x ) ;

40
(2) Branching: The “if-else” Statement:-
• Allows us to specify two alternate blocks of statements, one of which is executed
depending on the outcome of the condition.
• a single-entry / single-exit structure.
• General syntax:
if(test expression/condition)
{
Statement 1;
Statement n;
}
else
{ Statement 1;
Statement n;

Statement x;
41
(3) Branching: “Nesting of if-else” Structures:-
if(test expression/condition)
{
Statement block 1;
}
else if(test expression/condition)
{
Statement block 1;
}
else if(test expression/condition)
{
Statement block 1;
}
else
{
Statement block 1;
}
Statement x;
42
THE switch STATEMENT:

• The switch statement causes a particular group of statements to be chosen


from several available groups.

• The selection is based upon the current value of an expression


which is included within the switch statement.

• Syntax: switch (expression) statement


where expression results in an integer value
• Note that expression may also be of type char, since individual characters have
equivalent integer values.

43
• The keyword break can be included at the end of each case statement.

• In general, whenever a break statement is encountered in C, it interrupts


the normal flow of control. In the switch statement, it causes an exit from
the switch.

• The default clause is optional.

• In a switch statement, the “case value” must be of “char” and “int” type.

• The values in the case must be unique.

44
45
46
Advantages of switch case:-
• Easy to debug (bugs means errors).

• Easy to read and understand.

• Easy maintenance as compared to if-else statement.

• Switch case statement can also be nested like if-else.

• Execute faster than if-else statements

47
48
(1) The expression used in switch must be integral type.

49
(2) All the statements following a matching case execute
until a break statement is reached.

50
(3) The default block can be placed
anywhere.

51
(4) The statements written above cases are never executed.

Output:- CAT-01 EXAM


52
(5) Two case labels cannot have same
value.

Output:- Complier error: Duplicate case value


53
Exercise:-

Q1. Write a program to enter a number from 1-7 and display the
corresponding day of the week using switch case statement.

Q2. Write a C program to check positive negative or zero using switch


case statement.

54
Loops (Repeated Execution):-

• Group of instructions that are executed repeatedly while some condition remains
true with the help of control variable.

name of a control variable (or loop counter).


initial value of the control variable.
condition that tests for the final value of the control variable (i.e.,
whether looping should continue).
increment ( or decrement) by which the control variable is
modified each time through the loop.
• Example:
int count;
for( count=1; count<=100; count++) printf("%d",cont);

55
(1) LOOPING: THE while STATEMENT:-

• The “while” statement is used to carry out looping operations, in which a group
of statements is executed repeatedly, as long as some condition remains satisfied.

• Example:
int digit = 0;
while ( digit <=
9)
{
digit=digi
t+1;
56
printf
#include <stdio.h>
int main ()
{
int N,
count,
sum;
scanf("%d", &N) ;
sum = 0; count =
1; while (count <=
N)
{
sum = sum + count;
count = count + 1;
}
printf("Sum=%d\n", sum);
return 0;
} 57
(2)LOOPING: THE for STATEMENT:-

•The “for” statement is the most commonly used looping structure in

C. General syntax:

for (expression1; expression2; expression3)


statement-to-repeat;

for (expression1; expression2; expression3)


{
statement_1;
:
statement_N;
}
58
How it works?:-
• “expression1” is used to initialize some variable (called index) that controls the
looping action (i.e., expression 1 is an assignment expression).

• “expression2” represents a condition that must be true for the loop to continue
(i.e., expression 2 is a logical expression).

• “expression3” is used to alter the value of the index initially assigned


by “expression1” (i.e., expression 3 is a unary expression or an assignment
expression).

59
When the for statement is executed:-

• expression 2 is evaluated and tested at the beginning of each pass through the
loop.

• expression 3 is evaluated at the end of each pass.

for statement is equivalent using while:-


expression 1;
while (expression 2)
{
statement
expression 3;
}

60
• From a syntactic standpoint all three expressions need not be included in the for
statement. Though the semicolons must be present.

• The first and third expressions may be omitted if other means are provided for
initializing the index and or altering the index.

• If the second expression is omitted, however, it will be assumed to have a


permanent value of 1. Thus, the loop will continue indefinitely unless it is
terminated by some other means such as a break or a return statement

• In the for loop, arithmetic expressions are used for the Initialization, loop-
continuation, and increment (or) decrement.

Ex1: for (k=x; k <= 4*x*y; k +=


Ex-2: y/x)
for (digit=9; digit>=0; digit--)
• If loop continuation condition initially false, body of for structure not performed.
Control proceeds with statement after for structure. 61
A common mistake (; at the
end):- int fact = 1, i;
for ( i=1; i<=5; i+
+) fact = fact * i;
printf (“%d \n”, Output = 120
fact);
int fact = 1, i;
for ( i=1; i<=5; i+
+); fact = fact * i;
printf (“%d \n”, Output = 6
fact);
• Specifying “Infinite Loop”:-
while (1) for (; ;)
{ {
Statements Statements
}
}
62
Q. The output of below program?

#include <stdio.h>
int main()
{
int i=0,x=0;
for(i=1;i<10;i*=2)
{
x=x+1;
printf("%
d \n",x);
}
printf("%d",x);
return 0;
}
Answer:-
63
Q. The output of below program?

#include <stdio.h>
int main()
{
int i=0,x=0;
for(i=1;i<10;i*=2);
{
x=x+1;
printf("%
d \n",x);
}
printf("%d",x);
return 0;
}
Answer:-
64
Q. The output of below program?
#include <stdio.h>
int main()
{
int i = 0, x = 0;
while (i < 20)
{
if (i %
5 ==
0)
{
x

+
=

i
Answer:- ; 65
printf("%d", x);
return 0;
}
Nested loops:
• It consist of an outer loop with one or more inner loops.
• e.g.,
for (i=1;i<=100;i++)
{
for(j=1;j<=50;j++)
{

Inner loop
} }
• The above loop will run for 100*50 iterations.
66
(1) Print the following pattern:-

***** #include <stdio.h>


***** int main()
***** {
***** int i,j;
***** for(i=1;i<=5;i++)
{
printf("\n");
for(j=1;j<=5;j++)
{
printf("*
");
}
}
return 0;
}
67
(2) Print the following pattern:-

* #include <stdio.h>
** int main()
*** {
**** int i,j;
***** for(i=1;i<=5;i++)
{
printf("\n");
for(j=1;j<=i;j++)
{
printf("
*");
}
}
return 0;
}
68
(3) Print the following pattern:-

1 #include <stdio.h>
12 int main()
123 {
1234 int i,j;
12345 for(i=1;i<=5;i++)
{
printf("\n");
for(j=1;j<=i;j++)
{
printf(“
%d”, j);
}
}
return 0;
}
69
(4) Print the following pattern:-

1 #include <stdio.h>
22 int main()
333 {
4444 int i,j;
55555 for(i=1;i<=5;i++)
{
printf("\n");
for(j=1;j<=i;j++)
{

;
}
}
return 0;
}
70
(5) Print the following pattern:-

#include <stdio.h>
0 int main()
1 2 {
3 4 5 int i,j, val=0;
for(i=1;i<=5;i++)
{
printf("\n");
for(j=1;j<=i;j++)
{
printf("%d \t", val);
val++;
}
}
return 0;
}
71
(6) Print the following pattern:-

#include <stdio.h>
0 int main()
0 1 {
0 1 2

return 0;
}
72
(7) Print the following pattern:- #include <stdio.h>
int main()
1 {
12 int i,j,k;
123 for(i=5;i>0;i--)
1234 {
12345 f
o
r
(
j
=
1
;
j
<
=
i 73
Exercise:-

(1)
****
*
****
***
**
*

(2)

** *
*****
*******
******** 74
(1)
#include <stdio.h>
int main()
{
int i, j; ****
for (i = 5; i >= 1; i--) *
{ ****
for (j = 1; j <= i; j++) ***
{ **
printf("* ");
}
printf("\n");

}
return 0;
}
75
(2)
#include <stdio.h>
int main() {
int i, j,k;
for (i = 1; i <= 5; ++i)
{
for (j = 1; j <= 5 - i; ++j)
{ *
printf(" "); ***
} *****
for (k = 0; k != 2 * i - 1; ++k) *******
{ ********
printf("* "); *
}
printf("\n");
}
return 0;
} 76

You might also like