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

Outcome D Examples

The document provides multiple examples of C and Octave programming, demonstrating various control structures such as FOR, WHILE, and DO-WHILE loops. It includes tasks like calculating sums, finding powers, and manipulating matrices, as well as image processing techniques like inversion and thresholding. Each example is accompanied by code snippets and expected outputs.

Uploaded by

Mahori Thabane
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)
21 views12 pages

Outcome D Examples

The document provides multiple examples of C and Octave programming, demonstrating various control structures such as FOR, WHILE, and DO-WHILE loops. It includes tasks like calculating sums, finding powers, and manipulating matrices, as well as image processing techniques like inversion and thresholding. Each example is accompanied by code snippets and expected outputs.

Uploaded by

Mahori Thabane
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/ 12

Outcome D examples

C programming
Example 1: FOR loop
Write a C program that calls a function called arraySum. The function arraySum takes two arguments;
an integer array and the number of elements in the array. Have the function return as its result, the
sum of the elements in the array. Use a for loop
Answer

#include <stdio.h>
int arraySum(int arr[10], int num);

int main(void)
{
int val[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
char ch;

prin�("Sum = %d\n", arraySum(val, 10));


ch = getchar();
return 0;
}

int arraySum(int arr[10], int num)


{
int i;
int sum = 0;

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


{
sum += arr[i];
}
return sum;
}

Example 2: FOR loop


2.1 Write a C program that jumps out of an infinite loop using the break statement.
2.2 Simple program that uses continue statement.
Answer

#include <stdio.h>

int main (void)


{
int t , num;

for ( ; ; ) {
prin�("Enter a number: ");
scanf("%d" , &t) ;
if ( t==10 ) break ;
}

//when do not update t result in infinite while loop


/*while (t < 15) {
prin�("t=%d\n", t);
}//uncomment in class

//does not enter while loop


num = 31;
while(num >10&&num<=30)
{
prin�("%d\n", num);
}*/

for ( t=0 ; t<=20 ; t++) {


if (t%2) con�nue;
prin�("%d\n" , t);
}

Example 3: DO-WHILE loop


Write a C program demonstrating use of prefix and postfix operators with a do-while loop. The
program gets the remainder of a value and uses a switch statement to display a character. Play with the
values of I and j and print out the value of j before the decrement and after the decrement. Print out
the value of I before increment and after increment.
Answer

#include <stdio.h>

int main(void)
{
int i = 4, j = 4;

do
{
j = i%5;

switch (j--)
{
case 1:
prin�("A");
i *= (++j * 5)*3;
break;
case 2:
prin�("B");
i %= 2;
break;
case 3:
prin�("C");
i -= j;
break;
case 4:
prin�("D");
i %= 12;
break;
case 5:
prin�("E");
i *= 1;
break;
default:
prin�("F");
i *= 1;
break;
}
} while (++i < 10);

return 0;
}

Example 4: FOR loop


Write a C program to print the values in a 2x2 array.
Answer

#include <stdio.h>

int main()

int row, column;

int my_array[3][3] =

{10, 23, 42},

{1, 654, 0},

{40652, 22, 0}

};

for (row = 0; row <=2; row++)


{

for (column = 0; column <= 2; column++)

prin�("%d\t", my_array[column][row]);

prin�("\n");

prin�("\n");

return 0;

Example 5: DO-WHILE and WHILE loop


Write a C program to prompt a user for a password. Note the number of steps if using a WHILE loop
versus when using a DO-WHILE loop.
Answer

#include <stdio.h>

int main (void)


{
char password[] = "Lerato";
char pwd[100] = {};
int val;

prin�("password %s\n", password);


prin�("pwd %s\n", pwd);
val = strcmp(password, pwd);
prin�("Val %d\n", val);
while (val != 0)
{
prin�("Enter password\n");
scanf("%s", pwd);
val = strcmp(password, pwd);
prin�("Val %d\n", val);
}

do
{
prin�("Enter password\n");
scanf("%s", pwd);
} while (strcmp(password, pwd) != 0);

return 0;
}//main

Example 6: Nested FOR and WHILE loops


Write a C program to that uses a nested FOR loop to print a 3x3 matrix of the first nine numbers and a
nested WHILE loop to print a 3x3 matrix of the first nine alphabet letters.
Answer

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

int main()
{
int val[3][3] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
char ch[3][3] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'};
int i, j;
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
prin�("%d \t", val[i][j]);
}
prin�("\n");
}
prin�("\n\n\n");

i = 0;
while (i < 3) {
j = 0;
while (j < 3) {
prin�("%c \t", ch[i][j]);
j++;
}
i++;
prin�("\n");
}
return 0;
}

Octave

Example 1: Sum of First N Natural Numbers

Write an Octave script that calculates the sum of the first N = 10 natural numbers using a for loop.

Expected Output:
The sum of the first 10 natural numbers is 55

Answer

N = 10;

sum = 0;

for i = 1:N

sum = sum + i;

end

fprintf('The sum of the first %d natural numbers is %d\n', N, sum);

Example 2: Print Even Numbers from 1 to 20

Use a for loop to print all even numbers from 1 to 20.

Expected Output:

2 4 6 8 10 12 14 16 18 20

Answer

for i = 1:20
if mod(i, 2) == 0
fprin�('%d ', i);
end
end
fprin�('\n');

Example 3: Find the Smallest Power of 2 Greater Than 1000

Use a while loop to find the smallest power of 2 that is greater than 1000.

