Free Essay

C Programming

In:

Submitted By taiweikoh
Words 3795
Pages 16
C PROGRAMMING
Section 1.
Topics: Functions Statements Input Output Variables

Introduction

The C programming language has been the most popular high level language used for engineering applications for the last 20 years. It shares many common structures with other procedural languages, such as Pascal, and can be used for general purpose programming of a PC. However, it is also particularly good for development of embedded application programs such as those found in phones, video recorders and so forth. The term procedural language refers to the fact that the language uses procedures to do particular tasks such as printing on the screen. In C these procedures are known as functions and are described below.

What is so good about a language like C? The basic reason such languages were developed was to make it easier for humans to program computers. The alternative is the language of the computer, i.e., binary codes. Clearly such ‘low-level’ languages are not very appealing for humans, although sometimes necessary for detailed engineering work. (In fact C is often ‘mixed’ with such languages for engineering applications.)

C uses words and symbols that are part of, or similar to, normal language. This makes it easier for programmers to develop code. The C code is converted to the machine code by a special program called a compiler. See note 1. But perhaps the most useful thing about such a language is that it provides the developer with a library of ‘mini-programs’, the functions/procedures someone else has written, thereby allowing the programmer to concentrate on developing his own particular application programs.

Note 1 Typically the code entered by the programmer, known as the source code, is saved in a file with the extension .C . For instance, a program to monitor temperature might be saved in file called tempcont.c . When the compiler produces the machine code it is saved in a file with the same name but the extension is exe (executable) Thus the file tempcont.exe contains the code that the computer requires to execute the program that was written in the file tempcont.c.
The ’mini-programs’ are called functions because they do some function! For instance sound(1000); is the function to make a PC generate a sound (a single tone) at 1000 Hertz. In this example the number in the brackets sets the frequency of the sound. The technical way of describing this is that 1000 is a parameter of the function. This value must be a whole number (integer). The above example is a ‘line of code’ in a C program and referred to as a statement.

A programmer creates his own functions based mainly on the library functions supplied and a few other structures for making decisions and so forth. The following is an example of a user defined (written by the programmer) function called my_sounds

void my_sounds(void) { sound(500); /* make a sound at 500 Hz.*/ delay(2000); /* pause for 2000 milliseconds = 2 seconds */ sound(1000); delay(2000); sound(1500); delay(2000); sound(2000); delay(2000); nosound(); /* turn off sound */ }

The functions used in this example are explained with comments. These are the explanatory pieces of text between /* and */. It is very important to explain (document) the program in this way. It will be easier to understand when it is re-read. The little bit of effort required to add comments can save a lot of time in the long run and is considered as much a part of programming as the C code.

Before the above program can be compiled into executable machine code and run, some necessary additional code must be added. The details about this are not too important at present. A complete program is shown below and explained using comments.

Note 2 Sometimes I will use comments to explain new concepts. This will not be the case in your programs. Your comments should explain what the code is doing at a particular point in the program, particularly if it is a bit complicated. Clearly some things are fairly obvious and may not need a detailed explanation, e.g., what the sound function does. However, most of the user-defined functions need clear concise comments to explain their task and how it is implemented. The comments at the start of the following program should always be present

/**********************************************************************/
/*Title: C program to make sounds (sound1.c) */
/**********************************************************************/
/*Developer: A.C. Programmer 20-10-2000 */
/**********************************************************************/
/*Description: This program uses the sound() function and delay() functions to */
/* demonstrate a simple C program */
/**********************************************************************/
#include /* a special header file that is needed when using the */ /* sound function and so forth */ void my_sounds(void); /* this ‘warns’ the compiler that a ‘new’ user defined */ /* function will appear later- the technical term for this */ /* statement is function prototype and is basically a copy */ /* the first line of the user-defined function */

main() /*All C programs have a main function body */
{ /* the user defined functions are ‘called’ from the main */ my_sounds(); /* function as shown on this line. The ‘calling’ statement */ /* is simply the function name followed by a semi-colon */
} /*The curly braces are used to‘group together’ statements*/ /* inside a function body */
/*-------------------------------------------------------------------------------------------------------*/
/* The my_sound function ………../* void my_sounds(void) { sound(500); /* make a sound at 500 Hz.*/ delay(2000); /* pause for 2000 milliseconds = 2 seconds */ sound(1000); delay(2000); sound(1500); delay(2000); sound(2000); delay(2000); nosound(); /* turn off sound */ }
It would be possible to write all the statements in the my_sounds() function in the main function. However, we shall only use the main function to ‘call’ other functions or for some special sections of code. Why not use the main function?. The principle reason not to use main is to ensure that the program is ‘broken up’ into smaller functions. This is called modular programming and makes it easier to design and understand programs. This is a subject we shall return to at a later stage.

