0% found this document useful (0 votes)
6 views21 pages

CPCS301_Topic2

The document provides an overview of running programs in C, Python, PHP, and MATLAB, including examples and explanations of key concepts. It covers input/output handling in C, basic Python functions, PHP syntax for web programming, and MATLAB command usage. The goal is to familiarize students with these programming languages and their respective environments.

Uploaded by

rkomosany
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)
6 views21 pages

CPCS301_Topic2

The document provides an overview of running programs in C, Python, PHP, and MATLAB, including examples and explanations of key concepts. It covers input/output handling in C, basic Python functions, PHP syntax for web programming, and MATLAB command usage. The goal is to familiarize students with these programming languages and their respective environments.

Uploaded by

rkomosany
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/ 21

Topic 02 Running a program in different

languages
Objective

Students should get familiar with: C, Python, PHP and MATLAB language and some simple
programs.
Current Lab Learning Outcomes (LLO)

By completion of the lab the students should be able to


1. Running simple programs in C, Python, PHP, MATLAB

Lab Description
1. Running programs in C:

INPUT / OUTPUT:

The important aspects of C programming language are its ability to handle input and output
(I/O). A program using input / output functions must include the standard header file (stdio.h) in
it using the directive.

To run codes in C, we can use an online compiler (such as: https://www.onlinegdb.com/ ,


www.ideone.com or www.compileonline.com) or we can use Visual Studio. C code will not be
directly runnable in Visual Studio, some settings must be changed first. In this video, you will
find a detailed steps to run a C code in Visual Studio 2013 (see it here).

P a g e 1 | 21
Example 1:
C program for printing Fibonacci series up to n numbers
Code
/* PROGRAM FOR PRINTING FIBONACCI SERIES UPTO N NUMBERS */

#include <stdio.h>
#include <conio.h>
void main()
{
int num1 = 0, num2 = 1, no, counter, fib;

printf("\n ENTER LENGTH OF SERIES (N) : ");


scanf("%d", &no);

printf("\n\n<----FIBONACCI SERIES---->");
printf("\n\n\t\t %d %d", num1, num2);

for (counter = 1; counter <= no - 2; counter++)


{
fab = num1 + num2;
printf(" %d ", fib);
num1 = num2;
num2 = fib;
}
getch();
}
Output (in Visual Studio 2013)

Run the same code in an online compiler (www.compileonline.com)

Libraries In C Language:
#include <stdio.h>: standard input/output library for using functions like printf and scanf
#include <conio.h>: For console input/output functions like getch() (used to wait for a
keypress).
#include <string.h>: Provides string-related functions like strlen.
getch();: Waits for the user to press a key before the program exits.

Some of the Common Format Specifiers:

P a g e 2 | 21
1. For Integers:
o %d or %i: Signed decimal integer (e.g., 42, -42)
o %u: Unsigned decimal integer (e.g., 42 but not -42)
o %o: Unsigned octal integer (e.g., 052)
o %x or %X: Unsigned hexadecimal integer (x for lowercase, X for uppercase, e.g.,
0x2A)
2. For Floating-Point Numbers:
o %f: Decimal floating-point number (e.g., 3.14)
o %e or %E: Scientific notation (e.g., 3.14e+00)
3. For Characters:
o %c: Single character (e.g., 'A')
o %s: String of characters (e.g., "Hello")
4. For Pointers:
o %p: Pointer address (e.g., 0x7fff5fbff718)
5. For Length Modifiers (Used with %d, %u, %f, etc.):
o %ld: Long integer (e.g., 2147483647L)
o %lld: Long long integer (e.g., 9223372036854775807LL)
o %hd: Short integer (e.g., 32767)
o %lf: Double-precision floating-point number (e.g., 3.141592653589793)
o %Lf: Long double (extended precision floating-point number)
6. Miscellaneous:
o %%: Prints the % character.

scanf("%d", &no);

• The & operator is used to pass the memory address of the variable no to scanf.

• This allows scanf to directly store the value entered by the user into the memory location of
no.

