0% found this document useful (0 votes)
163 views12 pages

CSE 121, Structured Programming Language (Eve) Shornaa

Arrays allow storing multiple values of the same data type. Functions help improve code readability, reusability and debugging by encapsulating repeatable tasks. Strings are arrays of characters that end with a null terminator. Pointers store the address of a variable rather than its value. The break statement terminates the nearest enclosing loop, while continue skips to the next iteration of the current loop.

Uploaded by

Designer Emil
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)
163 views12 pages

CSE 121, Structured Programming Language (Eve) Shornaa

Arrays allow storing multiple values of the same data type. Functions help improve code readability, reusability and debugging by encapsulating repeatable tasks. Strings are arrays of characters that end with a null terminator. Pointers store the address of a variable rather than its value. The break statement terminates the nearest enclosing loop, while continue skips to the next iteration of the current loop.

Uploaded by

Designer Emil
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
You are on page 1/ 12

With the example of C codes explain the concept of array,

function, string and pointer


Arrays in C programming with examples
n array is a group (or collection) of same data types. For example an int array
holds the elements of int types while a float array holds the elements of float
types.
Why we need Array in C Programming?
Consider a scenario where you need to find out the average of 100 integer
numbers entered by user. In C, you have two ways to do this: 1) Define 100
variables with int data type and then perform 100 scanf() operations to store the
entered values in the variables and then at last calculate the average of them. 2)
Have a single integer array to store all the values, loop the array to store all the
entered values in array and later calculate the average.
Which solution is better according to you? Obviously the second solution, it is
convenient to store same data types in one single variable and later access them
using array index (we will discuss that later in this tutorial).
How to declare Array in C
int num[35];  /* An integer array of 35 elements */
char ch[10];  /* An array of characters for 10 elements */

Similarly an array can be of any data type such as double, float, short etc.


How to access element of an array in C
You can use array subscript (or index) to access any element stored in array.
Subscript starts with 0, which means arr[0] represents the first element in the array
arr.
In general arr[n-1] can be used to access nth element of an array. where n is any
integer number.
For example:
int mydata[20];
mydata[0] /* first element of array mydata*/
mydata[19] /* last (20th) element of array mydata*/
Example of Array In C programming
#include <stdio.h>
int main()
{
int avg = 0;
int sum =0;
int x=0;

/* Array- declaration – length 4*/


int num[4];

/* We are using a for loop to traverse through the array


* while storing the entered values in the array
*/
for (x=0; x<4;x++)
{
printf("Enter number %d \n", (x+1));
scanf("%d", &num[x]);
}
for (x=0; x<4;x++)
{
sum = sum+num[x];
}

avg = sum/4;
printf("Average of entered number is: %d", avg);
return 0;
}

Output:

Enter number 1
10
Enter number 2
10
Enter number 3
20
Enter number 4
40
Average of entered number is: 20
Functions in C Programming with
examples
A function is a block of statements that performs a specific task. Let’s
say you are writing a C program and you need to perform a same task in
that program more than once. In such case you have two options:

a) Use the same set of statements every time you want to perform the
task
b) Create a function to perform that task, and just call it every time you
need to perform that task.

Why we need functions in C


Functions are used because of following reasons –
a) To improve the readability of code.
b) Improves the reusability of the code, same function can be used in
any program rather than writing the same code from scratch.
c) Debugging of the code would be easier if you use functions, as errors
are easy to be traced.
d) Reduces the size of the code, duplicate set of statements are
replaced by function calls.

Types of functions
1) Predefined standard library functions
Standard library functions are also known as built-in functions.
Functions such as puts(), gets(), printf(), scanf() etc are standard library
functions. These functions are already defined in header files (files
with .h extensions are called header files such as stdio.h), so we just call
them whenever there is a need to use them.
For example, printf() function is defined in <stdio.h> header file so in order
to use the printf() function, we need to include the <stdio.h> header file in
our program using #include <stdio.h>.

2) User Defined functions


The functions that we create in a program are known as user defined
functions or in other words you can say that a function created by user is
known as user defined function.

Now we will learn how to create user defined functions and how to use
them in C Programming

Syntax of a function
return_type function_name (argument list)
{
Set of statements – Block of code
}
return_type: Return type can be of any data type such as int, double,
char, void, short etc. Don’t worry you will understand these terms better
once you go through the examples below.

function_name: It can be anything, however it is advised to have a


meaningful name for the functions so that it would be easy to understand
the purpose of function just by seeing it’s name.

argument list: Argument list contains variables names along with their


data types. These arguments are kind of inputs for the function. For
example – A function which is used to add two integer variables, will be
having two integer argument.

Block of code: Set of C statements, which will be executed whenever a


call will be made to the function.
Creating a user defined function addition()
#include <stdio.h>
int addition(int num1, int num2)
{
int sum;
/* Arguments are used here*/
sum = num1+num2;

/* Function return type is integer so we are returning


* an integer value, the sum of the passed numbers.
*/
return sum;
}

int main()
{
int var1, var2;
printf("Enter number 1: ");
scanf("%d",&var1);
printf("Enter number 2: ");
scanf("%d",&var2);

/* Calling the function here, the function return type


* is integer so we need an integer variable to hold the
* returned value of this function.
*/
int res = addition(var1, var2);
printf ("Output: %d", res);

return 0;
}