Interactive programs

The previous example program does not allow the user to interact with the computer. For instance it would be interesting to permit the user to select the frequency of the sound and the duration of the delay. To do this 3 extra tasks arise:

1. Output a request to the screen seeking the user to enter values 2. Input values from the keyboard 3. Store these values in the system memory for use later (by the functions sound and so forth)

Output

To output something to the screen the most common function is printf(). The easiest way to start using printf is with a ‘string of characters’ such as

Please enter your frequency selection (

To do this simply enclose the above text in quote marks “like this”, to indicate a string of text to the compiler, and write this between the brackets as shown below

printf(“Please enter your frequency selection ”);

Note how many functions have something between the brackets, the parameters which the function uses. Also, the ever present semi-colon which terminates the statement. The printf function always has something between quote marks “……” and this is called the format string. Further details about printf later. However, there is one extra item that must be learned now. How do you print on a new line and not just follow the previous piece of text on the same line? An escape sequence, which is written inside the format string as \n, .is used. For instance,

printf(“\n\n Now enter the duration of the delay (”);

In this case the two \n sequences cause 2 blank lines to be ‘printed’ before the text starts. Note that the \n appears inside the quote marks. Omitting the quotation marks or the semi-colon at the end of a statement, are the two most likely sources of errors for programming students.

To use printf() it is necessary to include details from a special ‘header file’ called stdio.h. The stdio is an abbreviation of standard input/output. This is written at the start (as in the example which used the dos.h file also) as follows: #include
More details about this later.
Storage (variables)

Before discussing input, we shall consider the storage of data. If a number, or any other form of data, is read in from the keyboard, then there must be some place to store this data. (Physically this is the RAM memory in the system). In order to save data in memory the program must ‘reserve’ some space in the memory and give it a name. This is described as declaring a variable.

You are already familiar with the notion of variables from mathematics, for instance, Y=3X+4
The value of Y depends on the value of X, which may be whatever we choose, i.e., it is variable. In a computer a variable is much the same. It is a memory location(s) that can hold (store) data and its contents may be changed (variable). However, variables can store more than just numbers. For instance they can be used to store text. When declaring a variable it is necessary to indicate what type of “data” is to be stored in it and give it an identifier (name). Declarations of variable appear in the start of functions. For the sound() and delay() functions the parameters are integer values (whole numbers). Thus, a possible declaration for the two variable required might be

/*declarations of variables */

int frequency,duration; /*The words ‘freqency’and ‘duration’*/ /* are the names (identifiers) of the variables*/

In the above example the computer is instructed to reserve memory locations and identify them with the names (identifiers) frequency and duration. Also, the type of data to be stored is specified with the abbreviation int, which is short for integer. (The computer reserves a certain amount of memory depending on the particular data type). A more detailed description of variables will be given at a later stage, but note that the most common type specifier for numbers is the word float. (As in the case of floating point, or decimal point, real numbers – not just whole numbers).
If a variable can store data then there must be a way of ‘loading’ that variable. One way is to use the assignment operator (the equal symbol = ) to assign a value in the way a mathematical expression is constructed

frequency=1000; sound(frequency);

In the two lines of code above the variable frequency is assigned the value 1000 and this is then the frequency of the tone generated by the sound function. But we want the person running the program to select the frequency. Thus we must consider how to input data from the keyboard.

input

For interactive input the most common function is scanf(), the input equivalent of printf(). Similarly to printf() it uses a string, the format string, to input the data from the keyboard. The term format relates to how data is treated for either output to the screen or input from the keyboard. Format specifiers are described in detail later. However, a simple way to understand them is to consider the difference between an ‘int’ such as 2 and a ‘float’ such as 2.0. If someone enters a ‘2’ character at the keyboard, they may want it to be treated as either one or other of the above (or even as something else!). The format specifier is used to specify which format is to be used. For instance, %f means treat it as a float and %d means treat it as an integer (decimal- hence the d).

Thus, for the my_sound function a possible input statement would be

scanf(“%d”,&frequency);

The “%d” is the format string and &frequency indicates where the input (the integer value) is to be stored. There is a particular significance in the & symbol but for the moment simply treat it as meaning ‘at’. (Store input at variable location frequency).
A single statement can read more than 1 input. A space or return is required between each input. The general format for the scanf() function is

scanf (“format string”,&var1,&var2,…)

notice the commas separating the various items in the brackets.

example scanf(“%d %d”, &data_1, &data_2);

This call tells the program that it expects you to type in two decimal (integer) values separated by a space; the first will be assigned to variable data_1 and the second to the variable data_2.

Exercise 1

Modify the the my_sounds() function to do the following

1. Declare int variables for frequency and duration 2. Request the user to select a frequency for the first tone and the duration of the delay. 3. let each subsequent tone be 100Hz higher value than the first tone with the same duration as the first tone, e.g., sound(frequency+100);

Note the use of the addition operator described in the next section..

Operators

The assignment operator was introduced earlier in relation to storing data in variables. As you might expect there are plenty of operators for manipulating variables. To begin with we shall note the common arithmetic operators and introduce others, such as Boolean, as we require them. A full table of operators will be provided later.

= assignment + addition - subtraction * multiplication / division % remainder (applies to integer division)

The usual arithmetic rules for precedence and the use of brackets apply. If integers are divided then the result is also an integer or zero.

Examples

res_total = res_1+res_2+res_3;

the 3 ‘res’ variables store resistance values entered by a person. The series equivalent resistance of the 3 is calculated and assigned to the res_total variable.

Note: a variable name cannot have a space in it. Thus in the above example to give the impression of a space, and make the name easier to read, an underscore symbol is used.

average_age = (age_1+age_2+age_3)/3;

in the above example the 3 ‘age’ variables contain the numbers associated with the ages of 3 people. The average is calculated and assigned to the variable average_age. Because division has a higher precedence than addition, the brackets are used.

Exercise 2

Write a function to request the user to input 2 values corresponding to resistance values and which then does the following

1. calculates the series equivalent resistance 2. calculates the parallel equivalent resistance 3. outputs both results to the screen.

Checkout the detailed description of printf() to see how to print the results..

NOTE 2: Printf function in detail

You’ve already used the most common output function in C, printf(). Its format is both simple and flexible: printf(,,,…);

The Format String

The format string begins and ends with double quotes (“like this”)and printf’s function is to write that string to the screen. First, though, printf substitutes any additional items listed into the string, according to the format commands found in the string itself. For example, your last exercise program may have had the following printf statement:

printf(“The series resistance is %f \n”,series_res);

The %f in the format string is a format specification. All format specifications start with a percent sign (%) and are (usually) followed by a single letter, indicating the type of data and how the data is to be formatted. (Remember in the computer the data is in a binary format and that format is not much good for humans).
You should have exactly one item listed for each format specification. The items themselves can be variables, constants, expressions, function calls. In other words anything that results in a value appropriate to the corresponding format specification.

The %f used in this specification means that a float is expected. The most common format specifications are listed below

- %u (unsigned integer) - %f (floating point) - %e (floating point in exponential format) - %c (single character) - %s (string) - %x or %X (integer in hexadecimal format)

e.g. printf(“The average age is %d”,average_age);

You may have noticed that when printing a value stored in a ‘float’ with %f, a number of decimal places are printed, 6 in all. If you wish to set the total number of characters printed, the field width, and the number of decimal place digits, then you may do this as follows by inserting details between the % and f of the format specifier.

%.f

For instance for a width of 6 and 2 decimal place the earlier example would be

printf(“The series resistance is %6.2f \n”,series_res);

If there are not enough characters (including the decimal place) to fill the width then the value will then be printed out right-justified (with leading blanks), so that the total field width is 6.

If you need to print a percent sign, just insert %%.

As described earlier the \n in the string is an escape sequence not a format specification. It represents a special character inserted into the string. In this case, the \n inserts a newline character, so that after the string is written out, the cursor moves to the start of a new line.

Some of the common escape sequences are listed

\f formfeed or clear screen \t tab \b backspace \n newline -

NOTE 3: Other common screen and keyboard functions

clrscr() puts() getch()

The clrscr() function is used to clear the screen. It requires the conio.h file to be included at the head of the program. The term conio refers to the phrase console input/output Most common functions are associated with the header files stdio.h, conio.h, dos.h, or math.h. Others will be mentioned as required.

The function puts(), as in put string, writes a string to the screen followed by a newline character automatically, without the requirement for the special escape sequence \n
.
For example, you could write

puts (“This is a simple string”);

Similarly the function putchar() writes a single character to the screen, although not commonly used.
For numeric output, or special formatting, printf is required. If only text is to be output then puts is a smaller and faster function and should be used in those cases.

Strings and characters are a particular data type which are described later. There is a variable type ‘char’ which is used for storing text This could be used with scanf(), and the character format specifier %c, to read in a character from the keyboard in the same way numbers may be read in. However, for text there is a simpler method using the getch() function. For example, .char reply; /* character variable */

reply = getch(); /* input from keyboard */

The getch() function causes the program to ‘wait’ for the user to press a character. This is then ‘returned’ and assigned to variable reply. A similar process is involved using gets() when a string of characters is to be entered. (Strings are not dealt with at this stage in detail).

A very useful function for getch() is to simply halt program execution to wait for the user to press a key. In effect it is a ‘pause’ waiting for the user. It will appear in a lot of future programs.

NOTE: 3 Further details about variables and data types

There are 4 basic types of data

integers, floating-point numbers, text, and pointers.

These can be defined as follows

Integers The ‘whole’ number used for counting and so forth (3, 55, -21, and 1052, for example).

Floating-point numbers –numbers with possible fractional portions after the decimal point (27.8976) and exponents (2.579*10^24). Also known as real numbers.

Text -characters (a,b,c…?,!,a and strings (“This is a string.”).

Pointers No details yet!!

Float Types

Most mathematical operations involve real/float numbers and unless required by a function, or for counting, then these should be used for storing numerical data. They occupy more memory space than an integer but this is not significant in modern computers. Typically 6 bytes for a float.

There’s also a large version of type float, known as double. As you might have guessed, variables of type double are twice as large as variables of type float. This means that they have more significant digits and a larger range of exponents. As an exercise determine the largest values that may be stored in these types for your system?

Integer Types

Although int type is sufficient for most purposes, if a very big integer is used then a long can be specified. An int occupies 2 bytes but a long occupies 4 bytes. Normally, we assume that the range of values spans positive and negative numbers. In the variable, the most significant bit represents the + or -. This is referred to as a signed number. It is possible to declare a variable to be ‘unsigned’, thus only positive values may be stored. As an exercise determine the largest numbers that may be stored in the different types of integer variables.

Examples

float var1; .double var2; int var3 long var4; unsigned int var5;

Characters and Strings

A character, such as those input from the keyboard, is a particular data type represented by a character code. This code is known as an ASCII (American Standard Code for Information Interchange) code. Like integer or float data values they may be stored in a variable. The variable is of type char

Example char var_a;

var_a = ‘c’ /* the code for the letter c is assigned to var_a */

Note that in the above example a single character code is ‘generated’ by enclosing the character between single quote marks ‘c’ . A character string, usually several characters, characters is generated between double quote marks. In fact a string consist of a special character called the null character \0 which is always at the end of a string and can be checked for. To store a string a special type character variable is required known as a character array. Consider the following example:

char name [30]; /*declaration of string variable*/

printf(“Enter you name ( “) scanf(“%s”,&name); /* characters stored in name*/
The [30] after name tells the compiler to set aside space for up to 29 characters, that is, an array of 29 char variables. (The 30th space will be filled by a null character. Because of this dependency on a null character, strings in C are known as being null terminated and can be any length, as long as there is enough memory to hold it.

Identifiers

There are restrictions on the identifiers (names) that can be used for variables, functions and other data types. In summary they are

- All identifiers must start with a letter (a…z or A…Z) or an underscore ( _ ).

- The rest of an identifier can consist of letters, underscores, and / or digits (0…9). No other characters are allowed.

- Identifiers are case-sensitive. This means that lowercase letters (a…z) are not the same as uppercase letters (A…Z). For example, the identifiers indx, Indx, and INDX are different and distinct from one another.

- The first 32 characters of an identifier are significant.

Similar Documents

Free Essay

C Programming

...Welcome to CS 241 Systems Programming at Illinois Robin Kravets Copyright ©: University of Illinois CS 241 Staff 1 The Team  Robin Kravets    TAs   Office: 3114 SC rhk@illinois.edu Wade Fagen, Farhana Ashraf, Hilfi Alkaff and Mainak Ghosh Discussion Sections   8 sessions (Thursdays 9, 10, 11, 12, 1, 2, 3, 4) All sections in SC 0220 Copyright ©: University of Illinois CS 241 Staff 2 News and Email  Announcements and discussions: Piazza  http://www.piazza.com/illinois/cs241     All class questions This is your one-stop help-line! Will get answer < 24 hours e-mail   cs241help-fa12@cs.illinois.edu Personal questions not postable on the news group Copyright ©: University of Illinois CS 241 Staff 3 The Textbook  Introduction to Systems Concepts and Systems Programming      University of Illinois Custom Edition Copyright © 2007 Pearson Custom Publishing ISBN 0-536-48928-9 Taken from:    Operating Systems: Internals and Design Principles, Fifth Edition, by William Stallings UNIX™ Systems Programming: Communication, Concurrency, and Threads, by Kay A. Robbins and Steven Robbins Computer Systems: A Programmer's Perspective, by Randal E. Bryant and David R. O'Hallaron Copyright ©: University of Illinois CS 241 Staff 4 Your CS 241 “Mission”  Come to class     Read textbook    20% 7:00 – 9:00 PM October 15th Final  3% 47% Longer MPs are worth a little more Midterm   Reading assignments posted on webpage Homework...

Words: 1748 - Pages: 7

Premium Essay

C++ Programming

...C++ PROGRAMMING: FROM PROBLEM ANALYSIS TO PROGRAM DESIGN FIFTH EDITION D.S. MALIK Australia  Brazil  Japan  Korea  Mexico  Singapore  Spain  United Kingdom  United States C++ Programming: From Problem Analysis to Program Design, Fifth Edition D.S. Malik Executive Editor: Marie Lee Acquisitions Editor: Amy Jollymore Senior Product Manager: Alyssa Pratt Editorial Assistant: Zina Kresin Content Project Manager: Matthew Hutchinson Art Director: Faith Brosnan Print Buyer: Julio Esperas Cover Designer: Roycroft Design/ www.roycroftdesign.com Cover Photo: ª Guntmar Fritz/Masterfile Proofreader: Green Pen QA Indexer: Elizabeth Cunningham Compositor: Integra ª 2011 Course Technology, Cengage Learning ALL RIGHTS RESERVED. No part of this work covered by the copyright herein may be reproduced, transmitted, stored or used in any form or by any means graphic, electronic, or mechanical, including but not limited to photocopying, recording, scanning, digitizing, taping, Web distribution, information networks, or information storage and retrieval systems, except as permitted under Section 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the publisher. For product information and technology assistance, contact us at Cengage Learning Customer & Sales Support, 1-800-354-9706 For permission to use material from this text or product, submit all requests online at www.cengage.com/permissions Further permissions questions can be...

Words: 11776 - Pages: 48

Free Essay

C# Programming

...True or False (Circle T/F if you think the statement is true/false) (Each question worth 5 points) 1. In C#, a project is a set of files and a solution is a set of projects. T 2. Every object you create or use in C# programming has a specific type usually. When a method doesn’t return anything, there is no return type defined for the method. F 3. In C#, some of the objects, variables or constants don’t have a specific type. F 4. The continue statement skips the remaining statements in the loop (any loop) and transfers control to the test condition. T 5. A smaller type must be explicitly cast to a compatible larger type. F 6. Assume you declared a constant when you’re programming. Although it is called a “constant”, its value can be changed when the program is running. F 7. The members in class A that are marked by private are accessible to methods of class A and also to methods of classes derived from class A. F 8. In C#, when you declare a variable without initializing it, the system will initialize the variable to 0 automatically as VB does. F 9. The system will execute a mathematical formula from left to right; you don’t have to consider the issue of operator precedence in C#. F 10. Implicit casting sometimes runs the risk of data loss. F Multiple Choice questions: (Circle all that applies. If all of your choices are correct but you missed the other correct choices, you will receive partial...

Words: 390 - Pages: 2

Premium Essay

C Programming Assignment

...C Programming assignment 1/10 APS106 2012 Project An adapted version of Chain Reaction The objectives of this project are twofold: (i) to strengthen your programming skills, and (ii) to provide you an opportunity to develop a complex project as a team. You are required to implement material covered in the APS106 course in a large C program that fulfills the requirements described below. Students will work together in teams, and students (even on different teams) are encouraged to learn from one another. However, each team is expected to develop its own project, and no teams should share code. The evaluation process at the end of term will include an automated and sophisticated comparison of codes that will identify instances of similarity. Such instances will be examined closely. Violations of the above rules will be dealt with in accordance with the University of Toronto’s Code of Behavior on Academic Matters. In case of ambiguities or errors in these instructions, we (the APS106 instructors) may clarify/modify them as the term progresses. IMPORTANT DATES ? March 5 -team registration ? April 9-11 -contest (optional) ? April 13 at 3:00 -submission deadline (report and code) PROJECT COORDINATOR: Babak Samareh (aps106ta@mie.utoronto.ca) -make sure you begin the subject line with “APS106”, as he’s going to get a lot of email. LOGISTICS Students will work in teams of 3-4 people. No exceptions. Teams may be composed of students from any of the five lecture sections of the course....

Words: 358 - Pages: 2

Premium Essay

C Programming

...1. What do we call the process of sub-dividing a problem into smaller sub-problems? This process is called Top-Down Design. 2. What is the purpose of a function prototype? It tells the return type of the data that the function will return. It tells the number of arguments passed to the function. It tells the data type of each of the passed arguments. It also tells the order in which the argument is passed to the function. 3. What is the purpose of the function definition? A function definition specifies the name of the function, the types and number of parameters it expects to receive, and its return type. A function definition also includes a function body with the declarations of its local variables, and the statements that determine what the function does. Chapter 3 Self-Check Exercises (p. 123) number 1a-d, 2a-e 4. 1a) root = u + v * pow(w,2) 1b) root = cube(x – y) 1c) loge=pow(x, y) 1d) absolute = (x*y) – (w/z) 2a) 20.0 2b) 17 2c) 22.0 2d) 3.0 Chapter 3, Review Questions (p. 167), numbers 3-6, 3. A function is executed after the function prototype in a source program. A function prototype and a function definition appear on separate lines in a source in a source program. 4. For a team of programmers working together on a large program, function subprograms make it easier to apportion tasks. They simplify programing tasks. Functions can be utilized more than once in a program. 5. Functions are more efficient for computer and programmer. When...

