Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

Programming in C Unit II

The document provides an overview of C programming, focusing on input/output statements, format specifiers, compilation and execution in Turbo C, escape sequences, decision-making, and looping structures. It details the usage of functions like printf() and scanf(), the syntax for various conditional statements, and loop control statements such as break and continue. Additionally, it includes examples and syntax for implementing these concepts in C programming.

Uploaded by

apexg7271
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Programming in C Unit II

The document provides an overview of C programming, focusing on input/output statements, format specifiers, compilation and execution in Turbo C, escape sequences, decision-making, and looping structures. It details the usage of functions like printf() and scanf(), the syntax for various conditional statements, and loop control statements such as break and continue. Additionally, it includes examples and syntax for implementing these concepts in C programming.

Uploaded by

apexg7271
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

B.

Sc: Information Technology- First Year Semester-I


B.Sc: Computer Science- First Year Semester-I

Introduction to C Programming

Unit-II Notes
1. I/O Statements:-
➢ C language has standard libraries that allow input and output in a program.
➢ The stdio.h or standard input output library in C has methods for input and output.
➢ 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).
a) scanf()
➢ The scanf() method, in C, reads the value from the console as per the type specified and store it in the
given address.
Syntax:
scanf("%X", &variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable and & is
the address operator in C, which tells the compiler to change the real value of variableOfXType, stored at
this address in the memory.
b) printf()
➢ The printf() method, in C, prints the value passed as the parameter to it, on the console screen.
Syntax:
printf("%X", variableOfXType);
where %X is the format specifier in C. It is a way to tell the compiler what type of data is in a variable
and variableOfXType is the variable to be printed.

1.1How to take input and output of basic types in C?


The basic type in C includes types like int, float, char, etc
. In order to input or output the specific type, the X in the above syntax is changed with the specific format
specifier of that type. The Syntax for input and output for these are:
• Integer:
Input: scanf("%d", &intVariable);
Output: printf("%d", intVariable);
• Float:
Input: scanf("%f", &floatVariable);
Output: printf("%f", floatVariable);
• Character:
Input: scanf("%c", &charVariable);
Output: printf("%c", charVariable);
• String:
Input: scanf("%s", stringVariable);
Output: printf("%s", stringVariable);

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

List of Format Specifiers in C:-

Format Specifier Description

%c For character type.

%d For signed integer type.

%e or %E For scientific notation of floats.

%f For float type.

%g or %G For float type with the current precision.

%i signed integer

%ld or %li Long

%lf Double

%Lf Long double

%lu Unsigned int or unsigned long

%lli or %lld Long long


Format Specifier Description

%llu Unsigned long long

%o Octal representation

%p Pointer

%s String

%u Unsigned int

%x or %X Hexadecimal representation

%n Prints nothing

%% Prints % character

3. Compilation and execution of program in Turbo C:-


Step 1: Open turbo C IDE(Integrated Development Environment), click
on “File”, and then click on “New”.
Step 2: Write the c program according to your given problem statement.

Step 3: Click on Compile menu and then on Compile option, or press the keys and press Alt + F9 to compile
the code.
Step 4: Click on Run or press Ctrl + F9 to run the code. Yes, C programs are first compiled to generate the
object code and then that object code is Run.

Step 5: Alt+F5 to view the output of the program at the output screen.

Step 6: Save the program using F2 (OR file > Save), remember the extension should be “.c”.
4. Escape Sequence Characters:-
➢ Programming languages like C have escape sequences as a standard feature.
➢ They enable the inclusion of special characters and control patterns in strings and character constants
that are difficult to represent or write directly.
➢ An escape sequence in the C programming language consists of a backslash () and a character that
stands in for a special character or control sequence.
➢ There are several escape sequence in C programming languages as mentioned in below table:-

Escape Meaning
Sequence

\a Alarm or Beep

\b Backspace

\f Form Feed

\n New Line

\r Carriage Return

\t Tab (Horizontal)

\v Vertical Tab

\\ Backslash

