0% found this document useful (0 votes)
44 views80 pages

C Programming Notes 18 September Unit1+Unit 2

Nothing

Uploaded by

hsisodia770
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)
44 views80 pages

C Programming Notes 18 September Unit1+Unit 2

Nothing

Uploaded by

hsisodia770
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/ 80

UNIT 1

FUNDAMENTALS OF C PROGRAMMING
C Language Introduction

• C is a procedural programming language initially developed by

Dennis Ritchie in the year 1972 at Bell Laboratories of AT&T

Labs. It was mainly developed as a system programming

language 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

• These features make the C language suitable for system


programming like an operating system or compiler
development.
Structure of the C program

• By structure, it is meant that any program can be written in this

structure only. Writing a C program in any other structure will

hence lead to a Compilation Error. The structure of a C program

is as follows:
Application of C

• Operating systems: C is widely used for developing operating systems


such as Unix, Linux, and Windows.
• Embedded systems: C is a popular language for developing embedded
systems such as microcontrollers, microprocessors, and other electronic
devices.
• System software: C is used for developing system software such as
device drivers, compilers, and assemblers.
• Networking: C is widely used for developing networking applications
such as web servers, network protocols, and network drivers.
• Database systems: C is used for developing database systems such as
Oracle, MySQL, and PostgreSQL.
• Gaming: C is often used for developing computer games due to its ability
to handle low-level hardware interactions.
Compilation process
Hello world program
#include <stdio.h>
int main() {
// printf() displays the string inside quotation
printf("Hello, World!");
return 0;
}

Output: Hello, World!"


How "Hello, World!" program works?
1. The #include is a preprocessor command that tells the compiler to
include the contents of stdio.h (standard input and output) file in
the program.
2. The stdio.h file contains functions such as scanf() and printf() to
take input and display output respectively.
3. If you use the printf() function without writing #include <stdio.h>,
the program will not compile.
4. The execution of a C program starts from the main() function.
5. printf() is a library function to send formatted output to the screen.
In this program, printf() displays Hello, World! text on the screen.
6. The return 0; statement is the "Exit status" of the program. In
simple terms, the program ends with this statement.
How to run hello world program in GCC
• Save the program file by name “hello.c”
• Compile the code using following command
gcc hello.c
This command will compile the code and if there are no errors it will
create a file a.out in the same folder.
./a.out
This command will run the code and perform the task inside the hello.c
program
Output: Hello, World!"
Format Specifiers in C

• The format specifier in C is used to tell the compiler about the


type of data to be printed or scanned in input and output
operations. They always start with a % symbol and are used in
the formatted string in functions like printf(), scanf, sprintf(),
etc.
printf() and scanf() in C

• The printf() and scanf() functions are used for input and output in C
language. Both functions are inbuilt library functions, defined in
stdio.h (header file).
printf() function

The printf() function is used for output. It prints the given statement to
the console.
The syntax of printf() function is given below:

printf("format string",argument_list);
scanf() function

• The scanf() function is used for input. It reads the input data from the

console.

• scanf("format string",argument_list);
#include<stdio.h>
int main(){
int number;
printf("enter a number:");
scanf("%d",&number);
printf("cube of number is:%d ",number*number*number);
return 0;
}
Constants in C

• A constant is a value or variable that can't be changed in the program,

for example: 10, 20, 'a', 3.4, "c programming" etc.

• There are different types of constants in C programming.


List of Constants in C
Constant Example

Decimal Constant 10, 20, 450 etc.

Real or Floating-point Constant 10.3, 20.2, 450.6 etc.

Octal Constant 021, 033, 046 etc.

Hexadecimal Constant 0x2a, 0x7b, 0xaa etc.

Character Constant 'a', 'b', 'x' etc.

String Constant "c", "c program"


C const keyword

• The const keyword is used to define constant in C programming.

const float PI=3.14;

Example:
#include<stdio.h>
int main(){
const float PI=3.14;
printf("The value of PI is: %f",PI);
return 0;
}
C #define

• The #define preprocessor directive is used to define constant or micro


substitution. It can use any basic data type.
• Syntax:
#define token value
Example:
#include <stdio.h>
#define PI 3.14
main() {
printf("%f",PI);
}
Operators in C
• Operators can be defined as the symbols that help us to
perform specific mathematical, relational, bitwise, conditional,
or logical computations on operands.

• C=a+b

• Here, ‘+’ is the operator known as the addition operator, and ‘a’
and ‘b’ are operands. The addition operator tells the compiler
to add both of the operands ‘a’ and ‘b’.
Unary Operators: ++, --
• Operators that operate or work with a single operand are unary
operators. For example: Increment(++) and Decrement(- -) Operators
#include<stdio.h>
int main()
{
int a=9;
a++;
printf("%d",a);
}
Output: 10
Binary Operators: +, -, /, *, %

