Learning About Compiler Installation, Basic C Program, Basic Data Types, Basic Input or Output and The Use of Variables

Download as pdf or txt
Download as pdf or txt
You are on page 1of 14

DHA Suffa University

Department of Computer Science


CS1001L – Programming Fundamentals
Spring 2020
Lab 03 – Overview of C
Objectives
Learning about compiler installation, basic C program, basic data types, basic input or
output and the use of variables.
Instructions
• Read, the text provided in bulleted form in different paragraphs, with proper attention.
• Perform all examples as shown.
• First complete the examples and tasks then try and test your own programs.

Programming
A programming language is a formal language designed to communicate instructions to a
machine, particularly a computer. Programming languages can be used to create programs that
control the behavior of a machine and/or to express algorithms precisely.
Compiler
A compiler is a computer program (or set of programs) that transforms source code written in
a programming language (the source language) into another computer language (the target
language, often having a binary form known as object code). The most common reason for wanting
to transform source code is to create an executable program.
Install Compiler
Step#1: http://download.savannah.nongnu.org/releases/tinycc/tcc-0.9.25-win32-
bin.zip

Step#2 after downloading Extract the folder

Step#3 Copy the folder in c drive: like

Step#4: Now your tcc folder path is C:\tcc\


Step#5: Right click on the “My Computer” icon or on “This PC” in File Explorer and go to properties
like below

Step#6: You will get the following window

Step#7: Click on Advanced System Settings and you will get system properties window
Step#8: In advance tab there is Environment Variables button click on it
Step#9: In System variable, click on “New”

Step# 10: create a variable named “path” and value is c:\tcc\ like below and click OK button
Step# 11: go to search bar and write “cmd” and click on Command Prompt
Step#12: In command prompt write command “tcc” if you get result like given below means
you configure tcc compiler successfully

Compiling the C program using the command prompt

• Type tcc<space>filename.c in the command prompt and press enter. If you see the prompt
again without anything being displayed this means that your code compiled without errors
(i.e. no syntax errors – your program grammar is correct at least).
• You may observe that filename.exe has been created in the same directory where the
filename.c file is.

Running/Executing the C program using the command prompt

• Type filename in the command prompt and press enter. You may see that Hello World!!!
has been displayed on the screen. (filename here is the name of the exe file created)
C Language: C is a general-purpose programming language that was originally developed by Dennis
Ritchie between 1969 and 1973 at AT&T Bell Labs. C is reliable, simple and easy to use.

Include files (Library) Many languages use include files, and this is usually done at the top of the
program code. Include files contain some information that the program needs to know in order
to run the code contained in the program. For example, <stdio.h>, <conio.h>, <math.h> etc.

<stdio.h>: If you are using printf() and scanf() in your program, you will use <stdio.h> header file.
<conio.h>: If you are using getche() in your program, you will use <conio.h> header file.
<math.h>: If you are using sqrt() and pow() in your program, you will use <math.h> header file.

For more info about header files click the link below.
https://fresh2refresh.com/c-programming/c-function/c-library-functions/

Function main: Function is a named block of code. Function “main” marks the beginning of the
main function where program execution begins. Every C program has a main function. The
remaining lines of the program form the body of the function which is enclosed in braces { } .

Syntax of function main:


void main(void)
{
: /*function body */
:
:
}

Structure of a C program
#include <stdio.h> /*includes library file “stdio” */
void main (void) /*main starting point of the program */
{
: /*statements and variables here */
:
:
}

The output function: printf() : We use printf in our programs to display information on the screen.
printf() function is defined in <stdio.h>

Example01 :

#include <stdio.h> /*includes library file “stdio” */


void main (void) /*main starting point of the program */
{
printf("Hello World"); /*displays Hello World on screen */
}

Task 01: ::

Write a program that prints Welcome (Your Full Name) on output screen.
Escape Sequences:

Example02

#include <stdio.h>
void main(void)
{
printf("\n\t****************************\t");
printf("\n\t/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\");
printf("\n\t****************************\t");
printf("\n\t\"Programming Fundamentals\"\t");
printf("\n\t\tWelcome to C\t");
printf("\n\t****************************\t");
printf("\n\t/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\/\\");
printf("\n\t****************************\t");
}

Task02
Write a program to print the given menu
Variable: Variable is a container which holds some value, a variable in programming is a
named memory location on which we store a value which we are going to use in our
program. Variable names should be meaningful.

Variable declaration and Datatypes:


The following table shows the basic data types in C.

Placeholder Placeholder
Data Type C Keyword Bytes Range
(printf) (scanf)
Character char 1 (–128 - 127) %c %c
Integer int 4 –2,147,483,648 to %d %d
2,147,483,647
Floating Point float 4 3.4E-38 to %f %f
3.4 E38

The input function scanf():


The scanf function copies into memory data typed at the keyboard by the program user
during program execution. The format string is a quoted string of placeholders, one
placeholder for each variable in the input list. Each int, float or char variable in the input list
is preceded by an ampersand (&). Commas are used to separate variable names. The order
of the placeholders must correspond to the order of the variables in the input list.
You must enter data in the same order as the variables in the input list.

Declaring and Operating Integer Variables

Example03: Asking user to type in his/her age, and displaying his/her age with a message.

# include <stdio.h>
void main (void)
{
int age;
printf("Enter your age =");
scanf("%d",&age);
printf("\nYour age = %d",age);
}

Task03:
Ask user to enter the value of a variable (say ‘x’) and display output as
“You have entered x = ____)

Example04: Calculating product of two numbers.


Pseudo Code:
1. Input firstNum
2. Input secNum
3. prod = firstNum*secNum
4. Output product
#include <stdio.h>
void main (void)
{
int firstNum, secNum, prod; /*Declaring variables*/

printf("Enter first number ="); /*Reading input in firstNum*/


scanf("%d",&firstNum);

printf("\nEnter second number ="); /*Reading input in secNum*/


scanf("%d",&secNum);

prod = firstNum * secNum /*assigning result of RHS to LHS


(prod)*/

printf("\n\nProduct of given numbers = %d", prod); /*print value of variable prod*/


}

Task 04: Read sides length of a rectangle and calculate the area of that rectangle. Write pseudo code
first, then convert it into code.

Declaring and Operating Character and Floating-point Variables

Example 05: Taking float and character values as input and displaying output using
placeholders. It also prints ASCII value of the character.

The ASCII Code


Printing a char variable using “%c” will print the character but printing it with “%d” will print the
ASCII code. Similarly, printing an integer variable with “%c” will also print the character provided
the value is within the range of characters. The following example demonstrates this.

#include <stdio.h>
void main (void)
{
float fpNum; /*Declaring floating point variable called fpNum*/
char alpha; /*Declaring character type variable called alpha*/

printf("\nEnter a character ="); /*Reading input in alpha*/


scanf("%c",&alpha);

printf("The ASCII value of %c = %d\n",alpha,alpha); /*print alpha’s character value and ASCII value*/

printf("\nEnter a number ="); /*Reading input in fpNum*/


scanf("%f",&fpNum);
printf("You have typed = %f",fpNum); /*print fpNum’s float value*/
}

Task 05: Write a program to ask user for a character input, program will print the ASCII
code of the character.
Some Notes About printf:
• The stuff that you write inside the double quotes will appear on the screen, with some
exceptions: a %d will be replaced by an integer, a %c will be replaced by a character, \n will
print new line, etc.

• Make sure you use the right format specifier or placeholder [%d for int, %c for char, %f for
float] in your printf statements! Weird things will happen if you don't.

The input function getche( ):


Scanf() function has one weakness i.e. you need to type a [Return] before the function will
digest what you have typed. But we often need a function that will read a single character
the instant it is typed, without waiting for [Return].
We can use getche() function for this purpose. The “get” means it gets something from the
outside world. The “ch” means a character and “e” means it echoes the character to the
screen when you type it.

Example06: Input a character and print it.

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

void main (void)


{
char ch; /*Declaring character type variable called ch*/

printf("Enter a character ="); /*Reading input */


ch = getche( ); /*Assigning the value of getche( ) to ch */

printf("\nThe character you type = %c",ch); /*print ch’s character value */


}

