0% found this document useful (0 votes)
46 views14 pages

engineering ele

Uploaded by

powerslipper69
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)
46 views14 pages

engineering ele

Uploaded by

powerslipper69
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/ 14

Unit No 3: Control Flow

Control Structure

1. Conditional Control (if, if..else, if else if ladder, Switch case)


2. Iteration/Looping and branching (for, while, do while)
3. Jump Statements (Break, continue, goto)

1. Simple if Statement:

The if statement is used to check some given condition and perform some operations depending upon
the correctness of that condition. It is mostly used in the scenario where we need to perform the
different operations for the different conditions.

Syntax:

if(expression)
{
//code to be executed
}
Example :
#include<stdio.h>
int main(){
int number=0;
printf("Enter a number:");
scanf("%d",&number);
if(number%2==0){
printf("%d is even number",number);
}
return 0; }
2. If else Statement :
The if-else statement is used to perform two operations for a single condition. The if-else statement is an
extension to the if statement using which, we can perform two different operations, i.e., one is for the
correctness of that condition, and the other is for the incorrectness of the condition. Here, we must
notice that if and else block cannot be executed simiulteneously.

Syntax: Flowchart :

if(expression){
//code to be executed if condition is
true
}else
{
//code to be executed if condition is
false
}

Example:
#include<stdio.h>
int main()
{
int number=0;
printf("enter a number:");
scanf("%d",&number);
if(number%2==0)
{
printf("%d is even number",number);
}
else{
printf("%d is odd number",number);
}
return 0;
}

3. If else-if ladder Statement (Nested if)

The if-else-if ladder statement is an extension to the if-else statement. It is used in the scenario where there
are multiple cases to be performed for different conditions. In if-else-if ladder statement, if a condition is
true then the statements defined in the if block will be executed, otherwise if some other condition is true
then the statements defined in the else-if block will be executed, at the last if none of the condition is true
then the statements defined in the else block will be executed.
Syntax:

if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

Example:
Program to calculate the grade of the student according to the specified marks.

#include <stdio.h>
int main()
{
int marks;
printf("Enter your marks?");
scanf("%d",&marks);
if(marks > 85 && marks <= 100)
{
printf("Congrats ! you scored grade A ...");
}
else if (marks > 60 && marks <= 85)
{
printf("You scored grade B + ...");
}
else if (marks > 40 && marks <= 60)
{
printf("You scored grade B ...");
}
else if (marks > 30 && marks <= 40)
{
printf("You scored grade C ...");
}
else
{
printf("Sorry you are fail ...");
}
}
4. Switch Statement
The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute
multiple operations for the different possibles values of a single variable called switch variable. Here, We
can define various statements in the multiple cases for the different values of a single variable.
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Rules for switch statement in C language
1. The switch expression must be of an integer or character type.
2. The case value must be an integer or character constant.
3. The case value can be used only inside the switch statement.
4. The break statement in switch case is not must. It is optional. If there is no break statement found
in the case, all the cases will be executed present after the matched case. It is known as fall
through the state of C switch statement.

Valid Switch Invalid Switch Valid Case Invalid case

switch(x) switch(f) case 3; case 2.5;

switch(x>y) switch(x+2.5) case 'a'; case x;

switch(a+b-2) case 1+2; case x+2;

switch(func(x,y)) case 'x'>'y'; case 1,2,3;


Flowchart:

Example:
#include <stdio.h>
int main()
{
int num = 2;
switch (num)
{
case 1:
printf("Value is 1\n");
break;
case 2:
printf("Value is 2\n");
break;
case 3:
printf("Value is 3\n");
break;
default:
printf("Value is not 1, 2, or 3\n");
break;
}

return 0;
}
Iteration Statements/Loops
The looping can be defined as repeating the same process multiple times until a specific condition satisfies.
The looping simplifies the complex problems into the easy ones. It enables us to alter the flow of the
program so that instead of writing the same code again and again, we can repeat the same code for a finite
number of times. For example, if we need to print the first 10 natural numbers then, instead of using the
printf statement 10 times, we can print inside a loop which runs up to 10 iterations.
There are three types of loops used in the C language.

