[go: up one dir, main page]

0% found this document useful (0 votes)
7 views10 pages

Lab Sheet-1 Basics of C Programming

The document provides an overview of programming languages, categorizing them into machine languages, assembly languages, and high-level languages, with a focus on C as a middle-level language. It outlines the phases of C program development, including editing, preprocessing, compiling, linking, loading, and execution, along with examples of simple C programs. Additionally, it includes lab assignments for students to practice coding in C and addresses common syntax errors in C programming.

Uploaded by

shubhlahoti.896
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)
7 views10 pages

Lab Sheet-1 Basics of C Programming

The document provides an overview of programming languages, categorizing them into machine languages, assembly languages, and high-level languages, with a focus on C as a middle-level language. It outlines the phases of C program development, including editing, preprocessing, compiling, linking, loading, and execution, along with examples of simple C programs. Additionally, it includes lab assignments for students to practice coding in C and addresses common syntax errors in C programming.

Uploaded by

shubhlahoti.896
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/ 10

Programming for Problem Solving (CS1010) LAB-1

[Reference: Paul Deitel and Harvey Deitel, C How to Program, 7th Ed., Pearson Education, 2013]

Programmers write instructions in various programming languages, some directly understandable by computers and
others requiring intermediate translation steps. Hundreds of computer languages are in use today. These may be
divided into three general types:
1. Machine languages
2. Assembly languages
3. High-level languages

Machine Language: Any computer can directly understand only its own machine language. Machine language is the
“natural language” of a computer and as such is defined by its hardware design.
[Note: Machine language is often referred to as object code.]
Machine languages generally consist of strings of numbers (ultimately reduced to 1s and 0s) that instruct computers
to perform their most elementary operations one at a time. Machine languages are machine dependent (i.e., a
particular machine language can be used on only one type of computer). Such languages are cumbersome for
humans. An example of machine-language program that adds overtime pay to base pay and stores the result in gross
pay:
+1300042774
+1400593419
+1200274027

Assembly languages: Machine-language programming was simply too slow, tedious and error prone for most
programmers. Instead of using the strings of numbers that computers could directly understand, programmers
began using English-like abbreviations to represent elementary operations. These abbreviations formed the basis of
assembly languages. Translator programs called assemblers were developed to convert early assembly-language
programs to machine language at computer speeds. Following assembly-language program also adds overtime pay
to base pay and stores the result in gross pay:
load basepay
add overpay
store grosspay

High-level Language: To speed the programming process, high-level languages were developed in which single
statements could be written to accomplish substantial tasks. Translator programs called compilers convert high-level
language programs into machine language. High-level languages allow programmers to write instructions that look
almost like everyday English and contain commonly used mathematical notations. A payroll program written in a
high-level language might contain a statement such as
grossPay = basePay + overTimePay;

The process of compiling a high-level language program into machine language can take a considerable amount of
computer time. Interpreter programs were developed to execute high-level language programs directly (without the
delay of compilation), although slower than compiled programs run.
C Is a Middle-Level Language [Ref: Herbert Schildt: C-The Complete Reference]
C is often called a middle-level computer language. C is thought of as a middle-level language because
it combines the best elements of high-level languages with the control and flexibility of assembly
language. As a middle-level language, C allows the manipulation of bits, bytes, and addresses— the
basic elements with which the computer functions.
Despite this fact, C code is also very portable. Portability means that it is easy to adapt software written
for one type of computer or operating system to another type. For example, if you can easily convert a
program written for DOS so that it runs under Windows 2000, that program is portable.

C does not demand strict type compatibility between a parameter and an argument. As you may know
from your other programming experience, a high-level computer language will typically require that the
type of an argument be (more or less) exactly the same type as the parameter that will receive the
argument. C is special in that it allows the direct manipulation of bits, bytes, words, and pointers. This
makes it well suited for system-level programming, where these operations are common.

