#Parentheses Integers Multiplication Division Addition Subtraction
Explore tagged Tumblr posts
itsthenerdwonder · 2 years ago
Text
where's that image about poll OPs getting proven completely incorrect
wanna see exactly HOW bad tumblr is at math so tell me
34K notes · View notes
kandztuts · 14 days ago
Text
Linux CLI 61 🐧 modern test version and in (( )) shell scripts
New Post has been published on https://tuts.kandz.me/linux-cli-61-%f0%9f%90%a7-modern-test-version-and-in-shell-scripts/
Linux CLI 61 🐧 modern test version and in (( )) shell scripts
Tumblr media
youtube
a - extended test command in shell scripts Unlike the traditional [ ] (or test) which requires spaces around operators, [[ ]] does not have this requirement. It's generally recommended to use [[ ]] over [ ] for most modern shell scripting needs due to its enhanced functionality and error prevention. Unlike [ ], [[ ]] does not split words or do pathname expansion unless explicitly told to with *. Using [[ ]] can lead to more robust and error-free scripts compared to the older [ ], especially in complex conditions involving strings, patterns, or file tests. String Comparison Without Quotes: [ $var1 = test ]: Without quotes, if var1 is empty or contains spaces, it will cause a syntax error. Using quotes ([ "$var1" = "test" ]) avoids this issue. [[ $var1 = test ]]: With [[ ]], you don't need to quote variables unless they contain special characters or are empty. This makes the code cleaner and less error-prone. Pattern Matching: [ $var2 = test* ]: Using pattern matching without quotes can lead to unexpected results due to word splitting and pathname expansion. [[ $var2 =~ test.* ]]: With [[ ]], you can use the =~ operator for regex matching, which is more flexible and powerful. Numeric Comparisons: Both [ ] and [[ ]] support numeric comparisons similarly (-eq, -ne, etc.), but [[ ]] allows for easier chaining of conditions due to its lack of word splitting issues. b - (( )) in shell scripts (()) is used for arithmetic evaluation. It allows you to perform mathematical operations and handle integer arithmetic directly within your scripts syntax: result=$((expression)) expression: This can include any valid arithmetic operation involving integers, such as addition (+), subtraction (-), multiplication (*), division (/), modulus (%), and exponentiation (using ** in some shells). Key Points 1. Integer Arithmetic Only: (()) supports only integer arithmetic. If you need floating-point calculations, you would typically use tools like bc or awk. 2. Expression Evaluation: The entire expression within (()) is evaluated to a single integer value. 3. Precedence and Associativity: (()) follows the standard mathematical precedence rules (multiplication and division before addition and subtraction). Parentheses can be used to alter the order of operations. example 1 → Simple Arithmetic Operations example 2 → Using Variables and Expressions example 3 → Incrementing and Decrementing Variables example 4 → Using Exponentiation
0 notes
1data2science · 1 year ago
Text
Pre Algebra part 1
Pre-Algebra for Data Science
Following are the topics which we will cover here
Definition of Algebra
Types of Numbers
Operation on numbers
Key terms that are used in algebra
Fractions and decimals
Ratios and proportions
1. Definition of Algebra
Algebra is a branch of mathematics that deals with the study of mathematical symbols and the rules for manipulating them. It allows us to represent and solve problems using variables, equations, and functions. In the context of data science, algebra provides the necessary tools to work with data, model relationships, and derive insights from complex information.
2. Types of Numbers
In pre-algebra, we encounter different types of numbers, including:
Natural Numbers: Also known as counting numbers, these include the positive integers (1, 2, 3, ...).
Whole Numbers: These include the natural numbers and the number zero (0, 1, 2, 3, ...).
Integers: Integers include the positive and negative whole numbers, as well as zero (-3, -2, -1, 0, 1, 2, 3, ...).
Rational Numbers: Rational numbers are numbers that can be expressed as a fraction of two integers, such as 1/2, 3/4, or 7/11.
Irrational Numbers: Irrational numbers are numbers that cannot be expressed as a fraction of two integers, such as π (pi) and √2.
Understanding the properties and relationships between these different types of numbers is crucial for working with data and performing mathematical operations.
3. Operations on Numbers
The fundamental operations in pre-algebra include:
Addition: Adding two or more numbers together.
Subtraction: Finding the difference between two numbers.
Multiplication: Repeatedly adding a number to itself.
Division: Splitting a number into equal parts.
Mastering these operations, including the order of operations (PEMDAS: Parentheses, Exponents, Multiplication, Division, Addition, Subtraction), is essential for performing calculations and manipulating data effectively.
4. Key Terms in Algebra
Some of the key terms used in algebra include:
Variable: A symbol, usually a letter, that represents an unknown or a changing value.
Equation: A mathematical statement that shows two expressions are equal.
Inequality: A mathematical statement that shows one expression is greater than, less than, or not equal to another expression.
Function: A relationship between two or more variables, where one variable (the dependent variable) depends on the value of the other variable(s) (the independent variable(s)).
Understanding these terms and their applications will help you work with algebraic concepts and effectively communicate your data science findings.
5. Fractions and Decimals
Fractions and decimals are crucial for representing and manipulating numerical data. In pre-algebra, you'll learn:
Fractions: A way to represent a part of a whole, written as a ratio of two integers (the numerator and the denominator).
Decimals: A way to represent a number using place value, where the decimal point separates the whole number from the fractional part.
Mastering operations with fractions and decimals, such as addition, subtraction, multiplication, and division, will enable you to work with numerical data more effectively.
6. Ratios and Proportions
Ratios and proportions are essential for understanding relationships between quantities. In pre-algebra, you'll learn:
Ratios: A comparison of two or more quantities, written as a fraction or expressed as a rate.
Proportions: An equation that shows two ratios are equal, allowing you to find unknown values.
Understanding ratios and proportions will help you analyze and interpret data, especially when working with rates, percentages, and scaling relationships.
By exploring these pre-algebra topics, you'll build a strong foundation for your data science journey. These concepts will empower you to work with data, create models, and derive meaningful insights. As you progress, remember to practice regularly and apply these principles to real-world data problems. Happy learning!
1 note · View note
izicodes · 2 years ago
Note
Hey! I saw your personal project rec post but I was wondering if you had any suggestions for projects that can’t use libraries? I am applying for an opportunity where we have to code something from scratch so I imagine it can be something small would you have any ideas? Thank you!
Tumblr media
Hiya! 💕
Since I don't know what languages you will be using, I'm just going to give you some quick and easy projects that are either webpage-building and console application ideas!
Tumblr media
Webpage Project Ideas
Personal Portfolio: Create a simple personal portfolio website showcasing your skills, projects, and contact information. Use pure HTML, CSS, and JavaScript for responsive design and interactivity.
Simple Blog: Develop a basic blog where you can post articles and visitors can read and leave comments. Implement features such as user authentication, a comment system, and article categorization using only vanilla JavaScript, HTML, and CSS.
To-Do List: Build a to-do list web application that allows users to create, edit, and delete tasks. Add the ability to mark tasks as complete and filter tasks based on their completion status. Implement this project using only HTML, CSS, and JavaScript.
Console Application Ideas
Text-based Adventure Game: Create a text-based adventure game where users can navigate through different rooms, pick up items, and interact with characters. Design the game with an interesting storyline and various challenges to engage the player.
File Organizer: Write a console application that organizes files in a directory based on their file types (e.g., images, documents, videos). The app should create folders for each file type and move the corresponding files into their respective folders.
Basic Calculator: Develop a console-based calculator that can perform basic arithmetic operations like addition, subtraction, multiplication, and division. Enhance the functionality by adding support for parentheses and differentiating between integer and floating-point arithmetic.
Tumblr media
These projects your coding skills for your opportunity without relying on any external libraries. I think it's kind of good that they want to see people code from scratch, just to see where their abilities are at!
I made another post about projects before that you can check out if you don't like the ones I listed: Beginner JavaScript Projects Hope this helps! Good luck with your opportunity! 🥰👍🏾💗
54 notes · View notes
Text
Easy Python Projects For Beginners with code
Build Your Calculator Using Python
Python is a great programming tool when playing with numbers and mathematical expressions. We will help you to make a simple python program run in the command-line. This is a tutorial that presents how to build your own calculator using a python program for beginners. We will use variables, conditional statements, math operations, functions for building our calculator.
STEP 1- Asking inputs from the user
Before moving to the tutorial I remind you, you have to install python on your computer. For accepting user-generated input from the keyboard, we have to use python’s built-in function input(). Inside parentheses of input() function for asking users, we can give a string. We have to input two numbers.
We have to input two numbers. For asking two numbers, we should give space at the end of the given strings. Because this gives a space between string and number.
num_1 = input('Enter your first number: ') num_2 = input('Enter your second number: ')
After writing two lines, save the program as calculator.py.We can run the program on the terminal by using the command python calculator.py.
Output:
Enter your first number:2 Enter your second number:5
Depending on our need, the input numbers can be either integer or float. For this, whole numbers are suitable. So, we use the int() function for converting inputs to the integer data type.
num_1 = int(input('Enter your first number: ')) num_2 = int(input('Enter your second number: '))
Now, we can give integers. It doesn’t show an error.
Enter your first number: 3 Enter your second number: 567
STEP 2- Adding Operators
Next we need to add our four mathematical operators,such as: + (Addition),- (Subtraction), * (Multiplication), / (Division).
Let’s look at how we can add two numbers within print().
num_1 = int(input('Enter your first number: ')) num_2 = int(input('Enter your second number: ')) print(num_1 + num_2)
After running the program,
Enter your first number: 2 Enter your second number: 5 7
Now, we use string formatters, for proper text format and getting feedback.
num_1 = int(input('Enter your first number: ')) num_2 = int(input('Enter your second number: ')) print('{} + {} = '.format(num_1, num_2)) print(num_1 + num_2)
When the program runs, we will get the output as,
Enter your first number: 2 Enter your second number: 5 2 + 5 = 7
So, use the same format for the rest of the mathematical operators.
num_1 = int(input('Enter your first number: ')) num_2 = int(input('Enter your second number: ')) # Addition print('{} + {} = '.format(num_1, num_2)) print(num_1 + num_2) # Subtraction print('{} - {} = '.format(num_1, num_2)) print(num_1 - num_2) # Multiplication print('{} * {} = '.format(num_1, num_2)) print(num_1 * num_2) # Division print('{} / {} = '.format(num_1, num_2)) print(num_1 / num_2)
If we run the above code, it will take all the operators. For avoiding such situations, we want to limit the operators, ie; only run one operator at a time. So, we have to use conditional statements.
STEP 3- Conditional Statements
We are giving freedom to the user for selecting the operator. So, we use the input() function for getting an operator symbol from the user.
operation = input(''' Please type in the math operation you would like to complete: + for addition - for subtraction * for multiplication / for division ''')
Now we are using conditional statements. Here we use one if statement, three else-if statements and one else statement. Else statement is used for handling the error or invalid entry.
operation = input(''' Please type in the math operation you would like to complete: + for addition - for subtraction * for multiplication / for division ''') num_1 = int(input('Enter your first number: ')) num_2 = int(input('Enter your second number: ')) if operation == '+':    print('{} + {} = '.format(num_1, num_2))    print(num_1 + num_2) elif operation == '-':    print('{} - {} = '.format(num_1, num_2))    print(num_1 - num_2) elif operation == '*':    print('{} * {} = '.format(num_1, num_2))    print(num_1 * num_2) elif operation == '/':    print('{} / {} = '.format(num_1, num_2))    print(num_1 / num_2) else:    print('invalid operator, try again.')
Let’s see the output for * operation.
Please type in the math operation you would like to complete: + for addition - for subtraction * for multiplication / for division * Please enter the first number: 2 Please enter the second number: 5 2 * 5 = 10
We are aiming for a fully functional program. But now it is impossible because we can’t perform first, second and fourth operations without using this code again. Make it possible using functions.
STEP 4- Defining Functions
Let’s put our code inside a function named as to calculate(). For running this program, we have to call this function from the bottom. Consider another important part of this program, the user has a choice to continue or discontinue the calculation. For this, we are adding another function called def calculate_again(). Add this on below def calculate().
def calculate():    operation = input(''' Please type in the math operation you would like to complete: + for addition - for subtraction * for multiplication / for division ''')    num_1 = int(input('Please enter the first number: '))    num_2 = int(input('Please enter the second number: '))    if operation == '+':        print('{} + {} = '.format(num_1, num_2))        print(num_1 + num_2)    elif operation == '-':        print('{} - {} = '.format(num_1, num_2))        print(num_1 - num_2)    elif operation == '*':        print('{} * {} = '.format(num_1, num_2))        print(num_1 * num_2)    elif operation == '/':        print('{} / {} = '.format(num_1, num_2))        print(num_1 / num_2)    else:        print('invalid operator, try again.')    # Add again() function to calculate() function    again() def calculate_again():    calcu_again = input(''' Do you want to calculate again? Please type Y for YES or N for NO. ''')    if calc_again.upper() == 'Y':        calculate()    elif calc_again.upper() == 'N':        print('See you later.')    else:        again() calculate()
You can run the program ‘calculator.py’ using the command ‘python calculator.py’.Now users can calculate as much they need without rewriting the code.
Conclusion
This tutorial will help you for creating your own calculator using python on the command line. This is a simple program to learn the basics for beginners. Try to learn more under proper guidance. Learn Python Programming from expertise. Demand for python developers are on the hike and the average junior Python developer salary is $89,776.
8 notes · View notes
study-from-here · 2 years ago
Text
Addition, Subtraction, Multiplication, Division in C: An Introduction in Under 10 Minutes
If you're new to programming or looking to refresh your knowledge of addition, subtraction, multiplication, and division in the C programming language, you've come to the right place. In this brief guide, we'll provide you with a quick introduction to these fundamental arithmetic operations in C, allowing you to grasp the basics in under 10 minutes. Let's get started!
Addition (+): Addition in C is straightforward. It is denoted by the plus sign (+) and is used to add two or more values together. For example, in the expression int result = 3 + 5;, the value of result will be 8.
Subtraction (-): Subtraction in C is represented by the minus sign (-) and is used to subtract one value from another. For instance, int result = 10 - 7; will assign the value 3 to result.
Multiplication (): Multiplication in C is denoted by the asterisk () and is used to multiply two or more values. For example, int result = 4 * 6; will assign the value 24 to result.
Division (/): Division in C is represented by the forward slash (/) and is used to divide one value by another. It returns the quotient, which can be a whole number (integer division) or a decimal (floating-point division). For instance, int result = 20 / 5; will assign the value 4 to result.
Note: Integer division truncates any decimal part, so int result = 9 / 2; will assign the value 4 to result.
Order of Operations: Like in mathematics, the order of operations matters in C. Use parentheses to specify the desired order if needed. For example, in the expression int result = (3 + 4) * 2;, the value of result will be 14, as the addition is performed first.
Conclusion: In just under 10 minutes, you've learned the basics of addition, subtraction, multiplication, and division in the C programming language. These fundamental arithmetic operations are the building blocks of more complex calculations and algorithms in C. With this foundational knowledge, you can now explore more advanced concepts and dive deeper into the world of C programming. Happy coding addition subtraction multiplication division program in c!
0 notes
mathematicianadda · 6 years ago
Text
How many consecutive integers can be made using: addition, subtraction, multiplication, division?
Update: "Weak" lower exponential bound was established: $f(n)\ge 3^{n/5}$, and $f(5)$ improved.
Problem
Up to how many consecutive integers $\in\mathbb N$, can be made using only the four basic operations:
$+$ addition, $-$ subtraction, $\times$ multiplication, $\div$ division
Given $n$ numbers ("digits") as building blocks, if parentheses are allowed?
The goal is to build all integers from $1$ to $N$, while maximizing $N$, for given $n$ amount of digits.
We are given $d\in\mathbb N^n$ natural numbers ("digits") to work with.
We define $f_d(n)$ as maximal $N$ reachable using digits $d$, and $f(n)$ as maximal $f_d(n)$, given $n$.
Example
Lets take $n=4,f_d(4)$ for example. We can try using $d=\{4,4,4,4\}$ four fours,
\begin{array}{} 1 &= (4 + 4 - 4) \div 4 \\ 2 &= 4 - ((4 + 4) \div 4) \\ 3 &= (4 + 4 + 4) \div 4 \\ 4 &= ((4 - 4) \times 4) + 4 \\ 5 &= ((4\times4)+4)\div4 \\ 6 &= ((4 + 4) \div 4) + 4 \\ 7 &= 4 - (4\div4 - 4) \\ 8 &= (4 + 4 + 4) - 4\\ 9 &= (4\div4 + 4) + 4 \end{array}
And see that $f_{\{4,4,4,4\}}(4)=9$, because if you try hard enough, $10$ can't be made!
This means that $f(4)\ge f_d(4)= 9$ is at least nine.
We probably need a better set of digits $d$ to use, to make $10$ and beyond.
Clarification example
Given digits $d=\{1,2,5\}$, we can build for example $15=(1+2)\times5$.
But, note that: Like pieces of a puzzle, all given digits in a set must be used. This means $\{1,2,5\}$ set can't build number $1$ for example. It's clear divisions aren't useful on it, and subtractions are not enough.
This means $f_{\{1,2,5\}}(3)=0$, since we can't reach $N=1$ to begin with.
But using just $\{1,2\}$ can build $1=2-1$ trivially, in comparison.
Definitions
Given a fixed set of $n$ digits $d=\{d_1,\dots,d_n\}$, we can construct consecutive integers from $1$ to $N\in\mathbb N$ using the basic operations and parentheses, but we can't construct $N+1$. Then we define the value $f_d(n)=N$.
Then we can define $f(n)=\max f_d(n)=N_{\text{max}}$, for $d\in\mathbb N^n$. That is, maximized $N$ obtained by using the optimal set of digits $d=\{d_1,\dots,d_n\}$ for a given case of using $n$ digits.
How to efficiently calculate, practically prove, $f(n)$ for given $n$?
The sets of digits are not ordered, so naturally:
WLOG we can assume $d_1\le d_2\le \dots \le d_n\implies d_n=\max\{d_1,\dots,d_n\}$. Keep this in mind.
Clarifications
All integers $1,2,3,\dots,N$ must be constructed using all digits from the digit set $d$.
We are after optimal $d=\{d_1,\dots,d_n\}$ that will allow us to construct the longest such sequence by applying the basic operations $+,-,\times,\div$ to the given digit set, when talking about maximal $N$.
Solution summary
So far I have the following data, where $d_n$ is optimal (so far) set giving $f(n),n=1,\dots,5$:
\begin{array}{cccccc} d_n & \{1\} & \{1, 2\} & \{1, 2, 4\} & \{2, 4, 6, 22\} & \{2, 3, 7, 11, 36\}^* \\ f(n)& 1 & 3 & 10 & 52 & \ge 314 \end{array}
The last entry, $f(5)$, could be better, but my brute force search is too slow to improve this.
The $52$ entry is probably optimal, but I don't have a proof, yet.
The $1,3,10$ can be determined exhaustively.
Solving small cases
Cases $n=1,2$
Trivially, $f(1)=1$ for $d=\{1\}$, since we can't apply binary operations to a single digit.
It can be easily seen that $f(2)=3$ is best, using optimal digits set $d=\{1,2\}$, here:
$$\begin{array}{} 1 &= 2 - 1 \\ 2 &= 2 \times 1 \\ 3 &= 2 + 1 \\ \end{array}$$
This is optimal: Since if we are given $d=\{d_1,d_2\}$, if not $d_2-d_1=1$ or not $d_1=d_2$, we can't make $1$, thus $f_d(2)=0$ in these $d$ cases. And we can't make $2$ unless they either add up to two, differ by two, or one is two times other. The only case that also extends to $3$, is the $d=\{1,2\}$ making this $f(2)=3$ proof easy.
Case $n=3$
It can be shown $f(3)=10$ if you observe enough cases. It can be seen that $f_d(3)= 3$ at best, if $d_3$ is too large. I have checked the rest (small enough) cases computationally.
The optimal set is $d=\{1,2,4\}$ and the solutions can be seen below:
$$\begin{array}{} 1 = 4 - (1 + 2) \\ 2 = 4 - (1 * 2) \\ 3 = (1 - 2) + 4 \\ 4 = (2 - 1) * 4 \\ 5 = 4 - (1 - 2) \\ 6 = (1 * 2) + 4 \\ 7 = (1 + 2) + 4 \\ 8 = (1 * 2) * 4 \\ 9 = 1 + (2 * 4) \\ 10 = (1 + 4) * 2 \\ \end{array}$$
Case $n=4$
The $f(4)=52$ is a conjectured solution, using $d=\{2,3,4,22\}$.
The previous records are $f_{\{1, 2, 5, 6\}}(4)=43, f_{\{1, 2, 5, 8\}}(4)=51$.
I have checked all $d_4\lt 64$, and tabulated maximal $N=y$ for subsets of digits such that $d_4=x$:
Tumblr media
Is it possible to prove $f(4)=52$?
A similar problem to $f(4)$, but roots and exponentiation are allowed, was asked.
Computing larger cases
Cases $n\ge 5$
Is it possible to set up bounds or make progress in calculating these cases?
If not, can we optimize the computation?
I'm running a brute force search, and have $f(5)\ge 314$ so far.
For this result, all sets of digits with $d_5\le 15$ have been checked with record being $f_{\{2, 8, 9, 12, 13\}}=271$. But this is going on too slow in my python code to extend further. (Code based on this four fours solver.)
So I've decided to not brute force all sets, but try ones with $d_1,d_2=1,2$ or $d_1,d_2=2,3$ and $d_3\le d_4/2$, for $d_5\ge 20$. I've reached $d_5=37$ so far, with these restrictions on $d_1,d_2,d_3$.
This is where current record $f_{\{2, 3, 7, 11, 36\}}=314$ was found so far.
The solutions for $1,\dots,314$ for the record holder can be seen.
Growth of $f(n)$?
Can we analyse and give bounds on growth of $f(n)$?
Here is weak example bound to get started:
For $d$, we pick $\{1,\dots,1\}$ all $1$'s. We can then make $1,\dots,2n-4$ easily:
$$\begin{array}{} 1 &= (1+1)-(1\times1\times\dots\times 1) &= 2 - 1\\ 2 &= (1+1)\times(1\times1\times\dots\times 1) &= 2 \times 1\\ 3 &= (1+1)+(1\times1\times\dots\times 1) &= 2 + 1\\ 4 &= (1+1)+1+(1\times1\times\dots\times 1) &= 2 + 1 + 1\\ \dots & & \\ n &= (1+1)+(1+1+1+\dots+ 1) &= 2 + (n-2) \\ n &= (1+1)\times(1+1)+(1+1+\dots+ 1) &= 2\cdot2 + (n-4) \\ n+1 &= (1+1)\times(1+1+1)+(1+\dots+ 1) &= 2\cdot3 + (n-5) \\ n+2 &= (1+1)\times(1+1+1+1)+(1+\dots+ 1) &= 2\cdot4 + (n-6) \\ \dots & & \\ 2n-4 &= (1+1)\times(1+1+1+\dots+ 1) &= 2(n-2) + (n-n) \end{array}$$
Also note that this works if we replace $(1+1)$ with $(d_n\div d_{n-1})$ if $d_{n-1}=d_n/2$, so we also have an infinite family of digit sets that can achieve at least $2n-4$, since $d_n\in\mathbb N$ can be any digit.
We have now shown $f(n)\ge 2n-4$ with this trivial digit set.
Can we do better than a linear lower bound?
Update: Weak exponential lower bound
The bound is "weak" due to ignoring $(-,\div)$ operations by the following restriction.
Lets restrict the problem to only $(+,\times)$ operations, and define this restricted $\overline{f}(n)$. We have:
$$ f(n)\ge \overline{f}(n) $$
By definition. For $\overline{f_d}$, optimal $d$ consists of pure $1$'s, since otherwise, $N=1$ can't be made.
Now this becomes related to the "Complexity of natural number $n$" problem. That is, $a(N)$ - minimal number of $1$'s for expressing $N$ using $1$'s and $+,\times$. Now, this has known bounds:
$5\log_3N \ge a(N) \ge 3\log_3N$,$\space$ [R. K. Guy, Unsolved Problems in Number Theory, Sect. F26.].
If $N_0$ some number, notice that $a(N_0)$ defines the price of building $N_0$, in terms of the amount of digits. And since the price $a(N)$ is bounded above by a monotone increasing function, if we can build $N_0$ with at least the bound given amount of digits, we can also build numbers $1,\dots, N_0$ with that many or less digits, thus $N\ge N_0$.
Also, an important fact is that if we can build $N_0$ with $n$ digits, we can build it with $\ge n$ digits as well. This is due to optimal $d$ being a set of $1$'s for restricted $\overline{f_d}$, so we can multiply two digits $1$'s to reduce the case of digits, down to $n$, for every case $\gt n$.
So, by the definition of $a(N)$ and $\overline{f}(n)$ we have:
$$\begin{array}{} k(N)\ge a(N_0) \implies \overline{f}(k(N_0))\ge N_0 \\ \end{array}$$
So we can use the result on bounds of $a(N)$ to establish:
$$ 5\log_3N_0 \ge a(N_0) \implies \overline{f}(5\log_3 N_0)\ge N_0 \implies \overline{f}(n)\ge 3^{n/5} $$
By substitution $n=5\log_3 N_0\implies N_0=3^{n/5}$. We have obtained:
An exponential lower bound for the original problem, $f(n)\ge 3^{n/5}$ follows from $f(n)\ge\overline{f}(n)$.
Questions regarding bounds
Can we improve this by getting a "non-weak", and better bound? - Perhaps use the fact that $(-,\div)$ allows extending the explicit construction I mentione earlier for lower linear bound, like user @Countingstuff mentiones in the comments?
Can we obtain non-trivial upper bounds?
A trivial upper bound can be the upper bound on number of (not necessarily consecutive) distinct positive integers that can be built with the given operations and $n$ digits.
I'm not sure how I would establish a non-trivial upper bound. - Bound that uses the fact that integers are consecutive. Idea is to find upper bound on the "hole" that breaks the consecutive sequence?
Partial answers answering any point of this question are appreciated, such as:
proving $f(4)=52$ is optimal or finding a better set of digits that gives a new record.
optimizing the search, (allowing to) find significant records for individual $f(n)$, for $n\ge 5$.
showing better non-trivial upper, lower bounds for $f(n)$ hold.
from Hot Weekly Questions - Mathematics Stack Exchange from Blogger https://ift.tt/2YYXPEf
0 notes
hannahlearnsthings · 8 years ago
Text
Chapter 2 Notes - Think Python
Chapter 2 Variables, expressions and Statements One of the most powerful features of a programming language is the ability to manipulate variables. A variable is a name that refers to a value 2.1 Assignment statements An assignment statement creates a new variable and gives it value. Example: >>>message='And now for something completely different >>>n=17 >>>pi=3.14 This example makes three assignments. The first assigns a string to a new variable named message. The second statement gives the integer 17 to n. The third assigns a value to pi. A state diagram is a written way of representing variables. it shows the name with an arrow pointing to its value.
2.2 Variable names Programmers generally choose names for their variables that are meaningful. Variable names: Can be as long as you like can contain both letters and number can use uppercase letters (but normally do noy) can use underscore character (_) your_name airspeed_of_unladen_swallow Things that will make a variable name illegal starting a name with a number >>>76trombones='big parade' SyntaxError: invalid syntax Using an illegal character >>>more@=10000 SyntaxError: invalid syntax Using a keyword >>>class='Advanced Theoretical Zymurgy' SyntaxError: invalid syntax The interpreter uses keywords to recognize the structure of the program. They cannot be used as variable names There are 33 keywords for Python. It is not necessary to memorize the list. Keywords are often displayed in a different color. If you try to use one as a variable name, you'll know. 2.3 Operators and operands Operators: special symbols that represent computations like addition and multiplication. Operands: the values the operator is applied to In Python 2, the division operator works differently than how you'd expect. >>>minute=59 >>>minute/60 0 This reason for the discrepancy is because Python is performing floor division. When both operands are integers, the result is also an integer Floor division rounds down to the nearest integer (0) In Python 3, the result of the same division is a float. If either of the operands is a floating-point number, Python performs floating-point division, and the result is a float >>> minute/60.0 0.98333 2.4 Expressions and Statements Expression: a combination of values, variables and operators. A value alone can be an expression A variable alone can be an expression Statement: A unit of code that the Python interpreter can execute So far we have seen two kinds of statements: print assignment Technically and expression is also a statement. The important difference is that an expression has a value; a statement does not. 2.5 Interactive mode and script mode When you work with the interactive mode, you can test bits of code before putting them into a script. If using Python as a calculator: In Interactive mode: >>>miles=26.2 >>>miles*1.61 42.18 The first line assigns a value to miles. But has no visible effect. The second line is an expression, so the interpreter evaluates it and displays the result. In script mode: miles=26.2 print miles*1.61 You get no output at all. In script mode, an expression, all by itself, has no visible effect. Python actually evaluates the expression, but it doesn't display the value unless you tell it to. A script usually contains a sequence of statements. If there is more than one statement, the results appear one at a time as the statements execute. For example the script print 1 x=2 print x Produces the output 1 2 The assignment statement produces no output 2.7 Order of operations Rules of Precedence determine the order of evaluation. Python follows the same rules of precedence as in math. The acronym PEMDAS helps to remember this. Parentheses Exponentiation Multiplication and Division Addition and Subtraction Operators with the same precedence are evaluated from left to right
2.8 String operations In general, you can't perform mathematical operations on strings, even if the strings look like numbers. So, the following are illegal: '2'-'1' 'eggs'/'easy' 'third'*'a charm' The operator works with strings in an unexpected way. It performs concatenation: which means joining the strings by linking them end-to-end. For example: first='throat' second='warbler' print first+second The output of this program is throatwarbler The * operator also works on strings, but it performs repetition For example: 'spam'*3 is 'spamspamspam' If one of the operands is a string, the other has to be an integer
2.9 Comments Because of how dense programs are,it is wise to add note4s to programs to explain in natural language what the program is doing. These are called comments and they start with the # sign percentage=(minute*100) #percentage of an hour Everything from the # to the end of the line is ignored-it has no effect on the execution of the program Comments are most useful when they document non-obvious features of the code It is reasonable to assume the reader can figure out what the code does; it is more useful to explain why This comment with the code is redundant and useless: v=5 #assign 5 to v This comment contains useful information that is not in the code v=5 # velocity in meters/second Good variable names can reduce the need for comments, but long names can make complex expressions hard to read, so there is a tradeoff
2.8 Debugging Three kinds of errors can occur in a program Syntax errors: "Syntax" refers to the structure of a program and the rules about that structure. Parentheses have to come in matching pairs. If one is missing, there is a syntax error If there is a syntax error anywhere in your program, Python displays an error message and quits. You will not be able to run the program. Runtime errors: Called "runtime" errors because the error does not appear until after the program has started running. These errors are also called exceptions because they usually indicate that something exceptional (and bad) has happened These errors are rare in simple programs Semantic error "Semantic" referring to meaning. If there is a semantic error in your program, it will run without getting error messages, but it will not do the right thing. It will do something else Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing
2.9 Glossary variable: a name that refers to a  value assignment: a statement that assigns a value to a variable state diagram: a graphical representation of a set of variables and the values they refer to keyword: a reserved word that is used to parse a program; you cannot use keywords like if, def and while as variable names operand: one of the values on which an operator operates expression: a combination of variables, operators and values that represents a single result evaluate: to simplify an expression by performing the operations in order to yield a single value statement: a section of code that represents a command or action. So far, the statements we have seen are assignments and print statements execute: to run a statement and do what it says interactive mode: a way of using the Python interpreter by typing code at the prompt script mode: a way of using the Python interpreter to read code from a script and run it script: a program stored in a file order of operations: rules governing the order in which expressions involving multiple operators and operands are evaluated concatenate: to join two operands end-to-end comment: information in a program that is meant for other programmers (or anyone reading the source code) and has no effect on the execution of the program syntax error: an error in a program that makes it impossible to parse (and therefore impossible to interpret) exception: an error that is detected while the program is running semantics: the meaning of a program semantic error: an error in a program that makes it do something other than what the programmer intended
2.10 Exercises 2.1 We've seen that n=42 is legal. What about 42=n? There is a syntax error. It says it "can't assign to literal" This is because it started with a number How about x=y=1? This is legal, and same for y=x=1, it is only illegal if you start with 1 In some languages, every statement ends with a sem-colon ; What happens if you put a semi-colon at the end of a Python statement? In a math statement, it completes it. In a print statement, it give you a Syntax Error, stating "EOL while scanning string literal" What if you put a period at the end of a statement? In a math statement, it gives you a floating-point number In a print statement, it is a syntax error, saying "invalid syntax" In math notation, you can multiply x and y like this: xy.  What happens if you try that in Python? It gives you a Name Error, saying xy is not defined Exercises 2.2 The volume of a sphere with radius r is 4/3pir^3. What is the volume a sphere with radius 5? >>> r=5 >>> r^3 6 >>> r**3 125 >>> 4/3*3.14159*r**3 523.5983333333332 >>> Suppose the cover price of a book is $24.95, but book stores get a 40% discount. Shipping costs $3 for the fist copy and $.75 for each additional copy. What is the total wholesale cost for 60 copies? bookCost = 24.95 numBooks = 60.0
def cost(numBooks):    bulkBookCost = ((bookCost * 0.60) * numBooks)    shippingCost = (3.0 + (0.75 * (numBooks - 1)))    totalCost = bulkBookCost + shippingCost    print 'The total cost is: $', totalCost
cost(numBooks) If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast start_time_hr = 6 + 52 / 60.0 easy_pace_hr = (8 + 15 / 60.0 ) / 60.0 tempo_pace_hr = (7 + 12 / 60.0) / 60.0 running_time_hr = 2 * easy_pace_hr + 3 * tempo_pace_hr breakfast_hr = start_time_hr + running_time_hr breakfast_min = (breakfast_hr-int(breakfast_hr))*60 breakfast_sec= (breakfast_min-int(breakfast_min))*60
print ('breakfast_hr', int(breakfast_hr) ) print ('breakfast_min', int (breakfast_min) ) print ('breakfast_sec', int (breakfast_sec) ) >>>
I still need to figure out how to take my notes and keep their formatting when I paste on to here. That will come someday, but for now, let’s keep learning!
2 notes · View notes
felord · 6 years ago
Text
Assignment 2 COMP 250    Solved
  Introduction