Expected Output:

2^10 = 1024 is the first power of 2 greater than 1000

Answer
value = 1;
exponent = 0;

while value <= 1000


exponent = exponent + 1;
value = 2^exponent;
end

fprintf('2^%d = %d is the first power of 2 greater than 1000\n', exponent, value);

Example 4: Calculate Factorial of a Number

Use a while loop to compute the factorial of a number n = 5.

Expected Output:

Factorial of 5 is 120

Answer
n = 5;
factorial = 1;
i = 1;

while i <= n
factorial = factorial * i;
i = i + 1;
end

fprin�('Factorial of %d is %d\n', n, factorial);

Example 5: Sum of All Elements in a Matrix

Given a matrix A, use a for loop to calculate the sum of all its elements.

Expected Output:

Sum of all elements in the matrix is 45

Answer
A = [1 2 3; 4 5 6; 7 8 9];
[m, n] = size(A);
total = 0;

for i = 1:m
for j = 1:n
total = total + A(i,j);
end
end

fprintf('Sum of all elements in the matrix is %d\n', total);

Example 6: Transpose a Matrix Manually


Use nested for loops to manually compute the transpose of a matrix A.

Expected Output:

Original Matrix A:
1 2 3
4 5 6
Transposed Matrix A_T:
1 4
2 5
3 6

Answer
A = [1 2 3; 4 5 6];
[m, n] = size(A);
A_T = zeros(n, m); % Pre-allocate transpose matrix

for i = 1:m
for j = 1:n
A_T(j, i) = A(i, j);
end
end

disp('Original Matrix A:');


disp(A);
disp('Transposed Matrix A_T:');
disp(A_T);

Example 7: Find the First Negative Element in a Matrix

Given a matrix B, use a while loop to find the first negative element and its position. Assume row-
major order (left to right, top to bottom).

Expected Output:

First negative element is -1 at position (2, 1)

Answer

B = [3 5 7; -1 4 6; 2 -3 8];
[m, n] = size(B);
found = false;
i = 1;
j = 1;

while ~found && i <= m


j = 1;
while ~found && j <= n
if B(i, j) < 0
fprintf('First negative element is %d at position (%d, %d)\n', B(i,j), i, j);
found = true;
end
j = j + 1;
end
i = i + 1;
end

Example 8: Normalize Matrix Values Using a while Loop

Write a while loop to divide all elements of a matrix C by its maximum value so that all values are
between 0 and 1.

Expected Output:

Normalized Matrix C:
0.1667 0.3333 0.5000
0.6667 0.8333 1.0000

Answer

C = [4 8 12; 16 20 24];

[m, n] = size(C);

max_val = max(C(:));

i = 1;

while i <= m

j = 1;

while j <= n

C(i,j) = C(i,j) / max_val;

j = j + 1;

end

i = i + 1;

end
disp('Normalized Matrix C:');

disp(C);

Basic image processing tasks using loops in Octave. These examples assume you're using grayscale
images represented as 2D matrices. Use loops to do things like image inversion, thresholding, and
computing a simple image histogram.

For real image files, Octave’s imread, imshow, and imwrite functions (from the Image package) are
useful. Make sure the Image package is installed and loaded:

pkg load image;

Example 9: Invert a Grayscale Image (Negative Image)

Write a script to invert a grayscale image using a for loop. Pixel values range from 0 (black) to 255
(white).

Answer

pkg load image;


img = imread('cameraman.tif'); % Built-in grayscale image
[m, n] = size(img);
inverted_img = zeros(m, n, 'uint8');

for i = 1:m
for j = 1:n
inverted_img(i, j) = 255 - img(i, j);
end
end

imshow(inverted_img);
title('Inverted Image');

Effect:
The image is flipped in brightness — black becomes white, white becomes black.

Example 10: Apply Thresholding (Binary Image)

Using a while loop, convert a grayscale image into a binary image where all pixel values above 100
become 255 (white), and others become 0 (black).

Answer
pkg load image;
img = imread('cameraman.tif');
[m, n] = size(img);
binary_img = zeros(m, n, 'uint8');

i = 1;
while i <= m
j = 1;
while j <= n
if img(i, j) > 100
binary_img(i, j) = 255;
else
binary_img(i, j) = 0;
end
j = j + 1;
end
i = i + 1;
end

imshow(binary_img);
title('Binary Threshold Image');

Example 11: Simple Histogram Computation (Pixel Intensity Count)

Write a for loop to compute the histogram (pixel intensity count) of a grayscale image.

Answer
pkg load image;
img = imread('cameraman.tif');
histogram = zeros(1, 256); % One bin for each intensity value (0–255)

[m, n] = size(img);

for i = 1:m
for j = 1:n
intensity = img(i, j);
histogram(intensity + 1) = histogram(intensity + 1) + 1; % +1 for Octave indexing
end
end

bar(0:255, histogram);
xlabel('Pixel Intensity');
ylabel('Frequency');
title('Image Histogram');

Example 12: Brightness Adjustment

Write a script to increase the brightness of an image by 50 using a for loop, capping the max value at
255.

Answer
pkg load image;
img = imread('cameraman.tif');
[m, n] = size(img);
bright_img = zeros(m, n, 'uint8');

for i = 1:m
for j = 1:n
new_val = img(i, j) + 50;
bright_img(i, j) = min(new_val, 255);
end
end

imshow(bright_img);
title('Brightened Image');

You might also like