Words: 599 - Pages: 3

Free Essay

C++ Programming

...C++ CIS328 Professor Vijayakumar Kumarasamy 06/18/2014 Classes Classes are an expanded concept of data structures: like data structures, they can contain data members, but they can also contain functions as members. Object An object is an instantiation of a class. In terms of variables, a class would be the type, and an object would be the variable. Abstraction Data abstraction refers to, providing only essential information to the outside world and hiding their background details, i.e., to represent the needed information in program without presenting the details. Data abstraction is a programming (and design) technique that relies on the separation of interface and implementation. Encapsulation Encapsulation is an Object Oriented Programming concept that binds together the data and functions that manipulate the data, and that keeps both safe from outside interference and misuse. Data encapsulation led to the important OOP concept of data hiding. Data encapsulation is a mechanism of bundling the data, and the functions that use them and data abstraction is a mechanism of exposing only the interfaces and hiding the implementation details from the user. Inheritance One of the most important concepts in object-oriented programming is that of inheritance. Inheritance allows us to define a class in terms of another class, which makes it easier to create and maintain an application. This also provides an opportunity to reuse the code functionality and fast implementation...

Words: 1199 - Pages: 5

Free Essay

C Programming on Linux

...C Programming on Linux What You Need for This Project * A Kali Linux virtual machine. You could use other operating systems too, if they have a C compiler. Writing the hello.c Source Code In a Terminal window, execute this command: nano hello.c The nano editor opens. Type in the program shown below. #include <stdio.h> main() { printf("Hello World!\n"); } Save your file with Ctrl+X, Y, Enter. Compiling hello.c to Create the hello File In a Terminal window, execute these commands: gcc hello.c -o hello ./hello These commands compile the hello.c program, creating an executable machine language file named hello, and run the hello executable. You should see "Hello World!", as shown below. This program works, but it would be nicer if it greeted you by name, and if it put a couple of newline characters after the greeting to make it cleaner-looking. The next version, hello2, will add these features. Writing the hello2.c Source Code In a Terminal window, execute this command: nano hello2.c The nano editor opens. Type in the program shown below. #include <stdio.h> main() { char name[10]; printf("What is your name?"); scanf("%s", name); printf("Hi, %s\n\n", name); } ...