1. For Loop
The for loop is used in the case where we need to execute some part of the code until the given condition is
satisfied. The for loop is also called as a pre-tested loop/entry controlled loop. It is better to use for loop if
the number of iteration is known in advance.

Syntax:
for(initialization;condition;incr/decr)
{
//code to be executed
}

2. While Loop
The while loop in c is to be used in the scenario where we don't know the number of iterations in
advance. The block of statements is executed in the while loop until the condition specified in the while
loop is satisfied. It is also called a pre-tested loop/entry controlled loop.

Syntax:
while(condition)
{
//code to be executed
}

3. Do while
The do-while loop continues until a given condition satisfies. It is also called post tested loop/exit controlled
loop. It is used when it is necessary to execute the loop at least once (mostly menu driven programs).

Syntax:
do{
//code to be executed
}while(condition);
Difference between break and continue
Unit No 4: Arrays and Strings

 Array:
An array is defined as the collection of similar type of data items stored at contiguous memory locations.
Arrays are the derived data type in C programming language which can store the primitive type of data
such as int, char, double, float, etc. It also has the capability to store the collection of derived data types,
such as pointers, structure, etc. The array is the simplest data structure where each data element can be
randomly accessed by using its index number. C array is beneficial if you have to store similar elements.
For example, if we want to store the marks of a student in 6 subjects, then we don't need to define
different variables for the marks in the different subject. Instead of that, we can define an array which
can store the marks in each subject at the contiguous memory locations.
Advantage of C Array
1) Code Optimization: Less code to the access the data.

2) Ease of traversing: By using the for loop, we can retrieve the elements of an array easily.

3) Ease of sorting: To sort the elements of the array, we need a few lines of code only.

4) Random Access: We can access any element randomly using the array.

C Array: Declaration with Initialization (1-D array)


We can initialize the c array at the time of declaration.
int marks[5]={20,30,40,50,60};

Example:
#include<stdio.h>
int main(){
int i=0;
int marks[5]={20,30,40,50,60}; //declaration and initialization of array
//traversal of array
for(i=0;i<5;i++){
printf("%d \n",marks[i]);
}
return 0;
}

Two Dimensional Array in C (2-D)


The two-dimensional array can be defined as an array of arrays. The 2D array is organized as matrices
which can be represented as the collection of rows and columns.

Declaration of two dimensional Array in C

data_type array_name[rows][columns];
ex. int twodimen[4][3];

Initialization of 2D Array in C

int arr[4][3]={{1,2,3},{2,3,4},{3,4,5},{4,5,6}};
 String
A string in C is a one-dimensional array of char type, with the last character in the array
being a "null character" represented by '\0'. Thus, a string in C can be defined as a null-
terminated sequence of char type values.
There are two ways to declare a string in c language.

1. By char array

example of declaring string by char array in C language.