C Is a Structured Language
The distinguishing feature of a structured language is compartmentalization of code and data. This is
the ability of a language to section off and hide from the rest of the program all information and
instructions necessary to perform a specific task. One way that you achieve compartmentalization is by
using subroutines that employ local (temporary) variables. By using local variables, you can write
subroutines so that the events that occur within them cause no side effects in other parts of the program.
This capability makes it very easy for your C programs to share sections of code. If you develop
compartmentalized functions, you need to know only what a function does, not how it does it.
Remember, excessive use of global variables (variables known throughout the entire program) may
allow bugs to creep into a program by allowing unwanted side effects. (Anyone who has programmed
in standard BASIC is well aware of this problem.)
A structured language offers a variety of programming possibilities. For example, structured languages
typically support several loop constructs, such as while, do-while, and for. In a structured language, the
use of goto is either prohibited or discouraged and is not the common form of program control (as is
the case in standard BASIC and traditional FORTRAN, for example). A structured language allows you
to place statements anywhere on a line and does not require a strict field concept (as some older
FORTRANs do).

Standard Libraries: C programs consist of modules or pieces called functions. C programmers take advantage of a
rich collection of existing functions called the C Standard Library. Use existing pieces—this is called software
reusability.
Typical C Program Development Environment
C programs typically go through six phases to be executed as shown in Fig. 1.1. These are: edit, preprocess, compile,
link, load and execute.

Phase 1: Creating a Program


Linux based systems: Phase 1 consists of editing a file. This is accomplished with an editor program. Two editors
widely used on Linux systems are vi and emacs.
Window OS based systems: Write your C program with the notepad and save the file with the extension “.c”.
You can also use various software packages for the C/C++ integrated program development environments such as
Eclipse and Microsoft Visual Studio have editors that are integrated into the programming environment.

Phases 2 and 3: Preprocessing and Compiling a C Program


The compiler translates the C program into machine language-code (also referred to as object code). In a C system, a
preprocessor program executes automatically before the compiler’s translation phase begins.
The C preprocessor obeys special commands called preprocessor directives, which indicate that certain
manipulations are to be performed on the program before compilation.
These manipulations usually consist of including other files in the file to be compiled and performing various text
replacements.
In Phase 3, the compiler translates the C program into machine-language code.

Phase 4: Linking
C programs typically contain references to functions defined elsewhere, such as in the standard libraries or in the
private libraries of groups of programmers working on a particular project. The object code produced by the C
compiler typically contains “holes” due to these missing parts. A linker links the object code with the code for the
missing functions to produce an executable image (with no missing pieces).

The command to compile and link a program is


Gcc FileName.c
If the program compiles and links correctly, a file called a.out is produced. This is the executable image
of our FileName.c program.

gcc filename -o outputfile: can be used to specify the name of the output file instead of default name

Phase 5: Loading
The next phase is called loading. Before a program can be executed, the program must first be placed in memory
(Main memory/RAM). This is done by the loader, which takes the executable image from disk and transfers it to
memory. Additional components from shared libraries that support the program are also loaded.

Phase 6: Execution
Finally, the computer, under the control of its CPU, executes the program one instruction at a time. To load and
execute the program type
a at windows command prompt Object filename and press Enter
./a.out at the Linux prompt and press Enter.

A syntax error is caused when the compiler cannot recognize a statement. The compiler normally issues an error
message to help you locate and fix the incorrect statement. Syntax errors are violations of the language. Syntax
errors are also called compile errors, or compile-time errors.
Installation of GCC compiler for windows:
Please follow the steps mentioned at the https://dev.to/gamegods3/how-to-install-gcc-in-windows-10-the-easier-
way-422j

A Simple C Program: Printing a Line of Text


/* First.c A first program in C */
#include <stdio.h>
int main( void ) /* function main begins program execution */
{
printf( "Welcome to C!\n" );
return 0; /* indicate that program ended successfully */
} /* end function main */

Comment: Line begins with /* and end with */ indicating that these two lines are a comment. You insert comments
to document programs and improve program readability. Comments are ignored by the C compiler and do not cause
any machine-language object code to be generate.

#include <stdio.h>: a directive to the C preprocessor. Lines beginning with # are processed by the preprocessor
before the program is compiled. This Line tells the preprocessor to include the contents of the standard
input/output header (<stdio.h>) in the program. This header contains information used by the compiler when
compiling calls to standard input/output library functions such as printf.

int main( void ): is a part of every C program. The parentheses after main indicate that main is a program building
block called a function. Every program in C begins executing at the function main and hence every C program must
contain main. Functions can return information. The keyword int to the left of main indicates that main “returns” an
integer (whole number) value. We’ll understand what it means for a function to “return a value” when we
demonstrate how to create your own functions at a later stage. For now, simply include the keyword int to the left of
main in each of your programs. Functions also can receive information when they’re called upon to execute. The void
in parentheses here means that main does not receive any information, although we can pass on information to
main which will be discussed at a later stage.