In your usage of Java language so far you have come across various programming constructs such as variables, operators, control flow statements etc. Similar constructs are present in many other programming languages. In this assignment, you will deal specifically with expressions and their evaluation. You will parse expressions and evaluate them using a stack. An expression is a programming language construct which evaluates to a single value. It is composed of different elements such as constants, variables, operators, method calls etc, put together according to the syntax of the language. For example (2 + 3) in Java evaluates to a single value 5 and is composed of operator + and constants 2 and 3. A similar expression in a different programming language may follow different syntax. For example in Lisp the expression is written as (+ 2 3) .
Assignment
Your task in this assignment is to evaluate arithmetic expressions and calculate their values. The statements are written in a programming language whose syntax is described below. You will use Java to write a parser and an evaluator for expressions written in this language. For simplicity you will only deal with input expressions that are composed of positive integers and the operators that are listed below. + addition ++ increment – subtraction – – decrement * multiplication absolute value / integer division     You may assume that values of expressions are of type int in Java and are within the range specified by that type. Since the subtraction operator is included in the list below, the value of an expression can be either positive or negative. Increment or decrement operations on constants are not allowed in Java. But our language does allow it. In particular, our language has the pre-increment operation which increments values of an integers or an expression, and similarly it has the pre-decrement operation which decrements values. For example, the value of “(++5)” is “6” while expression “(– –(9))” evaluates to 8. Note that operators +, –, *, / are binary operators, i.e, they operate on two elements and produce a value, whereas the operators ++, – – and are unary operators, i.e, they operate on a single element and produce a value. Consider an expression “(++(3 + 2))” in our language. The binary operator “+” operates on two int values 2 and 3 and produces 5. The unary operator “++” then operates on the result 5, a single value, and produces 6 which is the value of the expression. Similarly “((++(5 - 2)) + 3)” evaluates to 7. The absolute value operator is denoted by , instead of the | | which is generally used in arithmetic. We use the square brackets because they have a left and right versions which makes parsing easier. An expression within the operator evaluates to its absolute value. Note that no such operator exists in Java. See Table 1 for more examples of expressions.
Formal language
Your task in this assignment is to write code to parse and evaluate expressions. You can assume that your code will only be tested on valid expressions. But how can we define what a valid expression is? As you will learn if you take COMP 330 and later a compilers course such as COMP 520, there are formal methods for defining languages. Indeed most programming languages are defined using these formal methods. The syntactic rules for expressions and operators in our expression language can be defined as follows. A digit is defined: digit = 0 | 1 | 2 | ... 9 The vertical bar | does not appear in expressions. Rather it is used here to mean or, that is, a digit can be any one of the characters ‘0’, ‘1’,.. ‘9’. Using the definition of a digit, we can then define a positive integer in a recursive manner as follows, positiveInteger = digit | digit positiveInteger so a positive integer is a digit or a digit followed by a positive integer. Notice that in this definition we allow positive integers to start with digit ‘0’, but you can redefine a positive integer to exclude this case if we wish. We can also define operators IncDecOperator = + + | − − binaryOperator = + | − | ∗ | / In a similar manner we define an expression as follows: expression = ( positiveInteger binaryOperator positiveInteger ) | ( expression binaryOperator positiveInteger ) | ( positiveInteger binaryOperator expression ) | ( expression binaryOperator expression ) | ( IncDecOperator positiveInteger ) | ( IncDecOperator expression ) | | An expression is therefore one of the following: a positive integer or an expression followed by a binary operator followed by a positive integer or an expression, enclosed within round brackets an increment or decrement operator followed by a positive integer or by an expression, enclosed within round brackets. an expression or a positive integer, enclosed within square brackets Note that a valid expression is always contained within brackets. Thus “(3+1)” is a valid expression but “3+1” is not. This requirement on the brackets ensures that there is a unique order for evaluating the (sub)expressions in the case that an expression has multiple operators. We will return to this issue later in the course when we discuss expression trees. In your solution, you may assume that each expression has been parenthesized with proper nesting. Therefore, you don’t need to worry about operator precedence issues nor checking for balanced parenthesis. Table 1 below lists some valid expressions and their respective values Expression Evaluated Value (2 / 3) 0 ((- -(2 + 3)) - 1) 3 (++((7 - 2) * 3)) 18 () 9 ((7 - 2) * (++(4 - 3))) 10 Table 1: Example expressions with corresponding values
Parsing
Your first task is to parse in input expression string into meaningful units called tokens. Parsing will take an expression as a string and return an array list of the tokens in the expression, such that each token is string. We use an array list because it is more efficient than a linked list in certain situations. Thus, the expression “(27 + 572)” should be parsed into the list of five tokens: “(”, “27”, “+”, “572”, “)”. Note that white spaces in an expression string must be ignored when parsing. We can then take this list of tokens as input to the eval() method. It is important that for any expressions containing the “++” and “– –” operators be stored as a single token rather than as two. Thus, “(++25)” should be parsed as “(”, “++”, “25”, “)” rather than “(”, “+”, “+”, “25”, “)”. Also note that “25” must be not be parsed as “2”, “5”. The parsing is done in the Expression constructor. You will need to fill in the missing code where it is indicated. You should use the Java StringBuilder class to build each token as you parse the expression string. The append() and delete() methods of the StringBuilder class will be helpful in tokenizing the string.
Evaluation
The evaluation is done in the eval method. Again, your task is to fill in the missing code where it is indicated. The easiest approach is to use two stacks, one to store values (named valueStack in the starter code) and another (named operatorStack) to store tokens such as operators or brackets. We emphasize that you may assume that all expressions are valid; that is, they are syntactically correct and will evaluate to a single value. HINT: Considering that all expressions are syntactically correct, there is no need to store the opening bracket of an expression in the stacks.
Testing
We provide an additional tester class to test your expression class along with sample testing files (sample in.txt, sample value.txt) which test for simple expressions only. Your code will be evaluated on a much more extensive and challenging set of test cases, and we encourage you to post complicated test cases on the discussion board.
Grading
Your grade will be based on the number of test cases passed. No points for code-style or readability, though you should comment your code for your own benefit. a) Implement parser in the Expression constructor (40 points) b) Implement support for operators +, –, *, / (20 points) c) Implement support for operators – – and ++ (20 points) d) Implement support for operator (20 points)
Other Specifications
All your code should be written in the Expression.java file. Submit a file A2.zip which contains only the file Expression.java . Only add code where it is indicated. Do not add import statements. You can use whatever package statement you want. The grading software will remove it. Good luck and have fun! Read the full article
0 notes
gethealthy18-blog · 6 years ago
Text
This Math Equation Is Leaving Netizens Puzzled. Can You Solve It?
New Post has been published on http://healingawerness.com/getting-healthy/getting-healthy-women/this-math-equation-is-leaving-netizens-puzzled-can-you-solve-it/
This Math Equation Is Leaving Netizens Puzzled. Can You Solve It?
Chaitra Krishnan Hyderabd040-395603080 August 2, 2019
Mathematics is a funny language and we’ve always wondered why we were taught so many equations and rules that never helped us solve any of our real life problems. Well, now that the internet is going gaga over tricky Math problems every now and then, you might want to regret not paying attention in Math class back in your school days. All jokes aside, Math is a wonderful and useful subject in many ways (at least for some people) and the viral equations that have taken over the internet is proof to that. Just a couple of days after the ‘230 – 220 x 0.5 = 5’ equation went viral on the internet, here’s a new one to light fire in your brain. “8/2(2+2) =?” — sounds like a very simple equation, isn’t it? We all thought it was until we got to know the real answer. Read on to know more about this brain-racking equation that zombied back from your Algebra classes!
BODMAS And PEMDAS
Remember BODMAS/ PEMDAS? No? Well, neither did we. But you have to brush up a little on the order of operation keys to find out the answer for the equation. BODMAS stands for Bracket-Order-Division-Multiplication-Addition-Subtraction and PEMDAS stands for Parentheses-Exponent-Multiplication-Division-Addition-Subtraction. These represent the order in which you solve a mathematical equation.
While BODMAS is what’s mostly used by the British, PEMDAS is its American counterpart. However, BODMAS and PEMDAS are believed to be the same. Wait, what? You must be wondering how that’s possible because in PEMDAS, multiplication comes first and division comes next whereas it’s the other way around in BODMAS. Well, brace yourself because division and multiplication are interchangeable according to Mathematicians! Now, we don’t want to get into the details of it, but know that this is the essence.
Solving The Equation
Now that we’ve refreshed our minds a bit about the order of operation, let’s get back to the viral equation that has left the smartest of the netizens scratching their heads. Let’s take a look at how most of us would solve this equation:
8/2(2+2) = ?
Step 1: 8/2×4= ?
Step 2: 4×4=16
We solved the (2+2) first because that’s what’s inside the brackets and brackets come first according to the BODMAS rule. Now, we divided 8/2 because division comes first according to this rule. And then multiplied the answer 4 by 4 again to get the final answer as 16. Tadaa! The problem is solved. Now, type the equation in your calculator and see if you’ve gotten the right answer or not.
Even if 16 seems to be a pretty easy and clear answer, why is your scientific calculator showing 1?
Now try working the equation in the PEMDAS way:
8/2(2+2) =?
Step 1: 8/2×4=?
Step 2: 8/8= 1
So we guess those who followed by the PEMDAS rule got it right. But how? Because we thought that BODMAS and PEMDAS are the same? This is the evil beauty of this equation.
Now there’s a second explanation from some people about how the equation turned out to give 1 as the answer.
8/2(2+2) =?
Step 1: 8/ 2(4) =? (Here you retained the bracket after the addition)
Step 2: 8/8=1
After the first step, if you keep the answer 4 within the brackets, you’ll have to do the 2 (4) next to get rid of the “()” according to BODMAS. This is how you get 8/8 and the final answer as 1.  Gosh! Aren’t you grateful that you don’t have to solve algebraic equations at work?
Twitterati is already going crazy trying to solve this equation and there are different answers popping up on the social media site from all over the world. @SoWhAT9000 tweeted:
“You will have to distribute the 2 first to get rid of parenthesis.
8/2(2)
2(2)=8
So now that the parenthesis is no longer on the equation you continue with PEMDAS from left to right
8/8=1
From what I recall the professor saying is multiplication always comes first.”
The Frustrated Netizens
via GIPHY
The equation has not only made people blow their brains out, but also argue with each other to justify their method of problem-solving.
@hidaaya tweeted: “Y’all are so annoying. The P in PEMDAS signifies completing the expression within parenthesis… once that is done you go left to right doesn’t matter if there is an integer embodied in an parenthesis. It doesn’t need further computation. You’re just putting it in () for show.”
To which many users disagreed and obviously lashed out at her including @GeniusUnleashed who replied, “If you typed that whole thing to say that answer isn’t one you don’t understand algebra. 2 x (2+2) is a different equation than 2(2+2). The first doesn’t interact with parenthesis, the second does.”
Now there is a third group of people who stay away from the arguments and are totally confused. Hands (or heads) down we’re in that group too. Now you try to find an explanation for your method of solving this equation and we’ll go put out the fire on our heads.
The following two tabs change content below.
Latest posts by Chaitra Krishnan (see all)
Chaitra Krishnan
Source: https://www.stylecraze.com/trending/math-equation-is-leaving-netizens-puzzled/
0 notes
baburaja97-blog · 8 years ago
Text
New Post has been published on Vin Zite
New Post has been published on https://vinzite.com/slight-exertion-with-objective-c-for-iphone-development/
Slight Exertion With Objective-C For iPhone Development
Introduction
Objective-C is a programming language designed to enable sophisticated object-oriented programming; it is nothing more than a superset of the C programming language and it supports all the basic syntax of the C language, which means that theoretically a program written in C should compile as an Objective-C program without any change.
Most object-oriented environments which is provided for the development consist of several parts, some of them are:
A language which is object-oriented programming
A library of objects
A package of development tools
A runtime environment
What will you need?
I will not focus on building iPhone applications throughout this tutorial because first you learn the programming language used in the iPhone app development. This tutorial will concentrate more on the language (Objective-C) basic concepts and for that you just need a Mac with a compiler like GNU Compiler Collection (GCC).
If you have already installed the Xcode package and Interface Builder from Apple’s Site then GCC was automatically installed. If not, then first you will need to register for an Apple Developer Connection account. Once you have registered, login and click Download Software then in Developer Tools you can download the required software.
Windows users (which is unlikely because this tutorial is written aimed at iPhone developers) can also compile Objective-C on your system using CygWin or the MinGW compiler.
Here you will learn the skills necessary to program in Objective-C using a style that is easy to follow, rich in examples and accessible to those who have never used Objective-C before.
Here we covered the fundamentals of Objective-C and object oriented programming. So, for that let’s quickly look at the predefined Data Types and Operators of Objective-C.
List of data types and qualifiers supported by Objective-C
int Data Type
char Data Type
float Data Type
double Data Type
id Data Type
BOOL Data Type
Special Characters/Escape Sequences
a – Sound alert
b – Backspace
f – Form feed
n – New line
r – Carriage return
t – Horizontal tab
v – Vertical tab
– Backslash
” – Double quote (It is using when we want to place a double quote into a string declaration)
‘ – Single quote (It is using when we want to place a double quote into a string declaration)
Objective-C Data Type Qualifiers
long
long long
short
signed / unsigned
Now you we will look the list of Objective-C Operators
Arithmetic Operators
Operator Description
-(unary) Negates the value
* Multiplication
/ Division
+ Addition
– Subtraction
% Modulo
Assignment Operators
Compound Assignment Operators
Operator Description
x += y It is used to Add x and y, and store result in x.
x -= y It is used to Subtract y from x and store result in x.
x *= y It is used to Multiply x by y and store result in x.
x /= y It is used to Divide x by y and store result in x.
x %= y It is used to Modulo on x and y and store result in x.
x &= y Send the result to x of logical AND operation on x and y.
x |= y Send the result to x of logical OR operation on x and y.
x ^= y Send the result to x of logical Exclusive OR on x and y.
Increment and Decrement Operators
Comparison Operators
Operator Description
x == y True if x is equal to y.
x > y True if x is greater than y.
x >= y True if x is greater than or equal to y.
x >= n Shift x right by n places and send result to x.
Objective-C requires the interface, implementation and instantiation of a class to be in separately declared code blocks which use the file extensions (I will describe that in detail later in this article): Extension
Source type .h It holds the class, type, function, and constant declarations. .m It holds the source files and can contain both Objective-C and C code. .mm It contain C++ code in addition to Objective-C and C code. This extension should be used only if you actually refer to C++ classes or features from your Objective-C code.
First Program: Welcome Objective C
Starting with a simple “Welcome Objective C” program as I am written this tutorial for iPhone Development, I choose Xcode for creating Objective-C programs. Start writing the program by launching Xcode; you just need to choose the “Foundation Tool” under “Command Line Utility” and give a name to your program. For example I chose here “WelcomeObjectiveC”, now the project window will open and you will see the highlighted file, “WelcomeObjectiveC.m”, start writing your program in this file.https://vinzite.com/wp-content/uploads/2017/03/AAEAAQAAAAAAAAesAAAAJGRhNWM0NGFhLTEzZjktNDk1ZC1iZGNhLWZlMzcyMGY4YTJhMw-3.jpg
Example #import int main (int argc, const char *argv[])
NSLog (@”Welcome, Objective C”);
return (0);
Now first build the program and then run it by clicking the Build and Go button or pressing. If there aren’t any nasty errors in your program, Xcode successfully compiles and runs your program.
To see the output of your program, open the Xcode console window. You can open the console window by selecting Console from the Run menu or pressing.
And there you have the output in the console window: Welcome, Objective C
Now see how the code works.
In the first line I import the Foundation.h file and this whole import statement informs the compiler to look at the Foundation.h header file in the Foundation framework.
Now you ask what is Foundation Framework? OK, first see what is Framework: A framework is a collection of parts-header files, libraries, images, sounds, and more-collected together into a single unit.
Foundation Framework: The Foundation framework defines a base layer of Objective-C classes and the Foundation framework is designed with these goals in mind (said by Apple):
It is provides a small set of basic utility classes used in the programs.
Introduces consistent conventions such as Deallocation which make software development easier.
Supports Unicode strings, object persistence, and object distribution.
Provide a level of OS independence, to enhance portability.
Next is Main Function int main (int argc, const char *argv[])
//Function Code
The main function (as in standard C) tells the Objective-C compiler where to start program execution. In the main function you see the various fields as follows:
return type: Specifies the data type of the result returned by the function. If the function does not return a result then void should be specified.
function name: It is the name by which the function will be referenced when it is called from within the application code. Note that, unless otherwise specified using the static specifier, function names are global and must be unique within the context of an application to avoid compilation errors.
argn type: The type of the argument passed through to the function.
argn name: The name by which the argument is to be referenced in the function code.
Now comes to NSLog() and @”strings” NSLog (@”Welcome, Objective C”);
Here NSLog() is a Cocoa function which is used to print the value in Objective-C. In NSLog we pass the string between double quotes started with @ symbol that is represent as Objective-C language keywords.
After execution of main() is finished the zero value is returned by a “return (0);” statement which says that our program completed successfully.
Interface, Implementation and Instantiation
You can use Objective C to develop full fledged iPhone applications; it revolves around objects. It has three parts:
Interface
Implementation
Instantiation
Interface
Interface is a object class in Objective-C, by convention, developers place the interface in a header file, it contains the class declaration and defines the instance variables and methods associated with the class. The interface is suffixed by.h, parentheses contained all the variables which is associated with the interface, but the methods are declared outside of the parentheses, yet still inside the structure formed by an opening @interface and a closing @end.
Structure of Interface @interface Fraction: NSObject
// instance variables
int numerator;
int denominator; -(void) setNumerator: (int) num; -(void) setDenominator: (int) den; -(void) print; @end //Fraction
Code Walk
Start from the first line: @interface Fraction: NSObject
The above line of code informs the compiler that a new interface for a new class named Fraction is created and NSObject specifies that the Fraction class is based/inherited from the NSObject class.
// instance variables
int numerator;
int denominator;
Now to the template design; the above is a template we create within curly braces which is used to work with the Fraction object. Here we declare two elements numerator type-of integer and denominator again type-of integer, we can say they are instance variables to these elements.
When we talk about the variable declaration, first we need to tell the compiler what we’re going to store and in what type-of. Here are some of the most important variables types that you should know about for now:
int: For storing integers (numbers with no decimal point).
char: For storing a character.
float: For storing numbers with decimal points.
double: Same as a float but double the accuracy.
Now come to method declaration. -(void) setNumerator: (int) num; -(void) setDenominator: (int) den; -(void) print;
The above code lines are just method declarations. In a method declaration you have to give the name of each method, the method’s return type, and any arguments. But the above code looks a little different; not a simple method declaration, isn’t it? Yep, first remember that methods are of two types and the defining syntax is also two types:
First which are defined using the plus sign (+)
Second which are defined using the negative sign (-)
What is difference between these two methods? Methods which define using the plus sign (+) are class methods, they operate on all instances of the interface. They do not have access to any specific instance variables defined in the interface. Methods defined using the negative sign (-) are instance methods, they operate on a specific instance of the interface. They can access the variables associated with an instance of the interface.
Returning to the previous code, in the first two lines we just start the method declaration with a leading dash sign and the return type is in parentheses then the name of the method “setNumerator and setDenominator” then the trailing colon after the method name is a hint to compilers and humans that a parameter is coming next, then the type of the argument is in parentheses and at last the parameter name exists.
In the last line of the method declarations part we just print without returning anything. @end // Fraction
We write the above line at the end; it ends the declaration of the Fraction class.
Implementation
After the interface declaration let’s proceed to the implementation of the interface; as you have learned the interface only declares the class interface and not the methods themselves; the actual code is written in the implementation. Implementation (method) files normally have the file extension.m. Interface implementation is like definition of the interface. All implementations are contained within an @implementation… @end block. One more thing that must be done when the implementation is done, that is importing the interface.
Structure of implementation #import @implementation Fraction} -(void) print
printf( “%i/%i”, numerator, denominator ); -(void) setNumerator: (int) numN
numerator = numN; -(void) setDenominator: (int) denD
denominator = denD; @end
Code Walk
Start from the first line: #import
As I already explained the Objective-C interface definition was contained in the file “Fraction.h”. At the time of implementation we need to import this file at the beginning such as shown in the above code. Why? To include any module that creates an instance of the class, sends a message to invoke a method declared for the class, or mentions an instance variable declared in the class.
Implementation for class Fraction @implementation Fraction
In the above code @implementation is a directive which introduces the code for the guts of a class. After witting @implementation we write the name of the class. There is no trailing semicolon on this line, because you don’t need semicolons after Objective-C directives.
Now define the individual methods -(void) print
printf( “%i/%i”, numerator, denominator ); -(void) setNumerator: (int) numN
numerator = numN; -(void) setDenominator: (int) denD
denominator = denD;
In the first line we print the values and you will see a sign of “%i” that is a formatting sign used because we were including an integer. Other variables have their own format specifiers:
%i: integer
%f: float
%e: double
%c: char
That actually implements the methods; in the above code we declared methods in the same manner as in the interface file, but without the semicolon. One thing more to notice here is that we renamed the parameters because it’s better for the parameter names to differ between the @interface and the @implementation. Then inside the body of the method code will refers to the instance variables.
The last line: @end
Closes the block of implementation.
Instantiation
When you are using Objective-C on the iPhone you will need to allocate memory as well as create an object. To allocate memory you send an alloc message to the class itself; this process is called instantiating. When you instantiate an object, memory is allocated, and then that memory is initialized to some useful default values; that is, something other than the random values you get with freshly allocated memory.
Structure of Instantiation int main( int argc, const char *argv[] )
// creating a new instance
Fraction *frac = [[Fraction alloc] init];
// set values
[frac setNumerator: 2];
[frac setDenominator: 5];
// simple print
printf( “The value of fraction is: ” );
[frac print]; printf( “n” );
// release the memory
[frac release];
return 0;
Here the output will be: The value of fraction is: 2/5
Code Walk
Instance Creation Fraction *frac = [[Fraction alloc] init];
The above is how you instantiate an object, here we will use a constructor that is generally prefixed with the word “init” or simply init. An initializer returns an instance – usually the same instance, initialized. Therefore you can, and always should, call alloc and the initializer in the same line of code.
Set the values [frac setNumerator: 2]; [frac setDenominator: 5];
The above code line is just simply calling the setNumerator and setDenominator method on frac, and passing it the parameter 2 and 5.
Printing printf( “The value of fraction is: ” ); [frac print]; printf( “n” );
This is simply calling the print method on frac and prints the values/output.
Free the memory [frac release];
When using Objective-C on the iPhone you must release objects that you have created using alloc, new or copy. This has to do with memory management. This is also functionally equivalent to C/C++; all three languaes do not use garbage collection. To release an object you simply send the “release” message to the object.
Let’s Program with Multiple Parameters
In Objective-C you can use a method with multiple parameters. These parameters can be of the same type or of a different type.
Let’s look at an example to clarify use of multiple parameters:
In class.h #import @interface Class:NSObject
// declare method for multiple parameter
-(int) sub: (int) i andj: (int) j andk:(int)k; @end
The main thing is that the separator in the arguments are “:”; you can set any number of arguments using “:”.
In class.m #import #import”Class.h” @implementation MyClass -(int) sub: (int) i andj: (int) j andk:(int)k;
return i+j+k; @end
In main #import #import”Class.m” int main()
Class *class = [[Class alloc]init];
printf(“Subtraction is: %d”,[class sub: 16 andj: 8 andk:5]);
[class release]; return;
The Output is: Subtraction is: 3
Designated Constructor
Constructors are to create and initialize an instance of a class. For a class, there can be multiple constructors with various parameters expecting some initial variables. But in Objective-C, first you allocate memory on the heap. Next you call a method called an initializer, which is kind of Objective-C’s equivalent of a constructor.
See the Example
Class Header: Employee.h #import @interface Employee: NSObject
NSString* name;
int age;
int mobileNumber;
Class Implementation: Employee.m #import “Employee.h” @implementation Employee -(id)init
self = [super init];
if(self)
//Initialization code here.
name=@””;
age=0;
mobilenumber=0;
return self; @end
Code Walk
First I created a standard Employee class; it does not consist of any methods, just some simple member variables; namely name, age, and mobilenumber.
Then in the implementation you see a method called “init”. It is the standard initializer method that Xcode creates as a boilerplate for each new class file you create, this method is used to initialize a newly created object and put it into a safe state, exactly as constructors do in C# or C++.
Access Privileges
In Objective-C, access privilege can only be specified on variables. Default access in objective-C is @protected. Types of access privileges are:
@public
@private
@protected
The @protected accessor enables access elements in the subclass.
Exception handling
Using GNU Compiler Collection (GCC) version 3.3 and later, Objective-C provides language-level support for exception handling. An exception is a special condition that interrupts the normal flow of program execution. There are a variety of reasons why an exception may be generated. It works like in every other modern language: they are represented by classes inheriting (usually) from NSException.
NOTE: Exception handling is only supported in Mac OS X 10.3
Compiler directives used for exception handling:
@try: block which throws an exception.
@catch: defines how to handle exceptions thrown by a try block; this is usually an NSException object.
@finally: it is executed whether an exception is thrown or not.
@throw: once your program detects an exception, it must propagate the exception to code that handles it. This code is called the exception handler. This entire
process of propagating an exception is referred to as “throwing an exception”.
Exception-Handling Algorithm mug *mug = [[mug alloc] init]; @try
[mug fill]; @catch (NSException *exception)
NSLog(@”main: Caught %@: %@”, [exception name], [exception reason]); @finally
[mug release];
Catching the Exception @try … @catch (CustomException *cex) … @catch (NSException *nex)
// Processing necessary at this level… @catch (id uex) … @finally
// Processing necessary…
Throwing Exceptions NSException *exception = [NSException exceptionWithName: @”MugfullException”reason: @”The mug is full of water”userInfo: nil]; @throw exception;
Inheritance
Inheritance brings something of a real-world view to programming. It allows a class to be defined that has a certain set of characteristics and then other classes can be created derived from that class. The derived class inherits all of the features of the parent class and typically then adds some features of its own. In addition to inheriting from classes we can also extend classes. When we extend a class, we take an existing class and add additional functionality to what is already available.
inheritance.gif
Let?s understand the above diagram, first take NSMutableString. NSMutableString has NSString for a parent, meaning it inherits from NSString. Meanwhile, NSString has NSObject as a parent, so it inherits from NSObject, then NSMutableArray has NSArray for a parent, which means it inherits from NSArray. Meanwhile, NSArray has NSObject as a parent, so it inherits from NSObject, then the last NSNumber has NSValue for a parent, meaning it inherits from NSValue. Meanwhile, NSValue also NSObject as a parent, so it inherits from NSObject.
Is new technology nothing without new terms to learn? Exactly, so here are some new terms of inheritance:
Super class: The superclass is the class you were inheriting from.
Parent class: Another word for “superclass” is Parent class.
Sub class: The subclass is the class doing the inheriting.
Child class: Child class is another word for ”subclass”.
Override: You override an inherited method when you want to change its implementation.
Let’s take a Circle and Rectangle example of see how inheritance works. Look at the following figure, I am going to explain this by example:
inheritance1.gif
In drawing.h @interface drawing: NSObject
DrawShape bounds; – (void) setBounds: (DrawShape) bounds; – (void) draw; @end // drawing
In drawing.m @implementation drawing – (void) setBounds: (DrawShape) b
bounds = b; // setBounds – (void) draw // draw @end // drawing
In Circle.h @interface Circle: NSObject
DrawShapebounds; – (void) setBounds: (DrawShape) bounds; – (void) draw; @end // Circle
In Circle.m @implementation Circle – (void) draw
NSLog (@”drawing a circle at (%d %d %d %d) in %@”, bounds.x,
bounds.y, bounds.width, bounds.height, // draw @end // Circle
In Rectangle.h @interface Rectangle: NSObject
DrawShape bounds; – (void) setBounds: (DrawShape) bounds; – (void) draw; @end // Rectangle
In Rectangle.m @implementation Rectangle – (void) draw
NSLog (@”drawing rect at (%d %d %d %d) in %@”, bounds.x, bounds.y,
bounds.width, bounds.height, // draw @end // Rectangle
In main int main (int argc, const char * argv[])
id shapes[2];
DrawShape shap1 = 5, 5, 20, 40 ;
shapes[0] = [Circle new];
[shapes[0] setBounds: rect0];
DrawShape shap2 = 50, 60, 70, 80 ;
shapes[1] = [Rectangle new];
[shapes[1] setBounds: rect1];
return (0); // main
In the output you will see:
Drawing a circle at (5 5 20 40) Drawing a rectangle at (50 50 60 70)
Memory Management
In the Apple’s library it says “The basic model used for memory management in a reference-counted environment is provided by a combination of methods defined in the NSObject protocol and a standard method naming convention. The NSObject class also defines a method, dealloc, that is invoked automatically when an object is deallocated.”
memory_management.jpg
For memory management you call [obj retain], which increases its “retain count” (number of references); and when you no longer need it, you call [obj release]. When the counter reaches zero, dealloc is then called.
Syntax of dealloc -(void) dealloc
//Message of deallocation.
printf( “Deallocing fractionn” );
[super dealloc];
Commonly used messages in memory management which you send to an abject are:
alloc
new
retain
release
autorelease
copy
Golden Rules of Cocoa memory management:
Retaining the Object: Retaining the object means to increment the retain count of any object and send it the retain message. The retain message increments the object’s reference count, and the release message decrements it.
0 notes