Example07: Sqare Root in C Programming Example.

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

void main()
{
float number, sqrtValue; /*Declaring float type variables called number,sqrtValue*/

printf(" Please Enter any Numeric Value : "); /*Reading input in number*/
scanf("%f", &number);

sqrtValue = sqrt(number); /*Assigning the value of sqrt(number) to sqrtValue */

printf("\n The Square Root Value of %f = %f ", number, sqrtValue); /*print number, sqrtValue
value */
}
Example08: Power in C Programming Example.

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

void main (void)


{
int power; /*Declaring int type variable called power*/
int value=3; /*Initializing value to 3*/

power = pow(value,2); /*Assigning the value of pow( ) to power */

printf("The square of %d = %d",value,power); /*print values of value,power */


}

ASCII TABLE

This table lists the ASCII characters and their decimal, octal and hexadecimal numbers. Characters
which appear as names in parentheses (e.g., (nl)) are non-printing characters. A table of the common
non-printing characters appears after this table.

Lab Assignment 03
Write a C program to print the following lines.

Problem 01
Write a program to read the distance between two cities (in km.) and convert the distance into
meters and feet.

Data Requirements

Input
float kmDistance /* Distance in kilometers*/
Output
float meterDistance /* Distance in meters */
float feetDistance /* Distance in feet */

Relevant Formulae
1 km = 1000 meters
1 km = 3280.84 feet

Sample Output:

Problem 02
Write a program that calculates the acceleration (m/s2) of a jet fighter launched from an aircraft
carrier, given the jet’s takeoff speed in m/s and the distance (meters). The jet starts from rest to
takeoff. Also calculate the time (seconds) for the fighter to be accelerated to takeoff speed.

Data Requirements

Input
float velocity /* velocity of the jet */
float distance /* distance covered by the jet */

Output
float acceleration /* acceleration of the jet fighter*/
float time /* Time for the fighter to accelerate to takeoff speed */

Relevant Formula
𝑆 = 𝑣𝑡
2𝑎𝑆 = 𝑣 2

where v = velocity, a = acceleration, t = time, S = distance

Sample Output:

Problem 03
Write a program to convert a temperature in degrees Fahrenheit to degrees Celsius.

Data Requirements

Input
float Fahrenheit /* temperature in degrees Fahrenheit */
Output
float Celsius /* temperature in degrees Celsius */
Relevant Formula
Celsius = 5/9 (Fahrenheit − 32)
Sample Output:

Problem 04
Write a program to find out the roots of a Quadratic Equation using sqrt( ) and pow( ) function.

Data Requirements

Input
int a = 1, b = 5, c = 4 /* values of constants of Quadratic Equation */
Output
int x1, int x2 /* values of roots of Quadratic Equation */
Relevant Formula
−𝑏 + √𝑏2 − 4𝑎𝑐
𝑥1 =
2𝑎
−𝑏 − √𝑏2 − 4𝑎𝑐
𝑥2 =
2𝑎
Sample Output:

Lab Assignment Submission Instructions:


1. Number your files as question number e.g. Q1.c, Q2.c, etc. (Q is in upper case)
2. Create a new folder named cs191abc where abc is your 3 digit roll #. e.g. cs191001.
3. Copy all the scratch files into this folder.
4. Right-click on the folder you created and create a zip file by selecting the option
• “Send to” and selecting “Compressed (zipped) folder” [for windows].
• “Create Archive” and change option to “.zip” instead of “.tar.gz” and click on
“Create”. [for linux]
Now make sure a zip file named cs191abc.zip is created e.g. cs191001.zip.
5. (A) Compose a new email, attach this zip file and send email to usman.khalil@dsu.edu.pk
• The subject of the email must be:

1A1-Lab03-cs191abc where 1A1 is the section you’re enrolled in (remember to write


your lab section not just 1A or 1B) and abc is your 3 digit unique roll#.
1A1-Lab03- cs191001
(B) The body of the email must contain:
Full Name
DSU Roll #
Section
Lab Number #
6. To double check whether your assignment was submitted or not make sure the Sent
Items folder of your email account contains the email you just sent.

You might also like