Code
/* PROGRAM FOR PRINTING FIBONACCI SERIES UPTO N NUMBERS */

#include <stdio.h>
void main()
{
int num1 = 0, num2 = 1, no, counter, fab;

printf("\n ENTER LENGTH OF SERIES (N) : ");


scanf("%d", &no);

P a g e 3 | 21
printf("\n\n<----FIBONACCI SERIES---->");
printf("\n\n\t\t %d %d", num1, num2);

for (counter = 1; counter <= no - 2; counter++)


{
fab = num1 + num2;
printf(" %d ", fab);
num1 = num2;
num2 = fab;
}
}
Output

Example 2:
C program to find the sum of individual digits of a positive integer:
Code
#include<stdio.h>
#include<conio.h>
void main()
{
int num, k = 1, sum = 0;
printf("\n **Enter the number whose digits are to be added: ");
scanf("%d", &num);
while (num != 0)
{
k = num % 10;

P a g e 4 | 21
sum = sum + k;
k = num / 10;
num = k;
}
printf("\n **Sum of the digits: %d", sum);
getch();
}
Output (in Visual Studio 2013)

Run the same code in an online compiler (www.compileonline.com)

Code
#include<stdio.h>
void main()
{
int num, k, sum = 0;
printf("\n **Enter the number whose digits are to be added: ");
scanf("%d", &num);
while (num != 0)
{
k = num % 10;
sum = sum + k;
k = num / 10;
num = k;
}
printf("\n **Sum of the digits: %d", sum);
}
Output

P a g e 5 | 21
Note:
• Modulus Operator (%):

• Used to extract the last digit of a number.

• Integer Division (/):

• Used to remove the last digit of a number.

Example 3:
C program to count the lines, words and characters in given text:
Code
/* Write a C program to count the lines, words and characters in given text*/

#include <stdio.h>
#include <string.h>
#include <conio.h>
void main()
{
char line[81], ctr;
int i, c,end = 0,characters = 0,words = 0,lines = 0;
printf("\n KEY IN THE TEXT.\n");
printf(" GIVE ONE SPACE AFTER EACH WORD.\n");
printf(" WHEN COMPLETED, PRESS 'ENTER' twice.\n\n");
while (end == 0)
{
/* Reading a line of text */
c = 0;
while ((ctr = getchar()) != '\n')
line[c++] = ctr;
line[c] = '\0';
/* counting the words in a line */
if (line[0] == '\0')
break;

P a g e 6 | 21
else
{
words++;
for (i = 0; line[i] != '\0'; i++)
if (line[i] == ' ' || line[i] == '\t')
words++;
}
/* counting lines and characters */
lines = lines + 1;
characters = characters + strlen(line);
}
printf("\n");
printf(" Number of lines = %d\n", lines);
printf(" Number of words = %d\n", words);
printf(" Number of characters = %d\n", characters);
getch();
}
Output (in Visual Studio 2013)

Run the same code in an online compiler (www.compileonline.com)

Code
/* Write a C program to count the lines, words and characters in a given text*/

#include <stdio.h>
#include <string.h>
void main()
{
/* line[81]: Stores the input line (up to 80 characters) */
/* ctr: Reads characters from input */
/* end: Flag to indicate the end of text entry (set to 0 initially) */
char line[81], ctr;
int i, c,end = 0,characters = 0,words = 0,lines = 0;
printf("\n KEY IN THE TEXT.\n");
printf(" GIVE ONE SPACE AFTER EACH WORD.\n");
printf(" WHEN COMPLETED, PRESS 'ENTER' twice.\n\n");

P a g e 7 | 21
/* This loop continues until the user presses Enter twice, signaling the end of
input */
while (end == 0)
{
/* Reading a line of text */
c = 0;
while ((ctr = getchar()) != '\n')
line[c++] = ctr;
line[c] = '\0';
/* counting the words in a line */
if (line[0] == '\0')
break;
else
{
words++;
for (i = 0; line[i] != '\0'; i++)
if (line[i] == ' ' || line[i] == '\t')
words++;
}
/* counting lines and characters */
lines = lines + 1;
characters = characters + strlen(line);
}
printf("\n");
printf(" Number of lines = %d\n", lines);
printf(" Number of words = %d\n", words);
printf(" Number of characters = %d\n", characters);
}
Output