{ }: A left brace, {, begins the body of every function and a corresponding right brace ends each function. This pair of
braces and the portion of the program between the braces is called a block.

printf( "Welcome to C!\n" ); :instructs the computer to perform an action, namely to print on the screen the
string of characters marked by the quotation marks. A string is sometimes called a character string, a message or a
literal. The entire line, including printf, its argument within the parentheses and the semicolon (;), is called a
statement.
Every statement must end with a semicolon (also known as the statement terminator). When the preceding printf
statement is executed, it prints the message Welcome to C! on the screen.
Notice that the characters \n were not printed on the screen. The backslash (\) is called an escape character. The next
character following with the backslash forms an escape sequence. The escape sequence \n means newline. When a
newline appears in the string output by a printf, the newline causes the cursor to position to the beginning of the next
line on the screen.
Some common escape sequences are as follow:
return 0; /* indicate that program ended successfully */

Another Simple C Program: Adding Two Integers


Our next program uses the Standard Library function scanf to obtain two integers typed
by a user at the keyboard, computes the sum of these values and prints the result using
printf. The program and sample output are shown in Fig. 2.8. [In the input/output dialog
of Fig. 2.8, we emphasize the numbers input by the user in bold.]

/* Prog2.c Addition program */


#include <stdio.h>
int main( void ) /* function main begins program execution */
{
int integer1; /* first number to be input by user */
int integer2; /* second number to be input by user */
int sum; /* variable in which sum will be stored */
printf( "Enter first integer\n" ); /* prompt */
scanf( "%d", &integer1 ); /* read an integer */
printf( "Enter second integer\n" ); /* prompt */
scanf( "%d", &integer2 ); /* read an integer */
sum = integer1 + integer2; /* assign total to sum */
printf( "Sum is %d\n", sum ); /* print sum */
return 0; /* indicate that program ended successfully */
} /* end function main */
OUTPUT:
Enter first integer
45
Enter second integer
72
Sum is 117

int integer1; /* first number to be input by user */


int integer2; /* second number to be input by user */
int sum; /* variable in which sum will be stored */
are definitions. The names integer1, integer2 and sum are the names of variables. A variable is a location in memory
where a value can be stored for use by a program. These definitions specify that the variables integer1, integer2 and sum
are of type int, which means that these variables will hold integer values, i.e., whole numbers such as 7, –11, 0,
31914 and the like. All variables must be defined with a name and a data type immediately after the left brace that
begins the body of main before they can be used in a program.
There are other data types besides int in C. The preceding definitions could have been combined into a single
definition statement as follows:

int integer1, integer2, sum;

A variable name in C is any valid identifier. C is case sensitive—uppercase and lowercase letters are different in C, so
a1 and A1 are different identifiers.

scanf( "%d", &integer1 ); /* read an integer */


scanfis used to obtain a value from the user. The scanf function reads from the standard input, which is usually the
keyboard. This scanf has two arguments, "%d" and &integer1.
The first argument, the format control string, indicates the type of data that should be input by the user. The %d
conversion specifier indicates that the data should be an integer (the letter d stands for “decimal integer”). The % in
this context is treated by scanf (and printf as we’ll see) as a special character that begins a conversion specifier.
The second argument of scanf begins with an ampersand (&)—called the address operator in C— followed by the
variable name. The ampersand, when combined with the variable name, tells scanf the location (or address) in
memory at which the variable integer1 is stored. The computer then stores the value for integer1 at that location. The
use of ampersand (&) is often confusing to novice programmers or to people who have programmed in other
languages that do not require this notation. For now, just remember to precede each variable in every call to scanf
with an ampersand.
When the computer executes the preceding scanf, it waits for the user to enter a value for variable integer1. The user
responds by typing an integer, then pressing the Enter key to send the number to the computer. The computer then
assigns this number, or value, to the variable integer1. Any subsequent references to integer1 in this program will use
this same value. Functions printf and scanf facilitate interaction between the user and the computer. Because this
interaction resembles a dialogue, it is often called conversational
computing or interactive computing.

printf( "Sum is %d\n", sum ); /* print sum */

calls function printf to print the literal Sum is followed by the numerical value of variable sum on the screen. This printf has
two arguments, "Sum is %d\n" and sum. The first argument is the format control string. It contains some literal
characters to be displayed, and it contains the conversion specifier %d indicating that an integer will be printed. The
second argument specifies the value to be printed. Notice that the conversion specifier for an integer is the same in
both printf and scanf. This is the case for most C data types.
Lab Assignment-1
Q. 1 Write a C code to perform the following and print it:
(a.) Addition, subtraction, multiplication, and division of two integers: 25 and 56

Q. 2 Write a C code to determine the sum of following series (without loop)

12 + 32 +52 + 92

Q. 3 Write a C program two swap a two numbers using temporary variable and without temporary
variable.

Q. 4 Explain the C Program’s life cycle? Mention the location and name of the files created in the life
cycle for your executed program.

Q.5 Write down the warnings and error shown by the compiler and correct the errors in each of the
following statements. (Note: There may be more than one error per statement.)
a) scanf( "d", value );
b) printf( "The product of %d and %d is %d"\n, x, y );
c) firstNumber + secondNumber = sumOfNumbers
e) printf(“Hello”) */ Program to determine the largest of three integers /*
f) Scanf( "%d", anInteger );
g) printf( "Remainder of %d divided by %d is\n", x, y, x % y );
i) print( "The sum is %d\n," x + y );
j) Printf( "The value you entered is: %d\n, &value );
Memory Concepts
Variable names such as integer1, integer2 and sum actually correspond to locations in the computer’s memory. Every
variable has a name, a type and a value. In the addition program, when the statement

scanf( "%d", &integer1 ); /* read an integer */