Words: 1293 - Pages: 6

Free Essay

C++ Programming

...(Package Inheritance Hierarchy) Package-delivery services, such as FedEx, DHL, and UPS, offer a number of different shipping options, each with specific costs associated. Create an inheritance hierarchy to represent various types of packages. Use Package as the base class of the hierarchy, then include classes TwoDayPackage and OvernightPackage that derive from Package. Base-class Package should include data members representing the name, address, city, state, and ZIP code for both the sender and the recipient of the package, in addition to data members that store the weight (in ounces) and cost per ounce to ship the package. Package's constructor should initialize these data members. Ensure that the weight and cost per ounce contain positive values. Package should provide a public-member function calculateCost that returns a double, indicating the cost associated with shipping the package. Package's calculateCost function should determine the cost by multiplying the weight by the cost per ounce. Derived class TwoDayPackage should inherit the functionality of base-class Package, but also includes a data member that represents a flat fee that the shipping company charges for two-day-delivery service. TwoDayPackage's constructor should receive a value to initialize this data member. TwoDayPackage should redefine member function calculateCost so that it computes the shipping cost by adding the flat fee to the weight-based cost calculated by base-class Package's calculateCost...

Words: 299 - Pages: 2

Free Essay

Quick Reference to C Programming

...A Quick Reference to C Programming Language Structure of a C Program #include(stdio.h) /* include IO library */ #include... /* include other files */ #define.. /* define constants */ /* Declare global variables*/) (variable type)(variable list); /* Define program functions */ (type returned)(function name)(parameter list) (declaration of parameter types) { (declaration of local variables); (body of function code); } /* Define main function*/ main ((optional argc and argv arguments)) (optional declaration parameters) { (declaration of local variables); (body of main function code); } Comments Format: /*(body of comment) */ Example: /*This is a comment in C*/ Constant Declarations Format: #define(constant name)(constant value) Example: #define MAXIMUM 1000 Type Definitions Format: typedef(datatype)(symbolic name); Example: typedef int KILOGRAMS; Variables Declarations: Format: (variable type)(name 1)(name 2),...; Example: int firstnum, secondnum; char alpha; int firstarray[10]; int doublearray[2][5]; char firststring[1O]; Initializing: Format: (variable type)(name)=(value); Example: int firstnum=5; Assignments: Format: (name)=(value); Example: firstnum=5; Alpha='a'; Unions Declarations: Format: union(tag) {(type)(member name); (type)(member name); ... }(variable name); Example: union demotagname {int a; float b; }demovarname; Assignment: Format: (tag).(member name)=(value); demovarname.a=1; demovarname.b=4...

Words: 253 - Pages: 2

Premium Essay

Introduction to C Programming

...1. CPU (Computer Processing Unit): the key component of a computer system, which contains the circuitry necessary to interpret and execute program instructions. 2. RAM (Random Access Memory): computer memory available to the user for creating, loading, or running programs and for the temporary storage and manipulation of data, in which time of access to each item is independent of the storage sequence. As a storage medium, RAM is volatile, so its contents are lost when the power fails or is turned off 3. ROM (Read Only Memory): computer memory in which program instructions, operating procedures, or other data are permanently stored, generally on electronic chips during manufacture and that ordinarily cannot be changed by the user. 4. Firmware: a microprogram stored in ROM, designed to implement a function that had previously been provided in software. 5. Operating system: the collection of software that directs a computer's operations, controlling and scheduling the execution of other programs, and managing storage, input/output, and communication resources. 6. Application program: a program used for a particular application 7. Machine language: a coding system built into the hardware of a computer, requiring no translation before being run. 8. Binary: A system of numerical notation to the base 2, in which each place of a number, expressed as 0 or 1, corresponds to a power of 2 9. Main memory: program-addressable storage that is directly controlled...

Words: 913 - Pages: 4

Premium Essay

Learn C Programming Language in 24 Hours

...Yourself C in 24 Hours Previous | Table of Contents | Next Hour 1 - Getting Started A journey of a thousand miles is started by taking the first step. —Chinese proverb High thoughts must have high language. —Aristophanes Welcome to Teach Yourself C in 24 Hours. In this first lesson you'll learn the following:     What C is Why you need to learn C The ANSI standard Hardware and software required in order to run the C program What Is C? C is a programming language. The C language was first developed in 1972 by Dennis Ritchie at AT&T Bell Labs. Ritchie called his newly developed language C simply because there was a B programming language already. (As a matter of fact, the B language led to the development of C.) C is a high-level programming language. In fact, C is one of the most popular general-purpose programming languages. In the computer world, the further a programming language is from the computer architecture, the higher the language's level. You can imagine that the lowest-level languages are machine languages that computers understand directly. The high-level programming languages, on the other hand, are closer to our human languages. (See Figure 1.1.) Figure 1.1. The language spectrum. High-level programming languages, including C, have the following advantages:    Readability: Programs are easy to read. Maintainability: Programs are easy to maintain. Portability: Programs are easy to port across different computer platforms. The C language's...

Words: 73255 - Pages: 294

Free Essay

Programming Concepts Using C++ Lab 6

...task. You are writing its definition. A function is a special type of module and most commonly referred to library functions which a made for different programming languages. 2. The three characteristics of a function in a IPO chart are: function header, function body, return statement. 3. The real number’s fractional part in a conversion function that is used to convert a real number to an integer usually shows up as a type mismatch error. A integer variable cannot hold fractional values. It’s better to convert the result of the math expression to an integer and then assign that integer to the variable. 4. A substring is a string within a string. The substring function typically accepts three arguments: (1) a string that you want to extract a substring from (2) the beginning position of the substring, and (3) the ending position of the substring. 5. The stringToInteger function accepts a string as an argument, converts it to an Integer, and returns the Integer value. The stringToReal function works the same way, but it converts a string to a Real, and usually then gets stored in the realNumber variable. 6. IsInteger function determines whether a string can be converted to a Integer and the isReal function determines whether a string can be converted to a Real. They use If Then Else statements. Programming Exercises 1....

Words: 260 - Pages: 2

Free Essay

C Programming

...16/15=1.066666667 15%16=10 16%15=1 3a. i = 3 % 4=yes, 3 3b. i = ( 989 – MAX,_ I) / 3=no 3c. i = 4 % 3=yes 3d. x = PI * -1.0 3e. i = 3 / - 4=no 3f. x = 3 / 4= yes, 0.75 3g. x = 3% ( 3 / 4)=no 4a. i = 7 % 3=yes, 1 4b. i = ( 989 - MAX_ I) / 7= no 4c. i = 3 % 7=yes, 3 4d. x = PI * 2.0=no 4e. i = 7/ - 3=no 4f. x = 7 / 3=yes, 2.3333333333 4g. x = 7 % ( 7 / 3)=no p.102 3. What is illegal about the following program fragment? %lf%lf 4. Stylistically, which of the following identifiers would be good choices for names of constant macros? G Part 2 A. Int V Int I Int R V=I*R B. Int Area Int length Int width Area=length*width C. Int Rseries Int R1 Int R2 Int R3 Rseries=R1+R2+R3 D. Int Rparallel Int R1 Int R2 Int R1 Int R2 Rparallel=R1*R2/(R1+R2) Part3 a. 15.0 b. 7.5 c. 5.0,10.0,5,10 d. 15.0 e. 0.51.0 f. 0,3 Part 4 The month day and year are...