2. Running programs in Python:

There are two main components we will be using to write a program in Python;
• Python Shell
• File Window

Writing code directly in Python Shell, Example:


P a g e 8 | 21
The Euclidean Algorithm is a method for finding the greatest common divisor (GCD) of two
integers.
Code
>>> def Euclid (m,n):
while n!=0:
r=m%n
m=n
n=r
return m
>>> Euclid(60,24)
12
>>>
Output

Writing code in File window, Example:


Euclid Function: Accepts two integer arguments m and n.
The loop runs as long as n is not zero. The Euclidean Algorithm works by repeatedly
dividing m by n until n becomes zero.

Code
#Euclid Algorithm
import math
def Euclid (m,n):

P a g e 9 | 21
while n!=0:
r=m%n #m % n computes the remainder of m divided by n
m=n #This remainder (r) will become the new value of n in the next iteration.
n=r
return m

Comparing Shell Execution with Source Code in a File:


• Advantage/Disadvantage of statements in shell:
– Advantage:
Executed immediately.
– Disadvantage:
Retype when it is to be executed again.
• Source code in a file:
Can be executed in several ways:
– Click on icon if in a windowing environment.
– Type file name in consol mode.
– Can execute easily within IDLE.
P a g e 10 | 21
P a g e 11 | 21
P a g e 12 | 21
Comments:

• Commented lines in Python start with a “#”. All text beyond “#” will be ignored.

Output: The print command

• The print command is similar to

“System.out.println” in Java.

• To concatenate output put a comma ( , ) between elements.

• Python puts a space between concatenated elements.

Try it out:

P a g e 13 | 21
3. Running PHP programs using XAMPP:

1. Write the following code, and save the file in c:\\xampp\htdocs\cpcs301 directory
as c:\\xampp\htdocs\cpcs301\Welcome.php. [Create cpcs301 folder in
c:\\xampp\htdocs.]

<html>
<?php
$name = "Introduction to Internet Programming"; //
declaration and initialization
?>
<head>
<title> Welcome </title>
</head>
<body>
<p>
Welcome to PHP, <?php print( "$name\n" ); ?>!
</p>
</body>
</html>
2. Now, open the browser and write the following in the address bar
http://localhost/cpcs301/Welcome.php to see the program output. [Again,
I assume that the Apache Web server is running. If not double click on the xampp
shortcut on the desktop which would open xampp control panel application. Start Apache
by clicking on the start button. You’d see the following.]

P a g e 14 | 21
Result is shown in following figure.

P a g e 15 | 21
In PHP, you can print output to the screen using functions like print and echo. Both are used to
display text, variables, or HTML content.

1. Using echo

• Syntax:

echo "Your text or variable here";

• Examples:

echo "Hello, World!";


echo "This is a heading";
$name = "PHP";
echo "Welcome to $name programming!";

P a g e 16 | 21
2. Using print

• Syntax:

print("Your text or variable here");

• Examples:

print("Hello, World!");
print("This is a heading");
$name = "PHP";
print("Welcome to $name programming!");

Differences Between echo and print

Aspect echo print


Usage Faster, can output multiple items Slower, outputs only one item
Return Value Does not return a value Returns 1 (useful in expressions)
Syntax Parentheses optional Parentheses required if arguments are passed

4. Running programs using MATLAB:

- Double clicking on the MATLAB icon that should be on the desktop of your computer.

P a g e 17 | 21
- The Command Window allows a user to enter simple commands.
- Next press the Enter or Return key.
For instance,
>> s = 1 + 2
s=
3

P a g e 18 | 21
Table 1 some commands of Matlab

P a g e 19 | 21
P a g e 20 | 21
Extra (supplementary) Materials (if any)

Provide extra references or more materials for the covered topics.

P a g e 21 | 21

You might also like