0% found this document useful (0 votes)
3 views83 pages

C - 1 Unit

C is a general-purpose programming language developed by Dennis Ritchie in 1972, primarily associated with UNIX. It features low-level memory access, fast execution, and a clean syntax, making it foundational for many modern programming languages. The document outlines the structure of a C program, variable declarations, data types, operators, and examples of basic C syntax.
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)
3 views83 pages

C - 1 Unit

C is a general-purpose programming language developed by Dennis Ritchie in 1972, primarily associated with UNIX. It features low-level memory access, fast execution, and a clean syntax, making it foundational for many modern programming languages. The document outlines the structure of a C program, variable declarations, data types, operators, and examples of basic C syntax.
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/ 83

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.

• C follows a top-down approach and much importance is given to flow of program.


3
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;
}

2
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.) 3
• 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

4
5
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;

6
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

7
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. 8
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
9
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);

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

11
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.

2
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.

3
Precedence of arithmetic operators:-

• High priority * \ %

Low priority +-

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

• a*–b+d%e–f
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) 4
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. 5
• 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.
*/%+-=

6
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. 7
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)

8
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
9
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 10
Operator associativity and precedence:-

11
(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)? 2
(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)? 3
Question:
Initial values :: a = 10; b = 20
(1) x = 50 + ++a; a=? X=?

(2) x = 50 + a--; a=? X=?

(3) x = 100 + --b; b=? X=?

(4) x = 100 + b++; b=? X=?

(5) x = a++ + --b; a=? b=? X=?

(6) x = a-- + ++b; a=? b=? X=?

(7) x = --a + b++; a=? b=? X=?

(8) x = ++a + b++; a=? b=? X=?


4
Answers:
Initial values :: a = 10; b = 20
(1) x = 50 + ++a; a=11 X=61

(2) x = 50 + a--; a=9 X=60

(3) x = 100 + --b; b=19 X=119

(4) x = 100 + b++; b=21 X=120

(5) x = a++ + --b; a=11 b=19 X=29

(6) x = a-- + ++b; a=9 b=21 X=31

(7) x = --a + b++; a=9 b=21 X=29

(8) x = ++a + b++; a=11 b=21 X=31


5
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", a++); printf("%d \n", a--);
printf("%d \n", a); printf("%d \n", a);
printf("%d \n", ++a); printf("%d \n", --a);
printf("%d \n", a); printf("%d \n", a);
return 0;} return 0;}

6
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;}

7
(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.

8
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);
}

9
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: !
2
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
3
(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;

• If there is a single statement in the block, the braces can be omitted.


4
Ex-1:
if (grade>=60)
{
printf(“Passed \n”);
printf(“Good luck\n”);
}
Ex-2:

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

5
#include <stdio.h>
main()
{
Int a,b,c;
scanf (“%d %d %d”, &a, &b, &c);
if ((a>=b) && (a>=c))
printf (“\n Display: %d”, a);
if ((b>=a) && (b>=c))
printf (“\n Display : %d”, b);
if ((c>=a) && (c>=b))
printf (“\n Display : %d”, c);
}

Guess the program:- ?


6
(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; 7
if ( grade >= 60 )
printf ("Passed\n");
else
printf ("Failed\n");

• If a block contains a single statement, the braces can be deleted.

• If the expression has a nonzero value (i.e., if expression is true), then statement1 will
be executed. Otherwise (i.e., if expression is false), statement 2will be executed.

8
9
(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;
10
11
Q. Write a program to enter the marks of a student in four subjects. Then,calculate
the total, average and display the grade obtain by the student. If the student scores
average is greater than 75 percent, then the grade is distinction. Ifaverage is 60>=
and <75, then the grade is first division. If average is 50<= and
<60, then the grade is second division. If average is 40>= and <50, then the grade
is third division, else the grade is fail.

Q. Write a program to test whether an entered number is divisible by 3 or not.

Q. Write a program to test whether an entered number is divisible by 5 and 7 or


not.

12
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.

2
• 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.

3
4
5
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

6
7
(1) The expression used in switch must be integral type.

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

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

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

Output:- CAT-01 EXAM


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

Output:- Complier error: Duplicate case value


12
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.

13
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);
2
(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=digit+1;
printf ("%d \n", digit);
} 3
#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;
}

Guess the program:- ?


4
(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;
}

5
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).

6
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;
}

7
• 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 += y/x)


Ex-2: 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. 8
A common mistake (; at the end):-
int fact = 1, i;
for ( i=1; i<=5; i++)
fact = fact * i;
printf (“%d \n”, fact); Output = 120

int fact = 1, i;
for ( i=1; i<=5; i++);
fact = fact * i;
printf (“%d \n”, fact); Output = 6

• Specifying “Infinite Loop”:-


while (1) for (; ;)
{ {
Statements Statements
}
}
9
#include <stdio.h>
void main()
{
int digit=0 ;
for(; digit<= 9; )
printf(“% d \ n”, digit++);
}

10
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:-
11
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:-
12
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;
printf("%d \n", x);
}
i=i+1;
}

Answer:- 13
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 Outer loop
}
}

• The above loop will run for 100*50 iterations.


2
(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;
}
3
(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;
}
4
(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;
}
5
(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;
}
6
(5) Print the following pattern:-

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

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

return 0;
}
8
(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 for(j=1;j<=i-1;j++)
{
printf(" ");
}
for(k=1; k<=6-j;k++)
{
printf("%d",k);
}
printf("\n");
}
return 0;
} 9
Exercise:-

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

(2)

*
***
*****
*******
********* 10
(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;
}
11
(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("* ");

} 12
}
printf("\n");
}
return 0;

13

You might also like