• Operators that operate or work with two operands are binary operators. For
example: Addition(+), Subtraction(-), multiplication(*), Division(/) operators

#include<stdio.h>
int main()
{
int a=9,b=8,sum;
sum=a+b;
printf("%d",sum);
}
Output: 17
Relational Operators in C: ==, >= , <=

• These are used for the comparison of the values of two operands.
For example, checking if one operand is equal to the other operand
or not, whether an operand is greater than the other operand or not,
etc. Some of the relational operators are ==, >= , <=
#include<stdio.h>
int main()
{
int a=9,b=8;
printf("%d",a>b);
}
output: 1
Logical Operator in C: && , II ,!
• Logical Operators are used to combining two or more
conditions/constraints or to complement the evaluation of the
original condition in consideration. The result of the operation of a
logical operator is a Boolean value either true or false. 0 or 1
#include<stdio.h>
int main()
{
int a=9,b=8;
printf("%d",a!=b);
}
Output: 1
• #include<stdio.h>
• int main()
•{
• int a=9,b=8,c=7;
• printf("%d",(a>b)&&(b<c));
•}
• Output: 0
Bitwise Operators in C

• The Bitwise operators are used to perform bit-level operations on


the operands. The operators are first converted to bit-level and then
the calculation is performed on the operands.
#include<stdio.h>
int main()
{
int a=2,b=8;
printf("%d",a & b);
}
Output: 0
1.The & (bitwise AND) in C or C++ takes two numbers as operands
and does AND on every bit of two numbers. The result of AND is 1
only if both bits are 1.
2.The | (bitwise OR) in C or C++ takes two numbers as operands and
does OR on every bit of two numbers. The result of OR is 1 if any of
the two bits is 1.
3.The ^ (bitwise XOR) in C or C++ takes two numbers as operands
and does XOR on every bit of two numbers. The result of XOR is 1 if
the two bits are different.
4.The << (left shift) in C or C++ takes two numbers, the left shifts the
bits of the first operand, and the second operand decides the
number of places to shift.
5.The >> (right shift) in C or C++ takes two numbers, right shifts the
bits of the first operand, and the second operand decides the
number of places to shift.
6.The ~ (bitwise NOT) in C or C++ takes one number and inverts all
bits of it.
X Y X&Y X|Y X^Y

0 0 0 0 0

0 1 0 1 1

1 0 0 1 1

1 1 1 1 0
#include <stdio.h>
int main()
{ // a = 5(00000101), b = 9(00001001)
unsigned int a = 5, b = 9;
// The result is 00000001
printf("a&b = %d\n", a & b);
// The result is 00001101
printf("a|b = %d\n", a | b);
return 0;
}
Output: a^b = 12
a|b = 13
Ternary Operator

A Ternary Operator has the following form,

exp1 ? exp2 : exp3

The expression exp1 will be evaluated always. Execution of exp2 and


exp3 depends on the outcome of exp1. If the outcome of exp1 is non
zero then exp2 will be evaluated, otherwise, exp3 will be evaluated.
#include <stdio.h>
int main()
{
// variable declaration
int n1 = 5, n2 = 10, max;
// Largest among n1 and n2
max = (n1 > n2) ? n1 : n2;
// Print the largest number
printf("Largest number between %d and %d is %d. ",n1, n2,
max);
return 0;
}
Assignment Operators in C

• Assignment operators are used to assign value to a variable.


The left side operand of the assignment operator is a variable
and the right side operand of the assignment operator is a
value. The value on the right side must be of the same data
type as the variable on the left side otherwise the compiler will
raise an error.
#include <stdio.h>
int main()
{
int a=5,b=11;
a+=b;
printf("%d",a);
}
Type Conversion

• Type conversion in C is the process of converting one data type


to another. The type conversion is only performed to those
data types where conversion is possible. Type conversion is
performed by a compiler. In type conversion, the destination
data type can’t be smaller than the source data type.
1. Implicit Type Conversion

• Also known as ‘automatic type conversion’.


• A. Done by the compiler on its own, without any external
trigger from the user.
• B. Generally takes place when in an expression more than one
data type is present. In such conditions type conversion (type
promotion) takes place to avoid loss of data.
• All the data types of the variables are upgraded to the data type of
the variable with the largest data type.

bool -> char -> short int -> int ->unsigned int -> long -> unsigned ->
long long -> float -> double -> long double
#include <stdio.h>
int main()
{
int x = 10; // integer x
char y = 'a'; // ASCII value of 'a' is 97
x = x + y;
float z = x + 1.0;
printf("x = %d, z = %f", x, z);
return 0;
}
2. Explicit Type Conversion
• This process is also called type casting and it is user-defined. Here the
user can typecast the result to make it of a particular data type. The
syntax in C Programming:

• (type) expression
• Type indicated the data type to which the final result is converted.
#include<stdio.h>
int main()
{
double x = 1.2;
// Explicit conversion from double to int
int sum = (int)x + 1;
printf("sum = %d", sum);
return 0;
}
#include <stdio.h>

int main() {
float a = 1.5;
int b = (int)a;
printf("a = %f\n", a);
printf("b = %d\n", b);
return 0;
}
UNIT 2
BRANCHING AND CONTROL STATEMENT

• The Branching Statements in C are categorized as follows.


• Conditional Branching Statements in C
• if Statement
• else Statement
• else-if Statement
• switch Statement
• Unconditional Branching Statements in C
• goto Statement
• break Statement
• continue Statement
Conditional Branching Statements in C

• Conditional Branching Statements in C are used to execute the


specific blocks of code on the basis of some condition (as per
requirements). These type of Branching statements in C
enables the programmers to execute the code only and only
certain statements are met.
if Statement

This statement is used to execute the specific block of code if a


certain condition is evaluated to be true.
Here is the syntax of the if statement in C.

if (condition) {
//code to be executed if condition specified evaluates is
true
}
If the condition is evaluated to be true, the code within curly braces will be executed but if
the condition is false, the code in braces will be skipped.
EXAMPLE
include <stdio.h>
int main() {
int x = 10;
if (x > 5) {
printf("x is greater than 5");
}
return 0;
}
else Statement

The else Statement in C is considered just the opposite of the if


statement. This statement is used to execute the code if the condition
specified in the if statement evaluates to false.
Syntax of else Statement in C

if (condition) {
// statements
} else{
// code executed if condition is false
}
#include <stdio.h>
int main()
{
int x = 10;
if (x < 5)
{
printf("x is less than 5\n");
}
else
{
printf("x is greater than or equal to 5\n");
}
return 0;
}
else if Statement
The else if statement in C is used when we want to check
multiple conditions. It follows an "if" statement and is executed if
the previous "if" statement’s condition is false.
Syntax of else-if Statement in C

if (condition1) {
// code to be executed if condition1 is true
}
else if (condition2) {
// code to be executed if condition2 is true and condition1 is false
}
• The "else if" statement can be repeated multiple times to check
for multiple conditions. If all conditions are false, the code
within the final "else" block will be executed.
#include <stdio.h>
int main() {
int x = 10;
if (x > 15) {
printf("x is greater than 15");
}
else if (x > 5) {
printf("x is greater than 5 but less than or equal to 15");
}
else {
printf("x is less than or equal to 5");
} Output
x is greater than 5 but less than or equal to 15

return 0;
}
switch Statement
• The switch statement in C is used when we have multiple
conditions to check. It is often used as an alternative to multiple
"if" and "else if" statements.
Syntax of switch Statement in C

switch (expression) {
case value1:
// code to be executed if expression equals value1
break;
case value2:
// code to be executed if expression equals value2
break;
default:
// code to be executed if none of the cases match
break;
}
Unconditional Branching Statements in C

• Unconditional branching statements are used in C to change


the normal flow of program execution. These statements allow
programmers to jump to a specific point in their code
regardless of any condition.
break Statement

The break Statement is one of the unconditional Branching Statements


in C which is generally used in the loops for exiting the loop before the
completion of the loop.

Syntax of break Statement in C


Here is the syntax for the "break" statement in C.

break;
Output
case 3:
#include <stdio.h> printf("x is 3");
int main() { break;
int x = 2; default:
switch (x) { printf("x is not 1, 2, or 3");
case 1: break;
printf("x is 1"); }
break; return 0;
case 2: } Output
printf("x is 2");
break; x is 2
goto Statement

The "goto" statement is an unconditional branching statement that allows


programmers to jump to a specific labeled statement within their code.

Syntax of goto Statement in C

goto label;

...

label:
// code to be executed
#include <stdio.h>
int main() {
int x = 0;
start:
x++;
if (x < 10) {
goto start;
}
printf("x is %d", x);
Output
return 0; x is 10

}
continue Statement

The continue statement is used in C programming language to


skip the current iteration of a loop and move to the next iteration.
This statement is typically used in loops like for or while.

Syntax of continue Statement in C


continue Statement in C has following syntax.