\' Single Quote

\" Double Quote

\? Question Mark

\nnn octal number

hexadecimal
\xhh
number
\0 Null
i) Alarm or Beep (\a):
The alarm or beep escape sequence (a) produces an audible alert or beep sound.

ii) Backspace (\b):


The cursor can be advanced by one character with the backspace escape key (b).

iii) Form Feed (\f):


The form feed escape sequence (f) is used to mimic a page break or advance to the next page.

iv) New Line (\n):


The new line escape sequence (n) is used to insert a newline character and move the cursor to the start of the
following line.
v) Carriage Return (\r):
The cursor can be moved to the start of the current line by using the carriage return escape sequence (r).

vi) Tab (Horizontal) (\t):


The tab escape sequence (t) is used to insert a horizontal tab character and shift the cursor to the following tab
stop.

vii) Vertical Tab (\v):


The vertical tab escape sequence (v) is used to simulate a vertical tab or shift the mouse to the following
vertical tab location.

viii) Backslash (\):


A backslash character is inserted using the backslash escape sequence (\).
ix) Single Quote ('):
The single quote escape sequence (') is used to insert a single quote character.

x) Double Quote ("):


A double quotation character is inserted using the double quote escape sequence (").

xi) Question Mark (?):


The question mark escape sequence (?) is used to insert a question mark character.

xii) Octal Number (\nnn):


The character's octal value can be inserted using the octal number escape sequence (nnn).
xiii) Hexadecimal Number (\xhh):
A character's hexadecimal value can be inserted using the hexadecimal number escape sequence (xhh).

xiv) Null (\0):


The null character, denoted by "0", is inserted using the null escape sequence (0).

5. Decision Making & Looping in C:-

5.1 Decision Making Statements/ Conditional Statements in C:-


➢ The conditional statements (also known as decision making structures) such as if, if else, switch, etc.
are used for decision-making purposes in C programs.
➢ They are also known as Decision-Making Statements and are used to evaluate one or more conditions
and make the decision whether to execute a set of statements or not.
➢ These decision-making statements in programming languages decide the direction of the flow of
program execution.
➢ Shown below is the general form of a typical decision-making structure found in
➢ most of the programming languages:
5.1.1 Types of Conditional Statements in C:-

Following are the decision-making statements available in C:


1. if Statement
2. if-else Statement
3. Nested if Statement
4. if-else-if Ladder
5. switch Statement
6. Conditional Operator
7. Jump Statements
• break
• continue
• goto
• return
1. if in C
➢ The if statement is the most simple decision-making statement.
➢ It is used to decide whether a certain statement or block of statements will be executed or not i.e if
a certain condition is true then a block of statements is executed otherwise not.

Syntax of if Statement:-

if(condition)
{
// Statements to execute if
// condition is true
}

Flowchart of if Statement:-

Example:

// C program to illustrate If statement


#include <stdio.h>

int main()
{
int i = 10;

if (i > 15) {
printf("10 is greater than 15");
}

printf("I am Not in if");


}
2. if-else in C:-
➢ We can use the else statement with the if statement to execute a block of code when the condition
is false.
➢ The if-else statement consists of two blocks, one for false expression and one for true expression.

Syntax:-

if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

Flowchart of if-else Statement:-

Flow Diagram of if else

Example:-

// C program to illustrate If statement


#include <stdio.h>

int main()
{
int i = 20;

if (i < 15) {

printf("i is smaller than 15");


}
else {

printf("i is greater than 15");


}
return 0;
}

3. Nested if-else in C:-


➢ A nested if in C is an if statement that is the target of another if statement.
➢ Nested if statements mean an if statement inside another if statement.
➢ Yes, C allow us to nested if statements within if statements, i.e, we can place an if statement inside
another if statement.

Syntax of Nested if-else:-

if (condition1)
{
// Executes when condition1 is true
if (condition_2)
{
// statement 1
}
else
{
// Statement 2
}
}
else {
if (condition_3)
{
// statement 3
}
else
{
// Statement 4
}
}

Flowchart of Nested if-else:-


Example:-

// C program to illustrate nested-if statement


#include <stdio.h>

int main()
{
int i = 10;

if (i == 10) {
// First if statement
if (i < 15)
printf("i is smaller than 15\n");

// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 12)
printf("i is smaller than 12 too\n");
else
printf("i is greater than 15");
}
else {
if (i == 20) {

// Nested - if statement
// Will only be executed if statement above
// is true
if (i < 22)
printf("i is smaller than 22 too\n");
else
printf("i is greater than 25");
}
}

return 0;
}

4. if-else-if Ladder in C:-


➢ The if else if statements are used when the user has to decide among multiple options.
➢ The C if statements are executed from the top down.
➢ As soon as one of the conditions controlling the if is true, the statement associated with
that if is executed, and the rest of the C else-if ladder is bypassed.
➢ If none of the conditions is true, then the final else statement will be executed.
➢ if-else-if ladder is similar to the switch statement.
Syntax of if-else-if Ladder:-

if (condition)
statement;
else if (condition)
statement;
.
.
else
statement;

Flowchart of if-else-if Ladder

Flow Diagram of if-else-if

Example:-

// C program to illustrate nested-if statement


#include <stdio.h>

int main()
{
int i = 20;

if (i == 10)
printf("i is 10");
else if (i == 15)
printf("i is 15");
else if (i == 20)
printf("i is 20");
else
printf("i is not present");
}
5. switch Statement in C:-
➢ The switch case statement is an alternative to the if else if ladder that can be used to
execute the conditional code based on the value of the variable specified in the switch
statement.
➢ The switch block consists of cases to be executed based on the value of the switch
variable.

Syntax of switch:-

switch (expression) {
case value1:
statements;
case value2:
statements;
....
....
....
default:
statements;
}

Flowchart of switch:-

Flowchart of switch in C
Example of switch Statement:-

// C Program to illustrate the use of switch statement


#include <stdio.h>

int main()
{
// variable to be used in switch statement
int var = 2;

// declaring switch cases


switch (var) {
case 1:
printf("Case 1 is executed");
break;
case 2:
printf("Case 2 is executed");
break;
default:
printf("Default Case is executed");
break;
}

return 0;
}

6. Conditional Operator in C:-


➢ The conditional operator is used to add conditional code in our program.
➢ It is similar to the if-else statement.
➢ It is also known as the ternary operator as it works on three operands.

Syntax of Conditional Operator:-

(condition) ? [true_statements] : [false_statements];

Flowchart of Conditional Operator:-

Flow Diagram of Conditional Operator


Example:-

// C Program to illustrate the use of conditional operator


#include <stdio.h>

// driver code
int main()
{

int var;
int flag = 0;

// using conditional operator to assign the value to var


// according to the value of flag
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is 0: %d\n", var);

// changing the value of flag


flag = 1;
// again assigning the value to var using same statement
var = flag == 0 ? 25 : -25;
printf("Value of var when flag is NOT 0: %d", var);

return 0;
}

5.2 Loop Control Statements / Jump Statements in C:-


These statements are used in C for the unconditional flow of control throughout the functions
in a program.
They support four types of Loop control/jump statements:

A) break:-
➢ This loop control statement is used to terminate the loop.
➢ As soon as the break statement is encountered from within a loop, the loop iterations
stop there, and control returns from the loop immediately to the first statement after the
loop.

Syntax of break:-

break;

➢ Basically, break statements are used in situations when we are not sure about the actual number of
iterations for the loop or we want to terminate the loop based on some condition.
Flowchart:-

Example of break:-

// C program to illustrate
// to show usage of break
// statement
#include <stdio.h>

void findElement(int arr[], int size, int key)


{
// loop to traverse array and search for key
for (int i = 0; i < size; i++) {
if (arr[i] == key) {
printf("Element found at position: %d",
(i + 1));
break;
}
}
}

int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6 };

// no of elements
int n = 6;