is executed, the value typed by the user is placed into a memory location to which the name integer1 has been
assigned. Suppose the user enters the number 45 as the value for integer1. The computer will place 45 into location
integer1 as shown in Fig.
Whenever a value is placed in a memory location, the value replaces the previous value in that location;
Returning to our addition program again, when the statement

scanf( "%d", &integer2 ); /* read an integer */

executes, suppose the user enters the value 72. This value is placed into location integer2, and memory appears as
shown in Fig. These locations are not necessarily adjacent in memory.
Once the program has obtained values for integer1 and integer2, it adds these values and places the sum into variable
sum. The statement

sum = integer1 + integer2; /* assign total to sum */

that performs the addition also replaces whatever value was stored in sum. This occurs when the calculated sum of
integer1 and integer2 is placed into location sum (destroying the value already in sum). After sum is calculated, memory
appears as shown in Fig. The values of integer1 and integer2 appear exactly as they did before they were used in the
calculation. They were used, but not destroyed, as the computer performed the calculation.
[ref: https://www.programiz.com/c-programming/c-keywords-identifier]
C Keywords
Keywords are predefined, reserved words used in programming that have special meanings to the compiler.
Keywords are part of the syntax and they cannot be used as an identifier. For example:
int money;
Here, int is a keyword that indicates money is a variable of type int (integer).
As C is a case sensitive language, all keywords must be written in lowercase. Here is a list of all keywords
allowed in ANSI C.

C Keywords
auto double int struct
break else long switch
case enum register typedef
char extern return union
continue for signed void
do if static While
default goto sizeof Volatile
const float short Unsigned

All these keywords, their syntax, and application will be discussed in their respective topics. However, if you
want a brief overview of these keywords without going further, visit List of all keywords in C programming.

C Identifiers
Identifier refers to name given to entities such as variables, functions, structures etc. Identifiers must be unique.
They are created to give a unique name to an entity to identify it during the execution of the program. For
example:
int money;
double accountBalance;
Here, money and accountBalance are identifiers.
Also remember, identifier names must be different from keywords. You cannot use int as an identifier
because int is a keyword.

Rules for naming identifiers


• A valid identifier can have letters (both uppercase and lowercase letters), digits and underscores.
• The first letter of an identifier should be either a letter or an underscore.
• You cannot use keywords like int, while etc. as identifiers.
• There is no rule on how long an identifier can be. However, you may run into problems in some
compilers if the identifier is longer than 31 characters.
• You can choose any name as an identifier if you follow the above rule, however, give meaningful names
to identifiers that make sense.

EXAMPLES:
Correct Incorrect
count 1count
test23 hi!there
high_balance high . . . balance

You might also like