char ch[10]={'j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't', '\0'};

2. By string literal

define the string by the string literal in C language. For example:


char ch[]="College";

C gets() and puts() functions


The gets() and puts() are declared in the header file stdio.h. Both the functions are involved in the
input/output operations of the strings.

Read a string using gets() and print it on the Screen using puts().

#include<stdio.h>
#include <string.h>
int main(){
char name[50];
printf("Enter your name: ");
gets(name); //reads string from user
printf("Your name is: ");
puts(name); //displays string
return 0;
}

Do it yourself:
String handling functions:
C String Length: strlen() function
C Copy String: strcpy()
Strcat() function in C
Strcmp() function in C
C Reverse String: strrev()
Strlwr() function in C
Strupr() function in C
Unit 5: Structures and user define functions

 Structures
Structures (also called structs) are a way to group several related variables into one place. Each variable in
the structure is known as a member of the structure.
Unlike an array, a structure can contain many different data types (int, float, char, etc.).

Create a Structure
You can create a structure by using the struct keyword and declare each of its members inside curly
braces:

struct MyStructure { // Structure declaration


int myNum; // Member (int variable)
char myLetter; // Member (char variable)
}; // End the structure with a semicolon

To access the structure, you must create a variable of it.

Use the struct keyword inside the main() method, followed by the name of the structure and then the
name of the structure variable:

Create a struct variable with the name "s1":

struct myStructure {
int myNum;
char myLetter;
};

int main() {
struct myStructure s1;
return 0;
}

Access Structure Members

To access members of a structure, use the dot syntax (.):


Example
// Create a structure called myStructure
struct myStructure {
int myNum;
char myLetter;
};

int main() {
// Create a structure variable of myStructure called s1
struct myStructure s1;

// Assign values to members of s1


s1.myNum = 13;
s1.myLetter = 'B';

// Print values
printf("My number: %d\n", s1.myNum);
printf("My letter: %c\n", s1.myLetter);

return 0;
}

Output:
My number: 13
My letter: B

Example :Refer Lab manual Experiment No 8:

 Functions :
o A function is a block of code which only runs when it is called.
o You can pass data, known as parameters, into a function.
o Functions are used to perform certain actions, and they are important for reusing code:
Define the code once, and use it many times.

Predefined Functions
For example, main() is a function, which is used to execute code, and printf() is a function; used to
output/print text to the screen:

User define functions:

A function consist of two parts:

 Declaration: the function's name, return type, and parameters (if any)
 Definition: the body of the function (code to be executed)

void myFunction()// declaration


{
// the body of the function (definition)
}

Create a Function

To create (often referred to as declare) your own function, specify the name of the function, followed by
parentheses () and curly brackets {}:

Syntax
void myFunction() // user define function
{
// code to be executed
}

Call a Function
Declared functions are not executed immediately. They are "saved for later use", and will be executed
when they are called.

To call a function, write the function's name followed by two parentheses () and a semicolon ;

In the following example, myFunction() is used to print a text (the action), when it is called:

Example

//Inside main, call myFunction():

// Create a function
void myFunction() // create a function
{
printf("I just got executed!");
}
int main()
{
myFunction(); // call the function
return 0;
}
// Outputs "I just got executed!"
A function can be called multiple times.

Example : Calculate the Sum of Numbers


#include <stdio.h>
void calculateSum() // create the user define function
{
int x = 5;
int y = 10;
int sum = x + y;
printf("The sum of x + y is: %d", sum);
}

int main() {
calculateSum(); // call the function
return 0;
}

C Function Parameters
Parameters and Arguments
Information can be passed to functions as a parameter. Parameters act as variables inside the function.

Syntax
returnType functionName(parameter1, parameter2, parameter3)
{
// code to be executed
}

Example:
#include<stdio.h>
void calculateSum(int x, int y) // function with parameter
{
int sum = x + y;
printf("The sum of %d + %d is: %d\n", x, y, sum);
}

int main() {
calculateSum(5, 3); // function call
calculateSum(8, 2);
calculateSum(15, 15);
return 0;
}

C Variable Scope
1. Local Scope
A local variable cannot be used outside the function it belongs to.
Example:
#include<stdio.h>
void myFunction()
{
int x = 5; // Local variable that belongs to only myFunction
printf("%d", x);
}

int main()
{
myFunction(); // function call
return 0;
}

2. Global scope
A variable created outside of a function, is called a global variable and belongs to the global
scope.
Example

A variable created outside of a function is global and can therefore be used by anyone:

#include<stdio.h>
int x = 5; // Global variable x
void myFunction()
{
printf("%d", x); // We can use x here
}
int main()
{
myFunction();
printf("%d", x); // We can also use x here
return 0;
}

C Recursion

Recursion is the technique of making a function call itself. This technique provides a way to break
complicated problems down into simple problems which are easier to solve.

Example : factorial program in c using recursion

#include<stdio.h>
long factorial(int n)
{
if (n == 0)
return 1;
else
return(n * factorial(n-1));
}
void main()
{
int number;
long fact;
printf("Enter a number: ");
scanf("%d", &number);

fact = factorial(number);
printf("Factorial of %d is %ld\n", number, fact);
return 0;
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy