CIS 209 (C) Exam 2

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

logical operators

&& [and]|| [or]! [not]when combining two or more relational statementswhile ( (x<y) && (z < y)) {...

arithmetic operators

+, -, *, %, ++, --

Arrays

a collection of items stored in a contiguous memory location and addressed using one or more indices

what is a loop?

a construct that causes a program to execute a list of steps as many times as the conditions are true.

a function

a group of predefined statements for repeatedly used operations,

typedef

a keyword that gives an existing data type a nickname. the nickname is now a data type like char or int

if-else statement

allows your program to perform one action if the Boolean expression evaluates to true and a different action if the Boolean expression evaluates to false.

strcpy(sentenceSubject, "boy");

assigns boy into sentenceSubject variable.

printf("%d", GetBirthdayAge(42));

calls the function GetBirthdayAge(42) to use value 42 in its program. kinda like scanning a number into the program.

data type for characters

char, %c

a two-dimmensional array

int myArray[Row][Column] myArray[0][0] = 33 creates an array that holds rows and columns. similar to a nested loop

for (i=0; i<= strlen(inputWord); i++) { if (inputWord[i]== inChar){ ++numChar;}}

if i is less than the length of the inputWord, then enter the loop. increment i. if the the inputword at i index matches the inchar, then count a numChar. run the loop again until i greater than the string length.

if (strcmp(str1, str2) != 0) {

if str1 does not equal str2, then run program.

for (i = 0; i < NUM_POINTS; ++i) { if(dataPoints[i] < controlVal) { dataPoints[i] = dataPoints[i]*2;}} for (i = 0; i < NUM_POINTS; ++i) { printf("%d ", dataPoints[i]); }

if the number is less than a control value, then multiply that number by 2. print the new number. use a for loop to print the function separately.

for (i = 0; i < NUM_VALS; ++i) { if (testGrades[i] > 100){ sumExtra = sumExtra + (testGrades[i]-100);

if the testGrade in storage i is greater than 100, the extra credit is added to a list.

for (i = 0; i < NUM_ELEMENTS; ++i) { if (copiedVals[i] < 0) { copiedVals[i] = 0;}

if the value is negative, it converts that value to a zero

four parts of any loop

initialize variables or set them to zero conditions to evaluate block of statements to act out if conditions are true update variable to eventually leave the loop.

Write a program that first gets a list of integers from input. The input begins with an integer indicating the number of integers that follow. Then, get the last value from the input, which indicates a threshold. Output all integers less than or equal to that last threshold value. EX: input 5 50 60 140 200 75 100 output 50,60,75,

int NUM_ELEMENTS; int userValues[NUM_ELEMENTS]; // Set of data specified by the user int threshold; int value; int i; scanf("%d",&NUM_ELEMENTS); for(i = 0; i < NUM_ELEMENTS; ++i) { //scan values into the array scanf("%d", &value); getchar(); userValues[i]=value; } scanf("%d", &threshold); getchar(); for(i = 0; i < NUM_ELEMENTS; ++i){ prnt numbers lss than thsh; if(userValues[i] < threshold) { printf("%d,", userValues[i]); } } printf("\n"); return 0;

Declare a two dimensional array of integers named dataVals with 4 rows and 7 columns.

int dataVals[4][7];

Write a program whose input is two integers, and whose output is the first integer and subsequent increments of 5 as long as the value is less than or equal to the second integer.

int first; int second; scanf("%d", &first); scanf("%d", &second); if (first > second) { printf("Second integer can't be less than the first."); } while (first <= second) { printf("%d ", first); first += 5; } printf("\n");

Write a program that takes in an integer in the range 11-100 as input. The output is a countdown starting from the integer, and stopping when both output digits are identical. End with a newline.

int flag = 0; int first; int second; if((num < 11) || (num > 100)){ printf("Input must be 11-100\n"); } else { printf("%d ", num); while(flag==0){ first = num/10; second = num % 10; if (first== second) { flag = 1; } else { num= num-1; printf("%d ", num);} }printf("\n"); return 0; } }

Write a program whose input is a character and a string, and whose output indicates the number of times the character appears in the string.

int main(void) { int i; char inputWord[50]; char inChar; int numChar; scanf("%c", &inChar); scanf("%s", inputWord); getchar(); numChar = 0; for (i=0; i<= strlen(inputWord); i++) { if (inputWord[i]== inChar){ ++numChar; } } if (numChar == 1) { printf("%d %c\n", numChar, inChar);} else { printf("%d %c's\n", numChar, inChar);} return 0; }

Given numRows and numColumns, print a list of all seats in a theater. Rows are numbered, columns lettered, as in 1A or 3E. Print a space after each seat, including after the last. Ex: numRows = 2 and numColumns = 3 prints: 1A 1B 1C 2A 2B 2C

int main(void) { int numRows; int numColumns; int currentRow; int currentColumn; char currentColumnLetter; scanf("%d", &numRows); scanf("%d", &numColumns); int i; int j; for ( i = 1; i <= numRows; ++i){ currentColumnLetter = 'A'; for (j = 0; j < numColumns; ++j) { printf("%d%c ", i, currentColumnLetter); ++currentColumnLetter;

Print numbers 0, 1, 2, ..., userNum as shown, with each number indented by that number of spaces. For each printed line, print the leading spaces, then the number, and then a newline. Ex: userNum = 3 prints: 0 1 2 3

int main(void) { int userNum; int i; int j; scanf("%d", &userNum); for (i= 0; i <= userNum; ++i){ printf("%d\n", i); if (i < userNum) { for (j = 0; j <= i; ++j) { printf(" "); } }

Given a sorted list of integers, output the middle integer. A negative number indicates the end of the input

int userValues[9]; // Set of data specified by the user int i; int middleIndex; int tempVal; scanf("%d", &tempVal); for(i = 0; tempVal > 0; i++){ // scans ints into the array until neg userValues[i] = tempVal; if (userValues[i] >= 0) { scanf("%d", &tempVal); getchar();} } if(i <= 9){ middleIndex = i / 2; printf("Middle item: %d\n", userValues[middleIndex]); } else { printf("Too many numbers\n");} return 0;

what is the data type of an array

it can be anything. an array of integers is a list of numbers. an array of characters is a sentence or word.

function of the following typedef char* string

nicknames char* to string. so now you can do stuff like string name = "CIS209"

what does printf("%c", userWord[3]); do

prints the single character in the 3rd index of userWord. for example, if userWord is Table. .userWord[3] is l

return statement. in a function

returns the results of the function return numToSquare * numToSquare; ^ can also do the results in this step

Write a program that reads a list of integers, and outputs those integers in reverse. first input is the number of inputs that follow

scanf("%d", &NUM_ELEMENTS); NUM_ELEMENTS = NUM_ELEMENTS + 1; for(i = 1; i < NUM_ELEMENTS; ++i) { scanf("%d",&tempVal); getchar(); userVals[i] = tempVal; } for(i = (NUM_ELEMENTS-1);i >=1; --i){ tempVal = userVals[i]; printf("%d,",tempVal); } printf("\n"); return 0; }

how to scan a string

scanf("%s", string);no need for a &

strcmp(str1, str2) == 0

str1 = str2

what is a call function

stuff like printf, scanf, etc.

for (i = 0; i < SCORES_SIZE; ++i) { scanf("%d", &(lowerScores[i])); for (i = 0; i < SCORES_SIZE; ++i) { lowerScores[i] = lowerScores[i] - 1; if ( lowerScores[i] <=0){ lowerScores[i]= 0;}}

subtract one from each score. if the score was already 0 or neg, set that num equal to zero.

Defining and using a new struct type.

typedef struct StructTypeName_struct { type item1; type item2; ... type itemN; } StructTypeName; ... StructTypeName myVar; myVar.item1 = ...

Write a function DrivingCost() with input parameters milesPerGallon, dollarsPerGallon, and milesDriven, that returns the dollar cost to drive those miles. using a function and main ()

#include <stdio.h> double DrivingCost( double milesPerGallon, double dollarsPerGallon, double milesDriven){ double yourValue; yourValue = (milesDriven/ milesPerGallon) * dollarsPerGallon; return yourValue;} int main(void) { double yourValue; double milesPerGallon; double dollarsPerGallon; scanf("%lf", &milesPerGallon); getchar(); scanf("%lf", &dollarsPerGallon); getchar(); yourValue = DrivingCost(milesPerGallon,dollarsPerGallon, 10); printf("%0.2lf ", yourValue);

One lap around a standard high-school running track is exactly 0.25 miles. Define a function named LapsToMiles that takes a double as a parameter, representing the number of laps, and returns a double that represents the number of miles write a main program that takes a number of laps as an input, calls function LapsToMiles() to calculate the number of miles, and outputs the number of miles.

#include <stdio.h> double LapsToMiles( double laps){ double miles; miles = laps*(.25); return miles;} int main(void) { double laps; scanf("%lf", &laps); getchar(); double yourValue; yourValue = LapsToMiles(laps); printf("%0.2lf\n", yourValue); /* Type your code here. Your code must call the function. */ return 0;

what library do you need for strings?

#include<string.h>

letter1 = 'a'; while (letter1 <= 'f') { letter2 = 'c'; while (letter2 <= 'f') { // Inner loop body ++letter2; } ++letter1; }

24

Given the following code, how many times will the inner loop body execute?int row; int col; for(row = 0; row < 2; row = row + 1) { for(col = 0; col < 3; col = col + 1) { // Inner loop body } }

6

Nested loop

A loop inside the body of another loop.

while loop

A loop that continues to repeat while a condition is true. while (letter2 <= 'z')

string indexing

Accessing certain characters in a string. ex: MaryString[0] would be M. it starts at 0.

for (i = 0; i < strlen(userName); ++i) { if (userName[i] == ' ') { userName[i] = '_';

Before: Alan Turing After: Alan_Turing

Array Declaration

Char sentence[length]; int person[numPeople}; int yearsArr[4].

strcmp

Compares two strings (case-sensitive)

strcat(s1, s2)

Concatenates string s2 onto the end of string s1 if s1 is Hey and s2 is !!! .s1 becomes Hey!!!

strcpy(str1, str2)

Copy the contents of str2 into str1. string 1 must be larger than string 2.

enum

Define a set of int constants

for loop

Loops that have a predetermined beginning, end, and increment (step interval).

strlen(userWord)

Returns the length of the string titled userWord.

swapping to values

Use a temporary value to hold a numnber int X = 33; int Y = 55; int tempVal = 0; tempVal = X; X = Y; Y = tempVal;

strcpy

copy second string into first

char sentenceSubject[20] function?

declares a string of size 19.

Complete the function definition to return the hours given minutes.

double GetMinutesAsHours(double origMinutes) { double hours; hours = origMinutes / 60.0; return hours; main code : scanf("%lf", &minutes); printf("%f\n", GetMinutesAsHours(minutes)); the main code calls the function with the input minutes

Calling functions from functions

double PizzaCalories(double pizzaDiameter) { double totalCalories; double caloriesPerSquareInch = 16.7; totalCalories = CalcCircleArea(pizzaDiameter) * caloriesPerSquareInch; return totalCalories; this calls function CalcCircleArea() to input the area of the circle using this pizza diameter.

enum

first value is always set to 0. if you set the first value to 1, then the following will be 2, 3 4 etc.

for (i = 0; i < SCORES_SIZE; ++i) { scanf("%d", &(oldScores[i])); for (i = 0; i < SCORES_SIZE; ++i) { newScores[i] = oldScores[i+1]; if(i == 3) { newScores[i] = oldScores[0];}} for (i = 0; i < SCORES_SIZE; ++i) { printf("%d ", newScores[i]); } printf("\n");

first, use a for loop for each function. this helps keep it clean and readable. sets newScores to oldScores rotated once left, with element 0 copied to the end. Ex: If oldScores = {10, 20, 30, 40}, then newScores = {20, 30, 40, 10}.

Find the maximum value and minimum value in milesTracker. Assign the maximum value to maxMiles, and the minimum value to minMiles.

for (i = 0; i < NUM_ROWS; i++){ for (j = 0; j < NUM_COLS; j++){ scanf("%d", &(milesTracker[i][j])); } } maxMiles = - 9999; minMiles = 9999; for (i = 0; i < NUM_ROWS; i++){ for (j = 0; j < NUM_COLS; j++){ if(milesTracker[i][j] > maxMiles){ maxMiles = milesTracker[i][j];} if(milesTracker[i][j] < minMiles){ minMiles = milesTracker[i][j];}}} printf("Min miles: %d\n", minMiles); printf("Max miles: %d\n", maxMiles);

a loop that runs until the end of a sentence

for (i = 0; userText[i] != '\0'; ++i) { brackets [ i ] necessary

types of loops

for (int i=0; condition > 3; ++i) {while (strcmp(userText, "Goodbye") != 0) {do-while ()

A function definition

the new function's name and a block of statements. Ex: double CalcPizzaArea() { /* block of statements */ } double CalcPizzaArea() { double pizzaDiameter; double pizzaRadius; double pizzaArea; double piVal = 3.14159265; pizzaDiameter = 12.0; pizzaRadius = pizzaDiameter / 2.0; pizzaArea = piVal * pizzaRadius * pizzaRadius; return pizzaArea; }

Read the following Code char userCaption[22]; int lastIndex; char lastChar; printf("Enter a caption (20 char max): "); scanf("%s", userCaption); lastIndex = strlen(userCaption) - 1; lastChar = userCaption[lastIndex]; if ( (lastChar != '.') && (lastChar != '!') && (lastChar != '?') ) { strcat(userCaption, "."); } printf("New: %s\n", userCaption); return 0;

this scans usercaption, it then takes the length of the string and subtracts 1. it then takes the last character. if the last character is not a !,., or ?, it will use strcat to add a . to the end of the caption.

nested loop use

to generate all possible combinations of an outcome. for example ab.com ac.com ad.com bb.com bc.com

typedef in a struct

typedef struct [STRUCT_NAME] { ELEMENTS; } IDENTIFIER; instead of then doing struct STRUCT_NAME element1 = 3 you can now just say IDENTIFIER element 1 = 3. it replaces all the struct mess with identifier.

initializing an array

userWeights[0] = 122; userWeights[1] = 119; userWeights[2] = 117;

replacing a character in a word

userWord[5] = 't' would turn Beautiful into Beauttful.

for (i = 0; i < NUM_ELEMENTS; ++i) { if (userVals[i] > maxVal) { maxVal = userVals[i];

uses a for loop with an array to compare multiple variables.

for (i = 0; i < NUM_ELEMENTS; ++i) { printf("Value: "); scanf("%d", &(userVals[i]));

uses a for loop with an array to scan multiple variables into a storage location.

for (i = 0; i < NUM_VALS; ++i) { if (i < 1) { printf("%d,", hourlyTemp[i]);} if (i >= 3){ printf(" %d", hourlyTemp[i]);} if (i >=1 && i < 3) { printf(" %d,", hourlyTemp[i]);} }

uses i to run through all the values of the array (hourTemp[i])

double letterWeights[14] = {1.0, 2.0, 3.0, 3.5, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0}; // Costs in cents (usps.com 2017) int postageCosts[14] = {49, 70, 91, 112, 161, 182, 203, 224, 245, 266, 287, 308, 329, 350}; for (i = 0; (i < NUM_ELEMENTS) && (!foundWeight); ++i) { if( userLetterWeight <= letterWeights[i] ) { foundWeight = true; printf("Postage for USPS first class mail is %d cents\n", postageCosts[i]);

using two arrays with the same position i to connect a postage cost to a letter weight


Ensembles d'études connexes

Chapter 3 Form and Function of Bacteria and Archaea

View Set

Community-Based Nursing Practice

View Set

Anatomy Chapter 8 test (The Nervous System)

View Set

algebra 1a - unit 1: the real numbers

View Set

5. Relational Databases and mySQL

View Set

ECO-251: Chapter 1 - Limits, Alternatives, and Choices

View Set

TBR Psych 3 - Learning and Memory

View Set