Output:
Enter number 1: 100
Enter number 2: 120
Output: 220
C – Strings and String functions with
examples
String is an array of characters. In this guide, we learn how to declare
strings, how to work with strings in C programming and how to use the
pre-defined string handling functions.

We will see how to compare two strings, concatenate strings, copy one
string to another & perform various string manipulation operations. We
can perform such operations using the pre-defined functions of “string.h”
header file. In order to use these string functions you must include
string.h file in your C program.

String Declaration

Method 1:

char address[]={'T', 'E', 'X', 'A', 'S', '\0'};


Method 2: The above string can also be defined as –

char address[]="TEXAS";
In the above declaration NULL character (\0) will automatically be
inserted at the end of the string.
What is NULL Char “\0”?
'\0' represents the end of the string. It is also referred as String terminator
& Null Character.

String I/O in C programming

Read & write Strings in C using Printf() and Scanf()


functions
#include <stdio.h>
#include <string.h>
int main()
{
/* String Declaration*/
char nickname[20];

printf("Enter your Nick name:");

/* I am reading the input string and storing it in nickname


* Array name alone works as a base address of array so
* we can use nickname instead of &nickname here
*/
scanf("%s", nickname);

/*Displaying String*/
printf("%s",nickname);

return 0;
}
Output:
Enter your Nick name:Negan
Negan
Note: %s format specifier is used for strings input/output

Pointers in C Programming with examples


A pointer is a variable that stores the address of another variable.
Unlike other variables that hold values of a certain type, pointer holds the
address of a variable. For example, an integer variable holds (or you can
say stores) an integer value, however an integer pointer holds the
address of a integer variable. 

A Simple Example of Pointers in C


This program shows how a pointer is declared and used. There are several other
things that we can do with pointers, we have discussed them later in this guide.
For now, we just need to know how to link a pointer to the address of a variable.

#include <stdio.h>
int main()
{
//Variable declaration
int num = 10;

//Pointer declaration
int *p;

//Assigning address of num to the pointer p


p = #

printf("Address of variable num is: %p", p);


return 0;
}

Output:

Address of variable num is: 0x7fff5694dc58


Write down the differences between
break and continue statement.
As we know in programming execution of code is done line by line.Now in
order to alter this flow C++ provides two statements break and coninue which
mainly used to skip some specific code at specific line.
Following are the important differences between continue and break.

Sr. Key Break Continue


No.

1 Functionality Break statement mainly used to Continue statement mainly skip


terminate the enclosing loop the rest of loop wherever
such as while, do-while, for or continue is declared and execute
switch statement wherever the next iteration.
break is declared.

2 Executional Break statement resumes the Continue statement resumes the


flow control of the program to the control of the program to the
end of loop and made next iteration of that loop
executional flow outside that enclosing 'continue' and made
loop. executional flow inside the loop
again.

3 Usage As mentioned break is used for On other hand continue causes


the termination of enclosing early execution of the next
loop. iteration of the enclosing loop.

4 Compatibility Break statement can be used We can't use continue statement


and compatible with 'switch', with 'switch','lablel' as it is not
'label'. compatible with them.
Example of Continue vs Break

public class JavaTester{

   public static void main(String args[]){

      // Illustrating break statement (execution stops when value


of i becomes to 4.)

      System.out.println("Break Statement\n");

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

         if(i==4) break;

         System.out.println(i);

      }

      // Illustrating continue statement (execution skipped when


value of i becomes to 1.)

      System.out.println("Continue Statement\n");

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

         if(i==1) continue;

         System.out.println(i);

      }

   }

Output
Break Statement
1
2
3

Continue Statement
2
3
4
5
What do you understand bynested loop? Give an
example of nested for loop.

A nested loop is a loop within a loop, an inner loop within the body of an outer one.
How this works is that the first pass of the outer loop triggers the inner loop, which
executes to completion. Then the second pass of the outer loop triggers the inner
loop again. This repeats until the outer loop finishes. Of course, a break within either
the inner or outer loop would interrupt this process.

Example. Nested Loop


#!/bin/bash
# nested-loop.sh: Nested "for" loops.

outer=1 # Set outer loop counter.

# Beginning of outer loop.


for a in 1 2 3 4 5
do
echo "Pass $outer in outer loop."
echo "---------------------"
inner=1 # Reset inner loop counter.

# ===============================================
# Beginning of inner loop.
for b in 1 2 3 4 5
do
echo "Pass $inner in inner loop."
let "inner+=1" # Increment inner loop counter.
done
# End of inner loop.
# ===============================================

let "outer+=1" # Increment outer loop counter.


echo # Space between output blocks in pass of outer loop.
done
# End of outer loop.

exit 0

Below program uses a nested for loop to print all prime factors of a number.in c
// C Program to print all prime factors
// of a number using nested loop

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

// A function to print all prime factors of a given number n


void primeFactors(int n)
{
// Print the number of 2s that divide n
while (n % 2 == 0) {
printf("%d ", 2);
n = n / 2;
}

// n must be odd at this point. So we can skip


// one element (Note i = i +2)
for (int i = 3; i <= sqrt(n); i = i + 2) {
// While i divides n, print i and divide n
while (n % i == 0) {
printf("%d ", i);
n = n / i;
}
}

// This condition is to handle the case when n


// is a prime number greater than 2
if (n > 2)
printf("%d ", n);
}

/* Driver program to test above function */


int main()
{
int n = 315;
primeFactors(n);
return 0;
}

Output:
3 3 5 7

You might also like