Words: 252 - Pages: 2

Free Essay

C++ Programming

...ALGORITHM: STEP 1:  Start the program. STEP 2:  Declare the class name as fn with data members and member functions. STEP 3:  Read the choice from the user. STEP 4:  Choice=1 then go to the step 5. STEP 5:  The function area() to find area of circle with one integer argument. STEP 6:  Choice=2 then go to the step 7. STEP 7:  The function area() to find area of rectangle with two integer argument. STEP 8:  Choice=3 then go to the step 9. STEP 9:  The function area() to find area of triangle with three arguments, two as Integer and one as float. STEP 10: Choice=4 then stop the program. PROGRAM: #include #include #include #define pi 3.14 class fn {       public:         void area(int); //circle         void area(int,int); //rectangle         void area(float ,int,int);  //triangle };   void fn::area(int a) {       cout<<"Area of Circle:"<>ch;        switch(ch)      {               case 1:                 cout<<"Enter Radious of the Circle:";                 cin>>r;                 obj.area(r);                 break;               case 2:             ...

Words: 282 - Pages: 2

Free Essay

Programming Using C++

...3. milling Section * In the milling section, the wheat is the only component arrives here. In this stge the wheat is processed and changed into flour. It passes the following steps. A. Breaker (B1-B5) In this step, the wheat will be broken down into pieces so that it will separate the bran from the endosperm. B. Reduction (R1-R7) In this step, the wheat that has been processed in the breaker stage will be rub-down or reflexology preceeds. Through this process, the bigger and smaller brans are separated. C. Scratch (C1-C7) At this step, the processed “somolina” and bran in the reduction stage (R1-R4) will be processed again and only the white component of the wheat will be extracted. And the extract white flour will be sucked out by high pressure fan to the plant sifter. Each pipe have their own siever. Then the flour which has passed the eighteen seieves will be the final product. The amount of wheat that has to be sieved shall be controlled by the airlock, the airlock will play a great role by determining the amount of wheat that has to be passed and seived. The end product or ther desired flour will be transported into silo via convier and elevator. The rest of the component which is not changed into flour will be transported back to the reduction process to be reprocessed (R1-R7 and C1-C7) until the bran and flour is competly separated. The milling process will be as follows. convier elevator scorer convier counter grinder pipe ...

Words: 561 - Pages: 3