// key to be searched
int key = 3;

// Calling function to find the key


findElement(arr, n, key);

return 0;
}
B) continue :-
➢ This loop control statement is just like the break statement.
➢ The continue statement is opposite to that of the break statement, instead of terminating the loop, it
forces to execute the next iteration of the loop.
➢ As the name suggests the continue statement forces the loop to continue or execute the next
iteration.
➢ When the continue statement is executed in the loop, the code inside the loop following the
continue statement will be skipped and the next iteration of the loop will begin.

Syntax of continue:-

continue;

Flowchart of Continue:

Flow Diagram of C continue Statement

Example:-

// C program to explain the use


// of continue statement
#include <stdio.h>

int main()
{
// loop from 1 to 10
for (int i = 1; i <= 10; i++) {

// If i is equals to 6,
// continue to next iteration
// without printing
if (i == 6)
continue;

else
// otherwise print the value of i
printf("%d ", i);
}

return 0;
}
C) goto:-
➢ The goto statement in C also referred to as the unconditional jump statement can be used to jump
from one point to another within a function.

Syntax of goto:-

Syntax1 | Syntax2
----------------------------
goto label; | label:
. | .
. | .
. | .
label: | goto label;
➢ In the above syntax, the first line tells the compiler to go to or jump to the statement marked as a
label.
➢ Here, a label is a user-defined identifier that indicates the target statement.
➢ The statement immediately followed after ‘label:’ is the destination statement.
➢ The ‘label:’ can also appear before the ‘goto label;’ statement in the above syntax.

Flowchart:-

Example:-

// C program to print numbers


// from 1 to 10 using goto
// statement
#include <stdio.h>

// function to print numbers from 1 to 10


void printNumbers()
{
int n = 1;
label:
printf("%d ", n);
n++;
if (n <= 10)
goto label;
}

// Driver program to test above function


int main()
{
printNumbers();
return 0;
}

D) return:-
➢ The return in C returns the flow of the execution to the function from where it is called.
➢ This statement does not mandatorily need any conditional statements.
➢ As soon as the statement is executed, the flow of the program stops immediately and
returns the control from where it was called.
➢ The return statement may or may not return anything for a void function, but for a non-
void function, a return value must be returned.

Flowchart of return:-

Flow Diagram of return

Syntax of return:-

return [expression];

Example:-
// C code to illustrate return
// statement
#include <stdio.h>

// non-void return type


// function to calculate sum
int SUM(int a, int b)
{
int s1 = a + b;
return s1;
}

// returns void
// function to print
void Print(int s2)
{
printf("The sum is %d", s2);
return;
}

int main()
{
int num1 = 10;
int num2 = 10;
int sum_of = SUM(num1, num2);
Print(sum_of);
return 0;
}

5.3 Looping in C:-


➢ The looping can be defined as repeating the same process multiple times until a specific condition
satisfies.
➢ Loops in programming are used to repeat a block of code until the specified condition is met.
➢ A loop statement allows programmers to execute a statement or group of statements multiple times
without repetition of code.
There are mainly two types of loops in C Programming:
1. Entry Controlled loops:
• In Entry controlled loops the test condition is checked before entering the main body of the
loop.
• For Loop and While Loop is Entry-controlled loops.
2. Exit Controlled loops:
• In Exit controlled loops the test condition is evaluated at the end of the loop body.
• The loop body will execute at least once, irrespective of whether the condition is true or false.
• do-while Loop is Exit Controlled loop.
Loop Type Description

for loop first Initializes, then condition check, then executes the body and at last, the update is done.

first Initializes, then condition checks, and then executes the body, and updating can be
while loop
inside the body.

do-while
do-while first executes the body and then the condition check is done.
loop

a) for Loop:-
➢ for loop in C programming is a repetition control structure that allows programmers to write a
loop that will be executed a specific number of times.
➢ for loop enables programmers to perform n number of steps together in a single line.
Syntax:

for (initialize expression; test expression; update expression)


{
//
// body of for loop
//
}

Example:

for(int i = 0; i < n; ++i)


{
printf("Body of for loop which will execute till n");
}
• In for loop, a loop variable is used to control the loop.
• Firstly we initialize the loop variable with some value, then check its test condition. If the
statement is true then control will move to the body and the body of for loop will be executed.
Steps will be repeated till the exit condition becomes true. If the test condition will be false then it
will stop.
• Initialization Expression: In this expression, we assign a loop variable or loop counter to
some value. for example: int i=1;
• Test Expression: In this expression, test conditions are performed. If the condition evaluates to
true then the loop body will be executed and then an update of the loop variable is done. If the
test expression becomes false then the control will exit from the loop. for example, i<=9;
• Update Expression: After execution of the loop body loop variable is updated by some value
it could be incremented, decremented, multiplied, or divided by any value.

for loop Equivalent Flow Diagram:-

Example:-
// C program to illustrate for loop
#include <stdio.h>

// Driver code
int main()
{
int i = 0;

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


{
printf( "Hello World\n");
}
return 0;
}

b) While Loop:-
➢ While loop does not depend upon the number of iterations.
➢ In for loop the number of iterations was previously known to us but in the While loop, the
execution is terminated on the basis of the test condition.If the test condition will become false
then it will break from the while loop else body will be executed.
Syntax:

initialization_expression;

while (test_expression)
{
// body of the while loop

update_expression;
}

Flow Diagram for while loop:


Example:-
// C program to illustrate
// while loop
#include <stdio.h>

// Driver code
int main()
{
// Initialization expression
int i = 2;

// Test expression
while(i < 10)
{
// loop body
printf( "Hello World\n");

// update expression
i++;
}

return 0;
}

c) do-while Loop:-
The do-while loop is similar to a while loop but the only difference lies in the do-while loop test condition
which is tested at the end of the body.
In the do-while loop, the loop body will execute at least once irrespective of the test condition.
Syntax:

initialization_expression;
do
{
// body of do-while loop

update_expression;

} while (test_expression);
Flowchart:-

Example:-

6. Conditional or Ternary Operator (?:) in C:-


➢ The conditional operator in C is kind of similar to the if-else statement as it follows the same
algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-
else statements in the shortest way possible.
➢ It is also known as the ternary operator in C as it operates on three operands.

Syntax of Conditional/Ternary Operator in C:-


The conditional operator can be in the form:

variable = Expression1 ? Expression2 : Expression3;

Or the syntax can also be in this form:

variable = (condition) ? Expression2 : Expression3;

Or syntax can also be in this form:

(condition) ? (variable = Expression2) : (variable = Expression3);


It can be visualized into an if-else statement as:

6.1 Working of Conditional/Ternary Operator in C:-


The working of the conditional operator in C is as follows:
Step 1: Expression1 is the condition to be evaluated.
Step 2A: If the condition(Expression1) is True then Expression2 will be executed.
Step 2B: If the condition(Expression1) is false then Expression3 will be executed.
Step 3: Results will be returned.
6.2 Flowchart of Conditional/Ternary Operator in C:-

6.3 Examples of C Ternary Operator:-


Example 1: C Program to Store the greatest of the two Numbers using the ternary operator.
Code:-
// C program to find largest among two
// numbers using ternary operator

#include <stdio.h>

int main()
{
int m = 5, n = 4;

(m > n) ? printf("m is greater than n that is %d > %d",


m, n)
: printf("n is greater than m that is %d > %d",
n, m);

return 0;
}

Example 2: C Program to check whether a year is a leap year using ternary operator.
Code:-

// C program to check whether a year is leap year or not


// using ternary operator

#include <stdio.h>

int main()
{
int yr = 1900;

(yr%4==0) ? (yr%100!=0? printf("The year %d is a leap year",yr)


: (yr%400==0 ? printf("The year %d is a leap year",yr)
: printf("The year %d is not a leap year",yr)))
: printf("The year %d is not a leap year",yr);
return 0;
}

You might also like