0% found this document useful (0 votes)
5 views25 pages

C Programming

Uploaded by

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

C Programming

Uploaded by

mrinal1986
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Input and output statements

getchar Function in C
getchar is part of a standard C language I/O library I.e . <stdio.h> .
It returns a single input character from standard input device i.e. keyboard.
The typed character is visible on the screen after typing the appropriate character,
the user is required to press the Enter key.
Syntax of getchar() Char variable= getchar();

Program 1 - #include <stdio.h>

int main() {

int ch;

printf("Enter a character: ");

ch = getchar();

printf("You entered: %d\n", ch);

return 0;

Program 2 -
#include <stdio.h>

int main() {

int ch;

int vowels = 0;

printf("Enter text: \n");

while ((ch = getchar()) != EOF) {

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||

ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {

vowels++;

printf("Number of vowels: %d\n", vowels);

return 0;
putchar() }
The C library putchar function is a part of the standard C library and is used to write a single
character to the standard output, which is typically the console or terminal.
Syntax: putchar(int c);

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

int main() int main()

{ { // Get the character to be written

// Get the character to be written char ch = '1';

char ch = 'G';

// Write the Character to stdout

// Write the Character to stdout for (ch = '1'; ch <= '9'; ch++)

putchar(ch); putchar(ch);

return (0); return (0);

} }

getch()
The getch in C is a non-standard function used to receive a character as input from the user. It
is defined in the header file conio.h .The character entered by the user is not visible on the
output screen but is stored in the assigned variable which makes this the best method for
receiving passwords from a user.

Syntax
int getch();
Parameters: This method does not accept any parameters.
Return value: This method returns the ASCII value of the key pressed.

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

int main(){
// Library where getch() is stored
// int variable to store the ASCII value of character
#include <conio.h>
int main()

C puts() function:
C library also facilitates a special function to print a string on the console screen. This function
is represented as puts() function and is also defined in the <stdio.h> header file of C.

C gets() function:
C library facilitates a special function to read a string from a user. This function is represented
as gets() function and is defined in the <stdio.h> header file of C.

#include<stdio.h>

#include <string.h>

void main()

char day[10];

printf("Enter current week day: \n");

gets(day);

printf("Today is: ");

puts(day);

}
scanf()
The scanf() function reads user input and writes it into memory locations specified by the
arguments.
The scanf() function is defined in the <stdio.h> header file.

#include<stdio.h>

void main()

int myNum;

// Ask the user to type a number


printf("Type a number: \n");

// Get and save the number the user types


scanf("%d", &myNum);

// Output the number the user typed


printf("Your number is: %d", myNum);

printf in C :
The printf() function in C is a standard library function used to print formatted output to the console. It is part
of the stdio.h header file

Example:
#include <stdio.h>

int main()

// Using printf to print the text "Hi!"

printf("Hi!");

return 0;

Typecasting
Typecasting in C is the process of converting one data type to another data type by
the programmer using the casting operator during program design.
Syntax:
int x;
float y;
y = (float) x;

example:
#include <stdio.h>
int main()
{
int sum = 17, count = 5;
double mean;
mean = sum / count;
printf("Value of mean: %f\n", mean);
}

Control Structures
A statement used to control the flow of execution in a program is called Control structures.
It basically analyzes and chooses in which direction a program flows based on certain
parameters or conditions. There are three basic types of logic, or flow of control, known as:
1. Sequence logic, or sequential flow
2. Selection logic, or conditional flow
3. Iteration logic, or repetitive flow

Sequence-
In sequence structure, the statement are executed in the same order in which they are
specified in program. The control follows from one statement to other in a logical sequence. All
statement are executed exactly once. It means that no statement is skipped and no statement
is executed more than once.

Example- suppose a program inputs two numbers and displays average on screen. The program uses two
statements to input numbers, one statement to calculate average and one statement to displays average
numbers. These statements are executed in a sequence. All statements are executed once when the program
is executed.

Statement 1

Statement 2

Statement 3

Statement 4

2. Selection :- A Selection structure selects a statement or set of statements to execute on the basis of a
condition. In this structure, statement or set of statements is executed when a particular condition is true and
ignored when the condition is false.

Example-

Suppose a program inputs the marks of a student and displays a message on screen whether the student is
pass or fail. It displays Pass if the student gets 40 or more than 40. It displays Fail when the marks are below
40. The Program checks the mark before displaying the message.

Condition
T OR F

STATEMENT 1 STATEMENT 2
4. ITERATION (REPETATION)
A Iteration structure executes a statement or set of statements repeatedly known as Iteration structure
or loop. There are different type of iteration structure in C. These are while, do-while and for.

Condition
F
T OR F

Example #include <conio.h>


#include<stdio.h>
Void main()
{
Int sub1,sub2,total;
Printf(“Enter marks for sub1\n”);
Scanf(“%d”, &sub1);
Printf(“Enter marks for sub2\n”);
Scanf(“%d”, &sub2);
Total=sub1+sub2;
Printf(“Total marks : %d”, total);
If(total>=50)
{
Printf(“Pass”);
}
Else
Printf(“Fail”);
getch();

Conditional statements
Conditional statements in C programming allow the program to make decisions and execute different
blocks of code based on whether a given condition is true or false.
Three types of conditional statements are-
i. if statement
ii. if..else statement
iii. switch statement
These statements actually contain a block of statements.
if statement
If the condition is true then the statements within the if block are executed, but if the condition is false
then no any action is taken.
The general form of if statement is –
if(condition)
{
Statement block
}
Example:

#include<stdio.h>

#include<conio.h>

void main()

int x = 20;
int y = 18;
if (x > y) {
printf("x is greater than y");

getch();
}

(2) if-else statement.


This statement provides two paths of execution. If the condition is true, the code within the if block is
executed; otherwise, the code within the else block is executed.

if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
Program: Program to check whether a given integer number is odd or even

#include<stdio.h>
#include<conio.h>
void main()
{
Nested if statements

The syntax of nested if…esle statement is as followos-

#include <stdio.h>

int main(){

int i = 10;

if (i == 10) {

if (i < 18)

printf("Still not eligible for vote");

else

printf("Eligible for vote\n");

else {

if (i == 20) {

if (i < 22)

printf("i is smaller than 22 too\n");

else

printf("i is greater than 25");

return 0;

}
Nested If-Else Statement

#include <stdio.h>

int main() {

int marks;
printf("Enter your marks: ");

Switch Statement

The switch statement in C is a control flow statement that allows selection among multiple code blocks
based on the value of a single expression. It serves as an alternative to a series of if-else if statements when
dealing with a single variable or expression that needs to be compared against several constant values

Syntax
switch (expression)

{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
 The switch expression is evaluated once
}
 The value of the expression is compared with the values of each case

 If there is a match, the associated block of code is executed


 The break statement breaks out of the switch block and stops the execution

 The default statement is optional, and specifies some code to run if there is no case match

#include <stdio.h>

int main() {

int var = 1;

switch (var) {

case 1:
printf("Case 1 is Matched.");

 WRITE A PGM that enter weekday number to calculate the weekday name:

Looping statements
Looping statements in C programming allow for the repeated execution of a block
of code until a specified condition is met.
There are three primary types of looping statements in C.
1) for loop
2) while loop
3) do-while loop
Flowchart of C Loop Statement

The for loop


The for loop in C is a control structure that allows you to execute a block of code
multiple times. It is particularly useful when you know how many iterations are
needed. The loop consists of three main parts: initialization, condition, and
increment/decrement, all defined in a single line, making it concise and efficient.
Syntax

for (initialization; condition; increment/decrement)

{
// Code to be executed in each iteration
Components
} of the for loop syntax:
1. Initialization:
This step initializes the loop control variable (e.g., int i = 0). It runs only once, at the
start of the loop.
2. Condition:
The condition is a logical expression that determines whether the loop should
continue. If the condition is true, the loop executes; if false, it terminates.
3. Increment/Decrement:
It updates the loop control variable after each iteration. Also, it ensures the loop
progresses towards termination.
4. Loop Body: It contains the statements to execute repeatedly. The loop body runs
every time the condition evaluates to true.

Example: print the numbers 0 to 10

#include<stdio.h>

Int main()
{

Print Even Numbers from 2 to 10


#include <stdio.h>

int main() {

for (int i = 2; i <= 10; i += 2) {

printf("%d ", i);

return 0;

while Loop in C
The while loop in C allows a block of code to be executed repeatedly as long as a
given condition remains true. It is often used when we want to repeat a block of
code till some condition is satisfied.
Syntax while (condition)

{
// Code to execute while the condition is true

Condition: It is a logical expression that determines whether the loop will execute.
The loop runs as long as the condition evaluates to true.
Loop Body: It contains the block of code to be executed repeatedly while the
condition is true. This code runs every iteration of the loop.
Example

#include <stdio.h>

int main(){

int a = 1;

while(a <= 5)

printf("Hello World \n");

a++;

printf("End of loop");

return 0;

Do-While Loop
The do-while loop in C is a control structure that ensures a block of code executes
at least once, regardless of the condition. After the first execution, the condition is
checked; if true, the loop repeats, and if false, it terminates.
Syntax Do

{
// code block to be executed
}
while (condition);

 do: It indicates the start of the loop body. It ensures the code inside the block
executes at least once before the condition is evaluated.
 Loop Body: It contains the statements to execute repeatedly. It executes at
least once, regardless of the condition.
 Condition: It is a logical expression evaluated after each execution of the loop
body. If true, the loop repeats; if false, the loop terminates.
 Semicolon (;): A semicolon must follow the while statement to mark the end
of the loop syntax.
Example:

#include <stdio.h>

int main()

int a = 1;

do{

printf("Hello World\n");

a++;

} while(a <= 5);

printf("End of loop");

return 0;

Q1- write a program to Validate Positive Number Input.


Loop for counting iteration
To count iterations within a loop in C, a counter variable is typically used. This
variable is initialized before the loop and incremented or decremented within the
loop's body during each iteration.
1. For Loop:
#include <stdio.h>

int main() {
int count;

for (count = 0; count < 5; count++)

printf("Iteration: %d\n", count);


2. While Loop:
#include <stdio.h>
int main()

{
int count = 0;

while (count < 5)

{
printf("Iteration: %d\n", count);
count++;

}
printf("Loop finished. Total iterations: %d\n", count);
return 0;
}

3. Do-While Loop:

#include <stdio.h>

int main()

{
int count = 0;
do {
printf("Iteration: %d\n", count);
while loop for indefinite iterations
In C language, an infinite loop (or, an endless loop) is a never-ending looping
construct that executes a set of statements forever without terminating the loop. It
has a true condition that enables a program to run continuously.

#include <stdio.h>

int main() {

while (1)

printf("Hello World");

return 0;

he parenthesis of while keyword has a Boolean expression that initially evaluates


to True, and is eventually expected to become False. Note that any non-zero
number is treated as True in C. Hence, the following while loop is an infinite loop.
Example 2
#include <stdio.h>

int main()

int i = 0;

while (i <= 10)


{

Nested Loops
When a looping construct in C is employed inside the body of another loop, we call
it a nested loop (or, loops within a loop). Where, the loop that encloses the other
loop is called the outer loop. The one that is enclosed is called the inner loop.

Nested For Loops


#include <stdio.h>

int main()

int i, j;

for(i = 1; i <= 3; i++) // outer loop

for(j = 1; j <= 3; j++) // inner loop

printf("i: %d j: %d\n", i, j);


2. Nested while Loop

#include <stdio.h>

int main()

int end = 5;

printf("Pattern Printing using Nested While loop");

int i = 1;

while (i <= end) {

printf("\n");

int j = 1;
2. Nested do-while Loop
#include <stdio.h>
int main() {
int o = 1;

do {
printf("Outer loop iteration: %d\n", o);
int i = 1;

do {
printf(" Inner loop iteration: %d\n", i);
i++;
} while (i <= 3); // Inner loop condition

o++;
} while (o <= 2); // Outer loop condition
Break Statement in C
The break statement in C is a loop control statement that breaks out of the loop
when encountered. It can be used inside loops or switch statements to bring the
control out of the block. The break statement can only break out of a single loop at
a time.
#include <stdio.h>

int main() {

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

if (i == 5) {

break; // Exit the loop when i equals 5

printf("%d ", i);

return 0;
Continue Statement
}
The continue statement in C is a jump statement used to skip the current iteration
of a loop and continue with the next iteration. It is used inside loops (for, while, or
do-while) along with the conditional statements to bypass the remaining
statements in the current iteration and move on to the next iteration.
Syntax

while (expr)

...

if (condition)

continue;

...
skips the value of 4:
#include <stdio.h>

int main()

int i;

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

{
if (i == 4)

{
continue;
}
printf("%d\n", i);
}

return 0;

You might also like