continue;
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // skip even numbers
}
printf("%d ", i);
}
return 0;
} Output
13579
• Ques 1. Can the "switch" statement be nested in C?
Ans. No, we cannot nest the switch statement in C. This means that
a switch statement in C cannot contain another switch statement
inside it.
• Ques 2. How many "case" statements can a "switch" statement have
in C?
Ans. A "switch" statement in C can have any number of "case"
statements.
• Ques 3. What happens if none of the "case" statements match in a
"switch" statement in C?
Ans. If none of the "case" statements match in a "switch" statement
in C, the code within the "default" block is executed.
• Ques 4. Can the "break" statement be used outside of loops and
switch statements in C?
Ans. No, the "break" statement can only be used within loops and
switch statements in C.
• Ques 5. Can the "goto" statement be used to jump to a label defined
in another function in C?
Ans. No, the "goto" statement can only jump to a label defined within
the same function in C.
• Ques 4. Can the “continue" statement be used outside of loops and
switch statements in C?
Ans. No , The continue statement can only be used on loops and not
on switches.
Leap year program

• A leap year is exactly divisible by 4 except for century years (years

ending with 00). The century year is a leap year only if it is perfectly

divisible by 400.
#include <stdio.h>
int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
if (year % 400 == 0) {
printf("%d is a leap year.", year);
else if (year % 4 == 0) {
}
printf("%d is a leap year.", year);
else if (year % 100 == 0) {
}
printf("%d is not a leap year.",
year); else {
} printf("%d is not a leap year.",
year);
}
return 0;
}
#include<stdio.h>
Int main() {
int year;
printf("Enter a year: ");
scanf("%d", &year);
if(((year%4==0) && ((year%400==0) || (year%100!==0))
{
printf("%d is a leap year", &year);
} else {
printf("%d is not a leap year", &year);
} retirn 0;
}
#include <stdio.h>
int main() Largest of three numbers using if else
{
int A, B, C;
printf("Enter the numbers A, B and C: ");
scanf("%d %d %d", &A, &B, &C);
if (A >= B && A >= C)
printf("%d is the largest number.", A);
else if (B >= A && B >= C)
printf("%d is the largest number.", B);
else
(C >= A && C >= B)
printf("%d is the largest number.", C);
return 0;
}
Largest of three numbers using ternary operator
#include <stdio.h>
int main()
{
int n1 = 5, n2 = 10, n3 = 15, max;
max = (n1 > n2) ? (n1 > n3 ? n1 : n3) : (n2 > n3 ? n2 : n3);
printf("Largest number among %d, %d and %d is %d.",n1, n2, n3, max);
return 0;
}
Looping or iterating Statements:
Loops are produced by iteration statements in a program.
Iteration is the process of repeatedly running the same piece of
code until a predetermined condition is met. The same
instructions are carried out by iteration statements up until a
termination condition is satisfied.
statements loop in C is as follows:
1. while loop
2. for loop
3. do-while loop
While Loop :

#include<stdio.h>
int main()
{
int a=1;
while(a<=4)
{
printf("%d", a);
a++;
}
return 0;
}
#include <stdio.h>
int main()
{
int i = 1;
while(i <= 5)
{
printf("%d ", i);
i = i + 1;
}
return 0;
}
#include <stdio.h>
int main() {
Reverse of a
int n, reverse = 0, remainder; Number
printf("Enter an integer: ");
scanf("%d", &n);
while (n != 0) {
remainder = n % 10;
reverse = reverse * 10 + remainder;
n =n/ 10;
}
printf("Reversed number = %d", reverse);
return 0;
}
do...while
A do...while loop is similar to a while loop, except the fact that it is
guaranteed to execute at least one time.

Syntax
The syntax of a do...while loop in C programming language is −

do {
statement(s);
} while(condition);
#include <stdio.h>
int main () {
/* local variable definition */
int a = 10;
/* do loop execution */
do {
printf("value of a: %d\n", a);
a = a + 1;
}while( a < 10 );
return 0;
}
For Loop

The for loop is a control flow statement that allows you to execute a
block of code repeatedly based on a specified condition.

Syntax of For Loop


The basic syntax of a for loop is as follows:

for (initialization; condition; update) {


// statements
}
• The for Loop consists of the following main components.
• initialization: This is the first component, which is used for the
initialization of the counter variable which is used to control the
loop. This statement is only executed once.
• condition: It is a boolean expression, which is evaluated before
each iteration of the loop. If the boolean expression is true, the
loop body is executed.
• update: This statement is executed after each iteration of the
loop. Thi statement updates the counter variable or other values
taht are present in the loop.
Print numbers from 1 to 10
// Print numbers from 1 to 10
#include <stdio.h>

int main() {
int i;

for (i = 1; i < 11; ++i)


{
printf("%d ", i);
}
return 0;
}
#include <stdio.h>
int main()
{ // Program to
int num, count, sum = 0; calculate the
printf("Enter a positive integer: "); sum of first n
scanf("%d", &num); natural numbers
for(count = 1; count <= num; ++count)
{
sum += count;
}
printf("Sum = %d", sum);
return 0;
}

You might also like